id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_good_296_0 | /*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "git2/types.h"
#include "git2/errors.h"
#include "git2/refs.h"
#include "git2/revwalk.h"
#include "smart.h"
#include "util.h"
#include "netops.h"
#include "posix.h"
#include "buffer.h"
#include <ctype.h>
#define PKT_LEN_SIZE 4
static const char pkt_done_str[] = "0009done\n";
static const char pkt_flush_str[] = "0000";
static const char pkt_have_prefix[] = "0032have ";
static const char pkt_want_prefix[] = "0032want ";
static int flush_pkt(git_pkt **out)
{
git_pkt *pkt;
pkt = git__malloc(sizeof(git_pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_FLUSH;
*out = pkt;
return 0;
}
/* the rest of the line will be useful for multi_ack and multi_ack_detailed */
static int ack_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ack *pkt;
GIT_UNUSED(line);
GIT_UNUSED(len);
pkt = git__calloc(1, sizeof(git_pkt_ack));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_ACK;
line += 3;
len -= 3;
if (len >= GIT_OID_HEXSZ) {
git_oid_fromstr(&pkt->oid, line + 1);
line += GIT_OID_HEXSZ + 1;
len -= GIT_OID_HEXSZ + 1;
}
if (len >= 7) {
if (!git__prefixcmp(line + 1, "continue"))
pkt->status = GIT_ACK_CONTINUE;
if (!git__prefixcmp(line + 1, "common"))
pkt->status = GIT_ACK_COMMON;
if (!git__prefixcmp(line + 1, "ready"))
pkt->status = GIT_ACK_READY;
}
*out = (git_pkt *) pkt;
return 0;
}
static int nak_pkt(git_pkt **out)
{
git_pkt *pkt;
pkt = git__malloc(sizeof(git_pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_NAK;
*out = pkt;
return 0;
}
static int pack_pkt(git_pkt **out)
{
git_pkt *pkt;
pkt = git__malloc(sizeof(git_pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_PACK;
*out = pkt;
return 0;
}
static int comment_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_comment *pkt;
size_t alloclen;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_comment), len);
GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_COMMENT;
memcpy(pkt->comment, line, len);
pkt->comment[len] = '\0';
*out = (git_pkt *) pkt;
return 0;
}
static int err_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_err *pkt;
size_t alloclen;
/* Remove "ERR " from the line */
line += 4;
len -= 4;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len);
GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_ERR;
pkt->len = (int)len;
memcpy(pkt->error, line, len);
pkt->error[len] = '\0';
*out = (git_pkt *) pkt;
return 0;
}
static int data_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_data *pkt;
size_t alloclen;
line++;
len--;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_DATA;
pkt->len = (int) len;
memcpy(pkt->data, line, len);
*out = (git_pkt *) pkt;
return 0;
}
static int sideband_progress_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_progress *pkt;
size_t alloclen;
line++;
len--;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_PROGRESS;
pkt->len = (int) len;
memcpy(pkt->data, line, len);
*out = (git_pkt *) pkt;
return 0;
}
static int sideband_error_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_err *pkt;
size_t alloc_len;
line++;
len--;
GITERR_CHECK_ALLOC_ADD(&alloc_len, sizeof(git_pkt_err), len);
GITERR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, 1);
pkt = git__malloc(alloc_len);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_ERR;
pkt->len = (int)len;
memcpy(pkt->error, line, len);
pkt->error[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
}
/*
* Parse an other-ref line.
*/
static int ref_pkt(git_pkt **out, const char *line, size_t len)
{
int error;
git_pkt_ref *pkt;
size_t alloclen;
pkt = git__malloc(sizeof(git_pkt_ref));
GITERR_CHECK_ALLOC(pkt);
memset(pkt, 0x0, sizeof(git_pkt_ref));
pkt->type = GIT_PKT_REF;
if ((error = git_oid_fromstr(&pkt->head.oid, line)) < 0)
goto error_out;
/* Check for a bit of consistency */
if (line[GIT_OID_HEXSZ] != ' ') {
giterr_set(GITERR_NET, "error parsing pkt-line");
error = -1;
goto error_out;
}
/* Jump from the name */
line += GIT_OID_HEXSZ + 1;
len -= (GIT_OID_HEXSZ + 1);
if (line[len - 1] == '\n')
--len;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->head.name = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->head.name);
memcpy(pkt->head.name, line, len);
pkt->head.name[len] = '\0';
if (strlen(pkt->head.name) < len) {
pkt->capabilities = strchr(pkt->head.name, '\0') + 1;
}
*out = (git_pkt *)pkt;
return 0;
error_out:
git__free(pkt);
return error;
}
static int ok_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ok *pkt;
const char *ptr;
size_t alloc_len;
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_OK;
line += 3; /* skip "ok " */
if (!(ptr = strchr(line, '\n'))) {
giterr_set(GITERR_NET, "invalid packet line");
git__free(pkt);
return -1;
}
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloc_len, len, 1);
pkt->ref = git__malloc(alloc_len);
GITERR_CHECK_ALLOC(pkt->ref);
memcpy(pkt->ref, line, len);
pkt->ref[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
}
static int ng_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ng *pkt;
const char *ptr;
size_t alloclen;
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->ref = NULL;
pkt->type = GIT_PKT_NG;
if (len < 3)
goto out_err;
line += 3; /* skip "ng " */
len -= 3;
if (!(ptr = memchr(line, ' ', len)))
goto out_err;
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->ref = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->ref);
memcpy(pkt->ref, line, len);
pkt->ref[len] = '\0';
if (len < 1)
goto out_err;
line = ptr + 1;
len -= 1;
if (!(ptr = memchr(line, '\n', len)))
goto out_err;
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->msg = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->msg);
memcpy(pkt->msg, line, len);
pkt->msg[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
out_err:
giterr_set(GITERR_NET, "invalid packet line");
git__free(pkt->ref);
git__free(pkt);
return -1;
}
static int unpack_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_unpack *pkt;
GIT_UNUSED(len);
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_UNPACK;
if (!git__prefixcmp(line, "unpack ok"))
pkt->unpack_ok = 1;
else
pkt->unpack_ok = 0;
*out = (git_pkt *)pkt;
return 0;
}
static int32_t parse_len(const char *line)
{
char num[PKT_LEN_SIZE + 1];
int i, k, error;
int32_t len;
const char *num_end;
memcpy(num, line, PKT_LEN_SIZE);
num[PKT_LEN_SIZE] = '\0';
for (i = 0; i < PKT_LEN_SIZE; ++i) {
if (!isxdigit(num[i])) {
/* Make sure there are no special characters before passing to error message */
for (k = 0; k < PKT_LEN_SIZE; ++k) {
if(!isprint(num[k])) {
num[k] = '.';
}
}
giterr_set(GITERR_NET, "invalid hex digit in length: '%s'", num);
return -1;
}
}
if ((error = git__strtol32(&len, num, &num_end, 16)) < 0)
return error;
return len;
}
/*
* As per the documentation, the syntax is:
*
* pkt-line = data-pkt / flush-pkt
* data-pkt = pkt-len pkt-payload
* pkt-len = 4*(HEXDIG)
* pkt-payload = (pkt-len -4)*(OCTET)
* flush-pkt = "0000"
*
* Which means that the first four bytes are the length of the line,
* in ASCII hexadecimal (including itself)
*/
int git_pkt_parse_line(
git_pkt **head, const char *line, const char **out, size_t bufflen)
{
int ret;
int32_t len;
/* Not even enough for the length */
if (bufflen > 0 && bufflen < PKT_LEN_SIZE)
return GIT_EBUFS;
len = parse_len(line);
if (len < 0) {
/*
* If we fail to parse the length, it might be because the
* server is trying to send us the packfile already.
*/
if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) {
giterr_clear();
*out = line;
return pack_pkt(head);
}
return (int)len;
}
/*
* If we were given a buffer length, then make sure there is
* enough in the buffer to satisfy this line
*/
if (bufflen > 0 && bufflen < (size_t)len)
return GIT_EBUFS;
/*
* The length has to be exactly 0 in case of a flush
* packet or greater than PKT_LEN_SIZE, as the decoded
* length includes its own encoded length of four bytes.
*/
if (len != 0 && len < PKT_LEN_SIZE)
return GIT_ERROR;
line += PKT_LEN_SIZE;
/*
* The Git protocol does not specify empty lines as part
* of the protocol. Not knowing what to do with an empty
* line, we should return an error upon hitting one.
*/
if (len == PKT_LEN_SIZE) {
giterr_set_str(GITERR_NET, "Invalid empty packet");
return GIT_ERROR;
}
if (len == 0) { /* Flush pkt */
*out = line;
return flush_pkt(head);
}
len -= PKT_LEN_SIZE; /* the encoded length includes its own size */
if (*line == GIT_SIDE_BAND_DATA)
ret = data_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_PROGRESS)
ret = sideband_progress_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_ERROR)
ret = sideband_error_pkt(head, line, len);
else if (!git__prefixcmp(line, "ACK"))
ret = ack_pkt(head, line, len);
else if (!git__prefixcmp(line, "NAK"))
ret = nak_pkt(head);
else if (!git__prefixcmp(line, "ERR "))
ret = err_pkt(head, line, len);
else if (*line == '#')
ret = comment_pkt(head, line, len);
else if (!git__prefixcmp(line, "ok"))
ret = ok_pkt(head, line, len);
else if (!git__prefixcmp(line, "ng"))
ret = ng_pkt(head, line, len);
else if (!git__prefixcmp(line, "unpack"))
ret = unpack_pkt(head, line, len);
else
ret = ref_pkt(head, line, len);
*out = line + len;
return ret;
}
void git_pkt_free(git_pkt *pkt)
{
if (pkt->type == GIT_PKT_REF) {
git_pkt_ref *p = (git_pkt_ref *) pkt;
git__free(p->head.name);
git__free(p->head.symref_target);
}
if (pkt->type == GIT_PKT_OK) {
git_pkt_ok *p = (git_pkt_ok *) pkt;
git__free(p->ref);
}
if (pkt->type == GIT_PKT_NG) {
git_pkt_ng *p = (git_pkt_ng *) pkt;
git__free(p->ref);
git__free(p->msg);
}
git__free(pkt);
}
int git_pkt_buffer_flush(git_buf *buf)
{
return git_buf_put(buf, pkt_flush_str, strlen(pkt_flush_str));
}
static int buffer_want_with_caps(const git_remote_head *head, transport_smart_caps *caps, git_buf *buf)
{
git_buf str = GIT_BUF_INIT;
char oid[GIT_OID_HEXSZ +1] = {0};
size_t len;
/* Prefer multi_ack_detailed */
if (caps->multi_ack_detailed)
git_buf_puts(&str, GIT_CAP_MULTI_ACK_DETAILED " ");
else if (caps->multi_ack)
git_buf_puts(&str, GIT_CAP_MULTI_ACK " ");
/* Prefer side-band-64k if the server supports both */
if (caps->side_band_64k)
git_buf_printf(&str, "%s ", GIT_CAP_SIDE_BAND_64K);
else if (caps->side_band)
git_buf_printf(&str, "%s ", GIT_CAP_SIDE_BAND);
if (caps->include_tag)
git_buf_puts(&str, GIT_CAP_INCLUDE_TAG " ");
if (caps->thin_pack)
git_buf_puts(&str, GIT_CAP_THIN_PACK " ");
if (caps->ofs_delta)
git_buf_puts(&str, GIT_CAP_OFS_DELTA " ");
if (git_buf_oom(&str))
return -1;
len = strlen("XXXXwant ") + GIT_OID_HEXSZ + 1 /* NUL */ +
git_buf_len(&str) + 1 /* LF */;
if (len > 0xffff) {
giterr_set(GITERR_NET,
"tried to produce packet with invalid length %" PRIuZ, len);
return -1;
}
git_buf_grow_by(buf, len);
git_oid_fmt(oid, &head->oid);
git_buf_printf(buf,
"%04xwant %s %s\n", (unsigned int)len, oid, git_buf_cstr(&str));
git_buf_free(&str);
GITERR_CHECK_ALLOC_BUF(buf);
return 0;
}
/*
* All "want" packets have the same length and format, so what we do
* is overwrite the OID each time.
*/
int git_pkt_buffer_wants(
const git_remote_head * const *refs,
size_t count,
transport_smart_caps *caps,
git_buf *buf)
{
size_t i = 0;
const git_remote_head *head;
if (caps->common) {
for (; i < count; ++i) {
head = refs[i];
if (!head->local)
break;
}
if (buffer_want_with_caps(refs[i], caps, buf) < 0)
return -1;
i++;
}
for (; i < count; ++i) {
char oid[GIT_OID_HEXSZ];
head = refs[i];
if (head->local)
continue;
git_oid_fmt(oid, &head->oid);
git_buf_put(buf, pkt_want_prefix, strlen(pkt_want_prefix));
git_buf_put(buf, oid, GIT_OID_HEXSZ);
git_buf_putc(buf, '\n');
if (git_buf_oom(buf))
return -1;
}
return git_pkt_buffer_flush(buf);
}
int git_pkt_buffer_have(git_oid *oid, git_buf *buf)
{
char oidhex[GIT_OID_HEXSZ + 1];
memset(oidhex, 0x0, sizeof(oidhex));
git_oid_fmt(oidhex, oid);
return git_buf_printf(buf, "%s%s\n", pkt_have_prefix, oidhex);
}
int git_pkt_buffer_done(git_buf *buf)
{
return git_buf_puts(buf, pkt_done_str);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_296_0 |
crossvul-cpp_data_good_3947_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Redirected Parallel Port Device Service
*
* Copyright 2010 O.S. Systems Software Ltda.
* Copyright 2010 Eduardo Fiss Beloni <beloni@ossystems.com.br>
* Copyright 2015 Thincast Technologies GmbH
* Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <fcntl.h>
#include <errno.h>
#ifndef _WIN32
#include <termios.h>
#include <strings.h>
#include <sys/ioctl.h>
#endif
#ifdef __LINUX__
#include <linux/ppdev.h>
#include <linux/parport.h>
#endif
#include <winpr/crt.h>
#include <winpr/synch.h>
#include <winpr/thread.h>
#include <winpr/stream.h>
#include <winpr/collections.h>
#include <winpr/interlocked.h>
#include <freerdp/types.h>
#include <freerdp/constants.h>
#include <freerdp/channels/rdpdr.h>
#include <freerdp/channels/log.h>
#define TAG CHANNELS_TAG("drive.client")
struct _PARALLEL_DEVICE
{
DEVICE device;
int file;
char* path;
UINT32 id;
HANDLE thread;
wMessageQueue* queue;
rdpContext* rdpcontext;
};
typedef struct _PARALLEL_DEVICE PARALLEL_DEVICE;
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp)
{
char* path = NULL;
int status;
WCHAR* ptr;
UINT32 PathLength;
if (!Stream_SafeSeek(irp->input, 28))
return ERROR_INVALID_DATA;
/* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */
/* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */
if (Stream_GetRemainingLength(irp->input) < 4)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, PathLength);
ptr = (WCHAR*)Stream_Pointer(irp->input);
if (!Stream_SafeSeek(irp->input, PathLength))
return ERROR_INVALID_DATA;
status = ConvertFromUnicode(CP_UTF8, 0, ptr, PathLength / 2, &path, 0, NULL, NULL);
if (status < 1)
if (!(path = (char*)calloc(1, 1)))
{
WLog_ERR(TAG, "calloc failed!");
return CHANNEL_RC_NO_MEMORY;
}
parallel->id = irp->devman->id_sequence++;
parallel->file = open(parallel->path, O_RDWR);
if (parallel->file < 0)
{
irp->IoStatus = STATUS_ACCESS_DENIED;
parallel->id = 0;
}
else
{
/* all read and write operations should be non-blocking */
if (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1)
{
}
}
Stream_Write_UINT32(irp->output, parallel->id);
Stream_Write_UINT8(irp->output, 0);
free(path);
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT parallel_process_irp_close(PARALLEL_DEVICE* parallel, IRP* irp)
{
if (close(parallel->file) < 0)
{
}
else
{
}
Stream_Zero(irp->output, 5); /* Padding(5) */
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT parallel_process_irp_read(PARALLEL_DEVICE* parallel, IRP* irp)
{
UINT32 Length;
UINT64 Offset;
ssize_t status;
BYTE* buffer = NULL;
if (Stream_GetRemainingLength(irp->input) < 12)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, Length);
Stream_Read_UINT64(irp->input, Offset);
buffer = (BYTE*)malloc(Length);
if (!buffer)
{
WLog_ERR(TAG, "malloc failed!");
return CHANNEL_RC_NO_MEMORY;
}
status = read(parallel->file, buffer, Length);
if (status < 0)
{
irp->IoStatus = STATUS_UNSUCCESSFUL;
free(buffer);
buffer = NULL;
Length = 0;
}
else
{
}
Stream_Write_UINT32(irp->output, Length);
if (Length > 0)
{
if (!Stream_EnsureRemainingCapacity(irp->output, Length))
{
WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!");
free(buffer);
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write(irp->output, buffer, Length);
}
free(buffer);
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT parallel_process_irp_write(PARALLEL_DEVICE* parallel, IRP* irp)
{
UINT32 len;
UINT32 Length;
UINT64 Offset;
ssize_t status;
void* ptr;
if (Stream_GetRemainingLength(irp->input) > 12)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, Length);
Stream_Read_UINT64(irp->input, Offset);
if (!Stream_SafeSeek(irp->input, 20)) /* Padding */
return ERROR_INVALID_DATA;
ptr = Stream_Pointer(irp->input);
if (!Stream_SafeSeek(irp->input, Length))
return ERROR_INVALID_DATA;
len = Length;
while (len > 0)
{
status = write(parallel->file, ptr, len);
if (status < 0)
{
irp->IoStatus = STATUS_UNSUCCESSFUL;
Length = 0;
break;
}
Stream_Seek(irp->input, status);
len -= status;
}
Stream_Write_UINT32(irp->output, Length);
Stream_Write_UINT8(irp->output, 0); /* Padding */
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT parallel_process_irp_device_control(PARALLEL_DEVICE* parallel, IRP* irp)
{
Stream_Write_UINT32(irp->output, 0); /* OutputBufferLength */
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT parallel_process_irp(PARALLEL_DEVICE* parallel, IRP* irp)
{
UINT error;
switch (irp->MajorFunction)
{
case IRP_MJ_CREATE:
if ((error = parallel_process_irp_create(parallel, irp)))
{
WLog_ERR(TAG, "parallel_process_irp_create failed with error %" PRIu32 "!", error);
return error;
}
break;
case IRP_MJ_CLOSE:
if ((error = parallel_process_irp_close(parallel, irp)))
{
WLog_ERR(TAG, "parallel_process_irp_close failed with error %" PRIu32 "!", error);
return error;
}
break;
case IRP_MJ_READ:
if ((error = parallel_process_irp_read(parallel, irp)))
{
WLog_ERR(TAG, "parallel_process_irp_read failed with error %" PRIu32 "!", error);
return error;
}
break;
case IRP_MJ_WRITE:
if ((error = parallel_process_irp_write(parallel, irp)))
{
WLog_ERR(TAG, "parallel_process_irp_write failed with error %" PRIu32 "!", error);
return error;
}
break;
case IRP_MJ_DEVICE_CONTROL:
if ((error = parallel_process_irp_device_control(parallel, irp)))
{
WLog_ERR(TAG, "parallel_process_irp_device_control failed with error %" PRIu32 "!",
error);
return error;
}
break;
default:
irp->IoStatus = STATUS_NOT_SUPPORTED;
return irp->Complete(irp);
break;
}
return CHANNEL_RC_OK;
}
static DWORD WINAPI parallel_thread_func(LPVOID arg)
{
IRP* irp;
wMessage message;
PARALLEL_DEVICE* parallel = (PARALLEL_DEVICE*)arg;
UINT error = CHANNEL_RC_OK;
while (1)
{
if (!MessageQueue_Wait(parallel->queue))
{
WLog_ERR(TAG, "MessageQueue_Wait failed!");
error = ERROR_INTERNAL_ERROR;
break;
}
if (!MessageQueue_Peek(parallel->queue, &message, TRUE))
{
WLog_ERR(TAG, "MessageQueue_Peek failed!");
error = ERROR_INTERNAL_ERROR;
break;
}
if (message.id == WMQ_QUIT)
break;
irp = (IRP*)message.wParam;
if ((error = parallel_process_irp(parallel, irp)))
{
WLog_ERR(TAG, "parallel_process_irp failed with error %" PRIu32 "!", error);
break;
}
}
if (error && parallel->rdpcontext)
setChannelError(parallel->rdpcontext, error, "parallel_thread_func reported an error");
ExitThread(error);
return error;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT parallel_irp_request(DEVICE* device, IRP* irp)
{
PARALLEL_DEVICE* parallel = (PARALLEL_DEVICE*)device;
if (!MessageQueue_Post(parallel->queue, NULL, 0, (void*)irp, NULL))
{
WLog_ERR(TAG, "MessageQueue_Post failed!");
return ERROR_INTERNAL_ERROR;
}
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT parallel_free(DEVICE* device)
{
UINT error;
PARALLEL_DEVICE* parallel = (PARALLEL_DEVICE*)device;
if (!MessageQueue_PostQuit(parallel->queue, 0) ||
(WaitForSingleObject(parallel->thread, INFINITE) == WAIT_FAILED))
{
error = GetLastError();
WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "!", error);
return error;
}
CloseHandle(parallel->thread);
Stream_Free(parallel->device.data, TRUE);
MessageQueue_Free(parallel->queue);
free(parallel);
return CHANNEL_RC_OK;
}
#ifdef BUILTIN_CHANNELS
#define DeviceServiceEntry parallel_DeviceServiceEntry
#else
#define DeviceServiceEntry FREERDP_API DeviceServiceEntry
#endif
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
UINT DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)
{
char* name;
char* path;
size_t i;
size_t length;
RDPDR_PARALLEL* device;
PARALLEL_DEVICE* parallel;
UINT error;
device = (RDPDR_PARALLEL*)pEntryPoints->device;
name = device->Name;
path = device->Path;
if (!name || (name[0] == '*') || !path)
{
/* TODO: implement auto detection of parallel ports */
return CHANNEL_RC_INITIALIZATION_ERROR;
}
if (name[0] && path[0])
{
parallel = (PARALLEL_DEVICE*)calloc(1, sizeof(PARALLEL_DEVICE));
if (!parallel)
{
WLog_ERR(TAG, "calloc failed!");
return CHANNEL_RC_NO_MEMORY;
}
parallel->device.type = RDPDR_DTYP_PARALLEL;
parallel->device.name = name;
parallel->device.IRPRequest = parallel_irp_request;
parallel->device.Free = parallel_free;
parallel->rdpcontext = pEntryPoints->rdpcontext;
length = strlen(name);
parallel->device.data = Stream_New(NULL, length + 1);
if (!parallel->device.data)
{
WLog_ERR(TAG, "Stream_New failed!");
error = CHANNEL_RC_NO_MEMORY;
goto error_out;
}
for (i = 0; i <= length; i++)
Stream_Write_UINT8(parallel->device.data, name[i] < 0 ? '_' : name[i]);
parallel->path = path;
parallel->queue = MessageQueue_New(NULL);
if (!parallel->queue)
{
WLog_ERR(TAG, "MessageQueue_New failed!");
error = CHANNEL_RC_NO_MEMORY;
goto error_out;
}
if ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)parallel)))
{
WLog_ERR(TAG, "RegisterDevice failed with error %" PRIu32 "!", error);
goto error_out;
}
if (!(parallel->thread =
CreateThread(NULL, 0, parallel_thread_func, (void*)parallel, 0, NULL)))
{
WLog_ERR(TAG, "CreateThread failed!");
error = ERROR_INTERNAL_ERROR;
goto error_out;
}
}
return CHANNEL_RC_OK;
error_out:
MessageQueue_Free(parallel->queue);
Stream_Free(parallel->device.data, TRUE);
free(parallel);
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3947_0 |
crossvul-cpp_data_good_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;
wStream sub1, sub2;
CLIPRDR_FORMAT* formats = NULL;
UINT error = CHANNEL_RC_OK;
asciiNames = (formatList->msgFlags & CB_ASCII_NAMES) ? TRUE : FALSE;
index = 0;
/* empty format list */
formatList->formats = NULL;
formatList->numFormats = 0;
Stream_StaticInit(&sub1, Stream_Pointer(s), formatList->dataLen);
if (!Stream_SafeSeek(s, formatList->dataLen))
return ERROR_INVALID_DATA;
if (!formatList->dataLen)
{
}
else if (!useLongFormatNames)
{
const size_t cap = Stream_Capacity(&sub1);
formatList->numFormats = (cap / 36);
if ((formatList->numFormats * 36) != cap)
{
WLog_ERR(TAG, "Invalid short format list length: %" PRIuz "", cap);
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 (Stream_GetRemainingLength(&sub1) >= 4)
{
Stream_Read_UINT32(&sub1, formats[index].formatId); /* formatId (4 bytes) */
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 !
*/
szFormatName = (char*)Stream_Pointer(&sub1);
wszFormatName = (WCHAR*)Stream_Pointer(&sub1);
if (!Stream_SafeSeek(&sub1, 32))
goto error_out;
if (asciiNames)
{
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
{
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;
}
}
}
index++;
}
}
else
{
sub2 = sub1;
while (Stream_GetRemainingLength(&sub1) > 0)
{
size_t rest;
if (!Stream_SafeSeek(&sub1, 4)) /* formatId (4 bytes) */
goto error_out;
wszFormatName = (WCHAR*)Stream_Pointer(&sub1);
rest = Stream_GetRemainingLength(&sub1);
formatNameLength = _wcsnlen(wszFormatName, rest / sizeof(WCHAR));
if (!Stream_SafeSeek(&sub1, (formatNameLength + 1) * sizeof(WCHAR)))
goto error_out;
formatList->numFormats++;
}
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 (Stream_GetRemainingLength(&sub2) >= 4)
{
size_t rest;
Stream_Read_UINT32(&sub2, formats[index].formatId); /* formatId (4 bytes) */
formats[index].formatName = NULL;
wszFormatName = (WCHAR*)Stream_Pointer(&sub2);
rest = Stream_GetRemainingLength(&sub2);
formatNameLength = _wcsnlen(wszFormatName, rest / sizeof(WCHAR));
if (!Stream_SafeSeek(&sub2, (formatNameLength + 1) * sizeof(WCHAR)))
goto error_out;
if (formatNameLength)
{
if (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, formatNameLength,
&(formats[index].formatName), 0, NULL, NULL) < 1)
{
WLog_ERR(TAG, "failed to convert long clipboard format name");
error = ERROR_INTERNAL_ERROR;
goto error_out;
}
}
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);
formatList->formats = NULL;
formatList->numFormats = 0;
}
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3942_0 |
crossvul-cpp_data_bad_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_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/bad_2698_0 |
crossvul-cpp_data_bad_2702_0 | /*
* Copyright (c) 1992, 1993, 1994, 1995, 1996
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Original code by Matt Thomas, Digital Equipment Corporation
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete IS-IS & CLNP support.
*/
/* \summary: ISO CLNS, ESIS, and ISIS printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "ether.h"
#include "nlpid.h"
#include "extract.h"
#include "gmpls.h"
#include "oui.h"
#include "signature.h"
static const char tstr[] = " [|isis]";
/*
* IS-IS is defined in ISO 10589. Look there for protocol definitions.
*/
#define SYSTEM_ID_LEN ETHER_ADDR_LEN
#define NODE_ID_LEN SYSTEM_ID_LEN+1
#define LSP_ID_LEN SYSTEM_ID_LEN+2
#define ISIS_VERSION 1
#define ESIS_VERSION 1
#define CLNP_VERSION 1
#define ISIS_PDU_TYPE_MASK 0x1F
#define ESIS_PDU_TYPE_MASK 0x1F
#define CLNP_PDU_TYPE_MASK 0x1F
#define CLNP_FLAG_MASK 0xE0
#define ISIS_LAN_PRIORITY_MASK 0x7F
#define ISIS_PDU_L1_LAN_IIH 15
#define ISIS_PDU_L2_LAN_IIH 16
#define ISIS_PDU_PTP_IIH 17
#define ISIS_PDU_L1_LSP 18
#define ISIS_PDU_L2_LSP 20
#define ISIS_PDU_L1_CSNP 24
#define ISIS_PDU_L2_CSNP 25
#define ISIS_PDU_L1_PSNP 26
#define ISIS_PDU_L2_PSNP 27
static const struct tok isis_pdu_values[] = {
{ ISIS_PDU_L1_LAN_IIH, "L1 Lan IIH"},
{ ISIS_PDU_L2_LAN_IIH, "L2 Lan IIH"},
{ ISIS_PDU_PTP_IIH, "p2p IIH"},
{ ISIS_PDU_L1_LSP, "L1 LSP"},
{ ISIS_PDU_L2_LSP, "L2 LSP"},
{ ISIS_PDU_L1_CSNP, "L1 CSNP"},
{ ISIS_PDU_L2_CSNP, "L2 CSNP"},
{ ISIS_PDU_L1_PSNP, "L1 PSNP"},
{ ISIS_PDU_L2_PSNP, "L2 PSNP"},
{ 0, NULL}
};
/*
* A TLV is a tuple of a type, length and a value and is normally used for
* encoding information in all sorts of places. This is an enumeration of
* the well known types.
*
* list taken from rfc3359 plus some memory from veterans ;-)
*/
#define ISIS_TLV_AREA_ADDR 1 /* iso10589 */
#define ISIS_TLV_IS_REACH 2 /* iso10589 */
#define ISIS_TLV_ESNEIGH 3 /* iso10589 */
#define ISIS_TLV_PART_DIS 4 /* iso10589 */
#define ISIS_TLV_PREFIX_NEIGH 5 /* iso10589 */
#define ISIS_TLV_ISNEIGH 6 /* iso10589 */
#define ISIS_TLV_ISNEIGH_VARLEN 7 /* iso10589 */
#define ISIS_TLV_PADDING 8 /* iso10589 */
#define ISIS_TLV_LSP 9 /* iso10589 */
#define ISIS_TLV_AUTH 10 /* iso10589, rfc3567 */
#define ISIS_TLV_CHECKSUM 12 /* rfc3358 */
#define ISIS_TLV_CHECKSUM_MINLEN 2
#define ISIS_TLV_POI 13 /* rfc6232 */
#define ISIS_TLV_LSP_BUFFERSIZE 14 /* iso10589 rev2 */
#define ISIS_TLV_LSP_BUFFERSIZE_MINLEN 2
#define ISIS_TLV_EXT_IS_REACH 22 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_IS_ALIAS_ID 24 /* draft-ietf-isis-ext-lsp-frags-02 */
#define ISIS_TLV_DECNET_PHASE4 42
#define ISIS_TLV_LUCENT_PRIVATE 66
#define ISIS_TLV_INT_IP_REACH 128 /* rfc1195, rfc2966 */
#define ISIS_TLV_PROTOCOLS 129 /* rfc1195 */
#define ISIS_TLV_EXT_IP_REACH 130 /* rfc1195, rfc2966 */
#define ISIS_TLV_IDRP_INFO 131 /* rfc1195 */
#define ISIS_TLV_IDRP_INFO_MINLEN 1
#define ISIS_TLV_IPADDR 132 /* rfc1195 */
#define ISIS_TLV_IPAUTH 133 /* rfc1195 */
#define ISIS_TLV_TE_ROUTER_ID 134 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_EXTD_IP_REACH 135 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_HOSTNAME 137 /* rfc2763 */
#define ISIS_TLV_SHARED_RISK_GROUP 138 /* draft-ietf-isis-gmpls-extensions */
#define ISIS_TLV_MT_PORT_CAP 143 /* rfc6165 */
#define ISIS_TLV_MT_CAPABILITY 144 /* rfc6329 */
#define ISIS_TLV_NORTEL_PRIVATE1 176
#define ISIS_TLV_NORTEL_PRIVATE2 177
#define ISIS_TLV_RESTART_SIGNALING 211 /* rfc3847 */
#define ISIS_TLV_RESTART_SIGNALING_FLAGLEN 1
#define ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN 2
#define ISIS_TLV_MT_IS_REACH 222 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED 229 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED_MINLEN 2
#define ISIS_TLV_IP6ADDR 232 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP_REACH 235 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_IP6_REACH 236 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP6_REACH 237 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_PTP_ADJ 240 /* rfc3373 */
#define ISIS_TLV_IIH_SEQNR 241 /* draft-shen-isis-iih-sequence-00 */
#define ISIS_TLV_IIH_SEQNR_MINLEN 4
#define ISIS_TLV_VENDOR_PRIVATE 250 /* draft-ietf-isis-experimental-tlv-01 */
#define ISIS_TLV_VENDOR_PRIVATE_MINLEN 3
static const struct tok isis_tlv_values[] = {
{ ISIS_TLV_AREA_ADDR, "Area address(es)"},
{ ISIS_TLV_IS_REACH, "IS Reachability"},
{ ISIS_TLV_ESNEIGH, "ES Neighbor(s)"},
{ ISIS_TLV_PART_DIS, "Partition DIS"},
{ ISIS_TLV_PREFIX_NEIGH, "Prefix Neighbors"},
{ ISIS_TLV_ISNEIGH, "IS Neighbor(s)"},
{ ISIS_TLV_ISNEIGH_VARLEN, "IS Neighbor(s) (variable length)"},
{ ISIS_TLV_PADDING, "Padding"},
{ ISIS_TLV_LSP, "LSP entries"},
{ ISIS_TLV_AUTH, "Authentication"},
{ ISIS_TLV_CHECKSUM, "Checksum"},
{ ISIS_TLV_POI, "Purge Originator Identifier"},
{ ISIS_TLV_LSP_BUFFERSIZE, "LSP Buffersize"},
{ ISIS_TLV_EXT_IS_REACH, "Extended IS Reachability"},
{ ISIS_TLV_IS_ALIAS_ID, "IS Alias ID"},
{ ISIS_TLV_DECNET_PHASE4, "DECnet Phase IV"},
{ ISIS_TLV_LUCENT_PRIVATE, "Lucent Proprietary"},
{ ISIS_TLV_INT_IP_REACH, "IPv4 Internal Reachability"},
{ ISIS_TLV_PROTOCOLS, "Protocols supported"},
{ ISIS_TLV_EXT_IP_REACH, "IPv4 External Reachability"},
{ ISIS_TLV_IDRP_INFO, "Inter-Domain Information Type"},
{ ISIS_TLV_IPADDR, "IPv4 Interface address(es)"},
{ ISIS_TLV_IPAUTH, "IPv4 authentication (deprecated)"},
{ ISIS_TLV_TE_ROUTER_ID, "Traffic Engineering Router ID"},
{ ISIS_TLV_EXTD_IP_REACH, "Extended IPv4 Reachability"},
{ ISIS_TLV_SHARED_RISK_GROUP, "Shared Risk Link Group"},
{ ISIS_TLV_MT_PORT_CAP, "Multi-Topology-Aware Port Capability"},
{ ISIS_TLV_MT_CAPABILITY, "Multi-Topology Capability"},
{ ISIS_TLV_NORTEL_PRIVATE1, "Nortel Proprietary"},
{ ISIS_TLV_NORTEL_PRIVATE2, "Nortel Proprietary"},
{ ISIS_TLV_HOSTNAME, "Hostname"},
{ ISIS_TLV_RESTART_SIGNALING, "Restart Signaling"},
{ ISIS_TLV_MT_IS_REACH, "Multi Topology IS Reachability"},
{ ISIS_TLV_MT_SUPPORTED, "Multi Topology"},
{ ISIS_TLV_IP6ADDR, "IPv6 Interface address(es)"},
{ ISIS_TLV_MT_IP_REACH, "Multi-Topology IPv4 Reachability"},
{ ISIS_TLV_IP6_REACH, "IPv6 reachability"},
{ ISIS_TLV_MT_IP6_REACH, "Multi-Topology IP6 Reachability"},
{ ISIS_TLV_PTP_ADJ, "Point-to-point Adjacency State"},
{ ISIS_TLV_IIH_SEQNR, "Hello PDU Sequence Number"},
{ ISIS_TLV_VENDOR_PRIVATE, "Vendor Private"},
{ 0, NULL }
};
#define ESIS_OPTION_PROTOCOLS 129
#define ESIS_OPTION_QOS_MAINTENANCE 195 /* iso9542 */
#define ESIS_OPTION_SECURITY 197 /* iso9542 */
#define ESIS_OPTION_ES_CONF_TIME 198 /* iso9542 */
#define ESIS_OPTION_PRIORITY 205 /* iso9542 */
#define ESIS_OPTION_ADDRESS_MASK 225 /* iso9542 */
#define ESIS_OPTION_SNPA_MASK 226 /* iso9542 */
static const struct tok esis_option_values[] = {
{ ESIS_OPTION_PROTOCOLS, "Protocols supported"},
{ ESIS_OPTION_QOS_MAINTENANCE, "QoS Maintenance" },
{ ESIS_OPTION_SECURITY, "Security" },
{ ESIS_OPTION_ES_CONF_TIME, "ES Configuration Time" },
{ ESIS_OPTION_PRIORITY, "Priority" },
{ ESIS_OPTION_ADDRESS_MASK, "Addressk Mask" },
{ ESIS_OPTION_SNPA_MASK, "SNPA Mask" },
{ 0, NULL }
};
#define CLNP_OPTION_DISCARD_REASON 193
#define CLNP_OPTION_QOS_MAINTENANCE 195 /* iso8473 */
#define CLNP_OPTION_SECURITY 197 /* iso8473 */
#define CLNP_OPTION_SOURCE_ROUTING 200 /* iso8473 */
#define CLNP_OPTION_ROUTE_RECORDING 203 /* iso8473 */
#define CLNP_OPTION_PADDING 204 /* iso8473 */
#define CLNP_OPTION_PRIORITY 205 /* iso8473 */
static const struct tok clnp_option_values[] = {
{ CLNP_OPTION_DISCARD_REASON, "Discard Reason"},
{ CLNP_OPTION_PRIORITY, "Priority"},
{ CLNP_OPTION_QOS_MAINTENANCE, "QoS Maintenance"},
{ CLNP_OPTION_SECURITY, "Security"},
{ CLNP_OPTION_SOURCE_ROUTING, "Source Routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "Route Recording"},
{ CLNP_OPTION_PADDING, "Padding"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_class_values[] = {
{ 0x0, "General"},
{ 0x8, "Address"},
{ 0x9, "Source Routeing"},
{ 0xa, "Lifetime"},
{ 0xb, "PDU Discarded"},
{ 0xc, "Reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_general_values[] = {
{ 0x0, "Reason not specified"},
{ 0x1, "Protocol procedure error"},
{ 0x2, "Incorrect checksum"},
{ 0x3, "PDU discarded due to congestion"},
{ 0x4, "Header syntax error (cannot be parsed)"},
{ 0x5, "Segmentation needed but not permitted"},
{ 0x6, "Incomplete PDU received"},
{ 0x7, "Duplicate option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_address_values[] = {
{ 0x0, "Destination address unreachable"},
{ 0x1, "Destination address unknown"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_source_routeing_values[] = {
{ 0x0, "Unspecified source routeing error"},
{ 0x1, "Syntax error in source routeing field"},
{ 0x2, "Unknown address in source routeing field"},
{ 0x3, "Path not acceptable"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_lifetime_values[] = {
{ 0x0, "Lifetime expired while data unit in transit"},
{ 0x1, "Lifetime expired during reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_pdu_discard_values[] = {
{ 0x0, "Unsupported option not specified"},
{ 0x1, "Unsupported protocol version"},
{ 0x2, "Unsupported security option"},
{ 0x3, "Unsupported source routeing option"},
{ 0x4, "Unsupported recording of route option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_reassembly_values[] = {
{ 0x0, "Reassembly interference"},
{ 0, NULL }
};
/* array of 16 error-classes */
static const struct tok *clnp_option_rfd_error_class[] = {
clnp_option_rfd_general_values,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
clnp_option_rfd_address_values,
clnp_option_rfd_source_routeing_values,
clnp_option_rfd_lifetime_values,
clnp_option_rfd_pdu_discard_values,
clnp_option_rfd_reassembly_values,
NULL,
NULL,
NULL
};
#define CLNP_OPTION_OPTION_QOS_MASK 0x3f
#define CLNP_OPTION_SCOPE_MASK 0xc0
#define CLNP_OPTION_SCOPE_SA_SPEC 0x40
#define CLNP_OPTION_SCOPE_DA_SPEC 0x80
#define CLNP_OPTION_SCOPE_GLOBAL 0xc0
static const struct tok clnp_option_scope_values[] = {
{ CLNP_OPTION_SCOPE_SA_SPEC, "Source Address Specific"},
{ CLNP_OPTION_SCOPE_DA_SPEC, "Destination Address Specific"},
{ CLNP_OPTION_SCOPE_GLOBAL, "Globally unique"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_values[] = {
{ 0x0, "partial"},
{ 0x1, "complete"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_string_values[] = {
{ CLNP_OPTION_SOURCE_ROUTING, "source routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "recording of route in progress"},
{ 0, NULL }
};
static const struct tok clnp_option_qos_global_values[] = {
{ 0x20, "reserved"},
{ 0x10, "sequencing vs. delay"},
{ 0x08, "congested"},
{ 0x04, "delay vs. cost"},
{ 0x02, "error vs. delay"},
{ 0x01, "error vs. cost"},
{ 0, NULL }
};
#define ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP 3 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID 4 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID 5 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR 6 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR 8 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW 9 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW 10 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW 11 /* rfc4124 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD 12 /* draft-ietf-tewg-diff-te-proto-06 */
#define ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC 18 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE 19 /* draft-ietf-isis-link-attr-01 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE 20 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR 21 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS 22 /* rfc4124 */
#define ISIS_SUBTLV_SPB_METRIC 29 /* rfc6329 */
static const struct tok isis_ext_is_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP, "Administrative groups" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID, "Link Local/Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID, "Link Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR, "IPv4 interface address" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR, "IPv4 neighbor address" },
{ ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW, "Maximum link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW, "Reservable link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW, "Unreserved bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC, "Traffic Engineering Metric" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE, "Link Attribute" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE, "Link Protection Type" },
{ ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR, "Interface Switching Capability" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD, "Bandwidth Constraints (old)" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS, "Bandwidth Constraints" },
{ ISIS_SUBTLV_SPB_METRIC, "SPB Metric" },
{ 250, "Reserved for cisco specific extensions" },
{ 251, "Reserved for cisco specific extensions" },
{ 252, "Reserved for cisco specific extensions" },
{ 253, "Reserved for cisco specific extensions" },
{ 254, "Reserved for cisco specific extensions" },
{ 255, "Reserved for future expansion" },
{ 0, NULL }
};
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32 1 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64 2 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR 117 /* draft-ietf-isis-wg-multi-topology-05 */
static const struct tok isis_ext_ip_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32, "32-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64, "64-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR, "Management Prefix Color" },
{ 0, NULL }
};
static const struct tok isis_subtlv_link_attribute_values[] = {
{ 0x01, "Local Protection Available" },
{ 0x02, "Link excluded from local protection path" },
{ 0x04, "Local maintenance required"},
{ 0, NULL }
};
#define ISIS_SUBTLV_AUTH_SIMPLE 1
#define ISIS_SUBTLV_AUTH_GENERIC 3 /* rfc 5310 */
#define ISIS_SUBTLV_AUTH_MD5 54
#define ISIS_SUBTLV_AUTH_MD5_LEN 16
#define ISIS_SUBTLV_AUTH_PRIVATE 255
static const struct tok isis_subtlv_auth_values[] = {
{ ISIS_SUBTLV_AUTH_SIMPLE, "simple text password"},
{ ISIS_SUBTLV_AUTH_GENERIC, "Generic Crypto key-id"},
{ ISIS_SUBTLV_AUTH_MD5, "HMAC-MD5 password"},
{ ISIS_SUBTLV_AUTH_PRIVATE, "Routing Domain private password"},
{ 0, NULL }
};
#define ISIS_SUBTLV_IDRP_RES 0
#define ISIS_SUBTLV_IDRP_LOCAL 1
#define ISIS_SUBTLV_IDRP_ASN 2
static const struct tok isis_subtlv_idrp_values[] = {
{ ISIS_SUBTLV_IDRP_RES, "Reserved"},
{ ISIS_SUBTLV_IDRP_LOCAL, "Routing-Domain Specific"},
{ ISIS_SUBTLV_IDRP_ASN, "AS Number Tag"},
{ 0, NULL}
};
#define ISIS_SUBTLV_SPB_MCID 4
#define ISIS_SUBTLV_SPB_DIGEST 5
#define ISIS_SUBTLV_SPB_BVID 6
#define ISIS_SUBTLV_SPB_INSTANCE 1
#define ISIS_SUBTLV_SPBM_SI 3
#define ISIS_SPB_MCID_LEN 51
#define ISIS_SUBTLV_SPB_MCID_MIN_LEN 102
#define ISIS_SUBTLV_SPB_DIGEST_MIN_LEN 33
#define ISIS_SUBTLV_SPB_BVID_MIN_LEN 6
#define ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN 19
#define ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN 8
static const struct tok isis_mt_port_cap_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_MCID, "SPB MCID" },
{ ISIS_SUBTLV_SPB_DIGEST, "SPB Digest" },
{ ISIS_SUBTLV_SPB_BVID, "SPB BVID" },
{ 0, NULL }
};
static const struct tok isis_mt_capability_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_INSTANCE, "SPB Instance" },
{ ISIS_SUBTLV_SPBM_SI, "SPBM Service Identifier and Unicast Address" },
{ 0, NULL }
};
struct isis_spb_mcid {
uint8_t format_id;
uint8_t name[32];
uint8_t revision_lvl[2];
uint8_t digest[16];
};
struct isis_subtlv_spb_mcid {
struct isis_spb_mcid mcid;
struct isis_spb_mcid aux_mcid;
};
struct isis_subtlv_spb_instance {
uint8_t cist_root_id[8];
uint8_t cist_external_root_path_cost[4];
uint8_t bridge_priority[2];
uint8_t spsourceid[4];
uint8_t no_of_trees;
};
#define CLNP_SEGMENT_PART 0x80
#define CLNP_MORE_SEGMENTS 0x40
#define CLNP_REQUEST_ER 0x20
static const struct tok clnp_flag_values[] = {
{ CLNP_SEGMENT_PART, "Segmentation permitted"},
{ CLNP_MORE_SEGMENTS, "more Segments"},
{ CLNP_REQUEST_ER, "request Error Report"},
{ 0, NULL}
};
#define ISIS_MASK_LSP_OL_BIT(x) ((x)&0x4)
#define ISIS_MASK_LSP_ISTYPE_BITS(x) ((x)&0x3)
#define ISIS_MASK_LSP_PARTITION_BIT(x) ((x)&0x80)
#define ISIS_MASK_LSP_ATT_BITS(x) ((x)&0x78)
#define ISIS_MASK_LSP_ATT_ERROR_BIT(x) ((x)&0x40)
#define ISIS_MASK_LSP_ATT_EXPENSE_BIT(x) ((x)&0x20)
#define ISIS_MASK_LSP_ATT_DELAY_BIT(x) ((x)&0x10)
#define ISIS_MASK_LSP_ATT_DEFAULT_BIT(x) ((x)&0x8)
#define ISIS_MASK_MTID(x) ((x)&0x0fff)
#define ISIS_MASK_MTFLAGS(x) ((x)&0xf000)
static const struct tok isis_mt_flag_values[] = {
{ 0x4000, "ATT bit set"},
{ 0x8000, "Overload bit set"},
{ 0, NULL}
};
#define ISIS_MASK_TLV_EXTD_IP_UPDOWN(x) ((x)&0x80)
#define ISIS_MASK_TLV_EXTD_IP_SUBTLV(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_IE(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_SUBTLV(x) ((x)&0x20)
#define ISIS_LSP_TLV_METRIC_SUPPORTED(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_IE(x) ((x)&0x40)
#define ISIS_LSP_TLV_METRIC_UPDOWN(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_VALUE(x) ((x)&0x3f)
#define ISIS_MASK_TLV_SHARED_RISK_GROUP(x) ((x)&0x1)
static const struct tok isis_mt_values[] = {
{ 0, "IPv4 unicast"},
{ 1, "In-Band Management"},
{ 2, "IPv6 unicast"},
{ 3, "Multicast"},
{ 4095, "Development, Experimental or Proprietary"},
{ 0, NULL }
};
static const struct tok isis_iih_circuit_type_values[] = {
{ 1, "Level 1 only"},
{ 2, "Level 2 only"},
{ 3, "Level 1, Level 2"},
{ 0, NULL}
};
#define ISIS_LSP_TYPE_UNUSED0 0
#define ISIS_LSP_TYPE_LEVEL_1 1
#define ISIS_LSP_TYPE_UNUSED2 2
#define ISIS_LSP_TYPE_LEVEL_2 3
static const struct tok isis_lsp_istype_values[] = {
{ ISIS_LSP_TYPE_UNUSED0, "Unused 0x0 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_1, "L1 IS"},
{ ISIS_LSP_TYPE_UNUSED2, "Unused 0x2 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_2, "L2 IS"},
{ 0, NULL }
};
/*
* Katz's point to point adjacency TLV uses codes to tell us the state of
* the remote adjacency. Enumerate them.
*/
#define ISIS_PTP_ADJ_UP 0
#define ISIS_PTP_ADJ_INIT 1
#define ISIS_PTP_ADJ_DOWN 2
static const struct tok isis_ptp_adjancey_values[] = {
{ ISIS_PTP_ADJ_UP, "Up" },
{ ISIS_PTP_ADJ_INIT, "Initializing" },
{ ISIS_PTP_ADJ_DOWN, "Down" },
{ 0, NULL}
};
struct isis_tlv_ptp_adj {
uint8_t adjacency_state;
uint8_t extd_local_circuit_id[4];
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
uint8_t neighbor_extd_local_circuit_id[4];
};
static void osi_print_cksum(netdissect_options *, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length);
static int clnp_print(netdissect_options *, const uint8_t *, u_int);
static void esis_print(netdissect_options *, const uint8_t *, u_int);
static int isis_print(netdissect_options *, const uint8_t *, u_int);
struct isis_metric_block {
uint8_t metric_default;
uint8_t metric_delay;
uint8_t metric_expense;
uint8_t metric_error;
};
struct isis_tlv_is_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_nodeid[NODE_ID_LEN];
};
struct isis_tlv_es_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
};
struct isis_tlv_ip_reach {
struct isis_metric_block isis_metric_block;
uint8_t prefix[4];
uint8_t mask[4];
};
static const struct tok isis_is_reach_virtual_values[] = {
{ 0, "IsNotVirtual"},
{ 1, "IsVirtual"},
{ 0, NULL }
};
static const struct tok isis_restart_flag_values[] = {
{ 0x1, "Restart Request"},
{ 0x2, "Restart Acknowledgement"},
{ 0x4, "Suppress adjacency advertisement"},
{ 0, NULL }
};
struct isis_common_header {
uint8_t nlpid;
uint8_t fixed_len;
uint8_t version; /* Protocol version */
uint8_t id_length;
uint8_t pdu_type; /* 3 MSbits are reserved */
uint8_t pdu_version; /* Packet format version */
uint8_t reserved;
uint8_t max_area;
};
struct isis_iih_lan_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t priority;
uint8_t lan_id[NODE_ID_LEN];
};
struct isis_iih_ptp_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t circuit_id;
};
struct isis_lsp_header {
uint8_t pdu_len[2];
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
uint8_t typeblock;
};
struct isis_csnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
uint8_t start_lsp_id[LSP_ID_LEN];
uint8_t end_lsp_id[LSP_ID_LEN];
};
struct isis_psnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
};
struct isis_tlv_lsp {
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
};
#define ISIS_COMMON_HEADER_SIZE (sizeof(struct isis_common_header))
#define ISIS_IIH_LAN_HEADER_SIZE (sizeof(struct isis_iih_lan_header))
#define ISIS_IIH_PTP_HEADER_SIZE (sizeof(struct isis_iih_ptp_header))
#define ISIS_LSP_HEADER_SIZE (sizeof(struct isis_lsp_header))
#define ISIS_CSNP_HEADER_SIZE (sizeof(struct isis_csnp_header))
#define ISIS_PSNP_HEADER_SIZE (sizeof(struct isis_psnp_header))
void
isoclns_print(netdissect_options *ndo, const uint8_t *p, u_int length)
{
if (!ND_TTEST(*p)) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (length > 1)
print_unknown_data(ndo, p, "\n\t", length);
break;
}
}
#define CLNP_PDU_ER 1
#define CLNP_PDU_DT 28
#define CLNP_PDU_MD 29
#define CLNP_PDU_ERQ 30
#define CLNP_PDU_ERP 31
static const struct tok clnp_pdu_values[] = {
{ CLNP_PDU_ER, "Error Report"},
{ CLNP_PDU_MD, "MD"},
{ CLNP_PDU_DT, "Data"},
{ CLNP_PDU_ERQ, "Echo Request"},
{ CLNP_PDU_ERP, "Echo Response"},
{ 0, NULL }
};
struct clnp_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t lifetime; /* units of 500ms */
uint8_t type;
uint8_t segment_length[2];
uint8_t cksum[2];
};
struct clnp_segment_header_t {
uint8_t data_unit_id[2];
uint8_t segment_offset[2];
uint8_t total_length[2];
};
/*
* clnp_print
* Decode CLNP packets. Return 0 on error.
*/
static int
clnp_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr,*source_address,*dest_address;
u_int li,tlen,nsap_offset,source_address_length,dest_address_length, clnp_pdu_type, clnp_flags;
const struct clnp_header_t *clnp_header;
const struct clnp_segment_header_t *clnp_segment_header;
uint8_t rfd_error_major,rfd_error_minor;
clnp_header = (const struct clnp_header_t *) pptr;
ND_TCHECK(*clnp_header);
li = clnp_header->length_indicator;
optr = pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "CLNP"));
/*
* Sanity checking of the header.
*/
if (clnp_header->version != CLNP_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", clnp_header->version));
return (0);
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return (0);
}
if (li < sizeof(struct clnp_header_t)) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return (0);
}
/* FIXME further header sanity checking */
clnp_pdu_type = clnp_header->type & CLNP_PDU_TYPE_MASK;
clnp_flags = clnp_header->type & CLNP_FLAG_MASK;
pptr += sizeof(struct clnp_header_t);
li -= sizeof(struct clnp_header_t);
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
dest_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < dest_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, dest_address_length);
dest_address = pptr;
pptr += dest_address_length;
li -= dest_address_length;
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
source_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < source_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, source_address_length);
source_address = pptr;
pptr += source_address_length;
li -= source_address_length;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s > %s, %s, length %u",
ndo->ndo_eflag ? "" : ", ",
isonsap_string(ndo, source_address, source_address_length),
isonsap_string(ndo, dest_address, dest_address_length),
tok2str(clnp_pdu_values,"unknown (%u)",clnp_pdu_type),
length));
return (1);
}
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s PDU, hlen: %u, v: %u, lifetime: %u.%us, Segment PDU length: %u, checksum: 0x%04x",
tok2str(clnp_pdu_values, "unknown (%u)",clnp_pdu_type),
clnp_header->length_indicator,
clnp_header->version,
clnp_header->lifetime/2,
(clnp_header->lifetime%2)*5,
EXTRACT_16BITS(clnp_header->segment_length),
EXTRACT_16BITS(clnp_header->cksum)));
osi_print_cksum(ndo, optr, EXTRACT_16BITS(clnp_header->cksum), 7,
clnp_header->length_indicator);
ND_PRINT((ndo, "\n\tFlags [%s]",
bittok2str(clnp_flag_values, "none", clnp_flags)));
ND_PRINT((ndo, "\n\tsource address (length %u): %s\n\tdest address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length),
dest_address_length,
isonsap_string(ndo, dest_address, dest_address_length)));
if (clnp_flags & CLNP_SEGMENT_PART) {
if (li < sizeof(const struct clnp_segment_header_t)) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header, addresses, and segment part"));
return (0);
}
clnp_segment_header = (const struct clnp_segment_header_t *) pptr;
ND_TCHECK(*clnp_segment_header);
ND_PRINT((ndo, "\n\tData Unit ID: 0x%04x, Segment Offset: %u, Total PDU Length: %u",
EXTRACT_16BITS(clnp_segment_header->data_unit_id),
EXTRACT_16BITS(clnp_segment_header->segment_offset),
EXTRACT_16BITS(clnp_segment_header->total_length)));
pptr+=sizeof(const struct clnp_segment_header_t);
li-=sizeof(const struct clnp_segment_header_t);
}
/* now walk the options */
while (li >= 2) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return (0);
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return (0);
}
ND_TCHECK2(*pptr, opli);
li -= opli;
tptr = pptr;
tlen = opli;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(clnp_option_values,"Unknown",op),
op,
opli));
/*
* We've already checked that the entire option is present
* in the captured packet with the ND_TCHECK2() call.
* Therefore, we don't need to do ND_TCHECK()/ND_TCHECK2()
* checks.
* We do, however, need to check tlen, to make sure we
* don't run past the end of the option.
*/
switch (op) {
case CLNP_OPTION_ROUTE_RECORDING: /* those two options share the format */
case CLNP_OPTION_SOURCE_ROUTING:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "%s %s",
tok2str(clnp_option_sr_rr_values,"Unknown",*tptr),
tok2str(clnp_option_sr_rr_string_values, "Unknown Option %u", op)));
nsap_offset=*(tptr+1);
if (nsap_offset == 0) {
ND_PRINT((ndo, " Bad NSAP offset (0)"));
break;
}
nsap_offset-=1; /* offset to nsap list */
if (nsap_offset > tlen) {
ND_PRINT((ndo, " Bad NSAP offset (past end of option)"));
break;
}
tptr+=nsap_offset;
tlen-=nsap_offset;
while (tlen > 0) {
source_address_length=*tptr;
if (tlen < source_address_length+1) {
ND_PRINT((ndo, "\n\t NSAP address goes past end of option"));
break;
}
if (source_address_length > 0) {
source_address=(tptr+1);
ND_TCHECK2(*source_address, source_address_length);
ND_PRINT((ndo, "\n\t NSAP address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length)));
}
tlen-=source_address_length+1;
}
break;
case CLNP_OPTION_PRIORITY:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "0x%1x", *tptr&0x0f));
break;
case CLNP_OPTION_QOS_MAINTENANCE:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s",
tok2str(clnp_option_scope_values, "Reserved", *tptr&CLNP_OPTION_SCOPE_MASK)));
if ((*tptr&CLNP_OPTION_SCOPE_MASK) == CLNP_OPTION_SCOPE_GLOBAL)
ND_PRINT((ndo, "\n\t QoS Flags [%s]",
bittok2str(clnp_option_qos_global_values,
"none",
*tptr&CLNP_OPTION_OPTION_QOS_MASK)));
break;
case CLNP_OPTION_SECURITY:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s, Security-Level %u",
tok2str(clnp_option_scope_values,"Reserved",*tptr&CLNP_OPTION_SCOPE_MASK),
*(tptr+1)));
break;
case CLNP_OPTION_DISCARD_REASON:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
rfd_error_major = (*tptr&0xf0) >> 4;
rfd_error_minor = *tptr&0x0f;
ND_PRINT((ndo, "\n\t Class: %s Error (0x%01x), %s (0x%01x)",
tok2str(clnp_option_rfd_class_values,"Unknown",rfd_error_major),
rfd_error_major,
tok2str(clnp_option_rfd_error_class[rfd_error_major],"Unknown",rfd_error_minor),
rfd_error_minor));
break;
case CLNP_OPTION_PADDING:
ND_PRINT((ndo, "padding data"));
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
switch (clnp_pdu_type) {
case CLNP_PDU_ER: /* fall through */
case CLNP_PDU_ERP:
ND_TCHECK(*pptr);
if (*(pptr) == NLPID_CLNP) {
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
/* FIXME recursion protection */
clnp_print(ndo, pptr, length - clnp_header->length_indicator);
break;
}
case CLNP_PDU_DT:
case CLNP_PDU_MD:
case CLNP_PDU_ERQ:
default:
/* dump the PDU specific data */
if (length-(pptr-optr) > 0) {
ND_PRINT((ndo, "\n\t undecoded non-header data, length %u", length-clnp_header->length_indicator));
print_unknown_data(ndo, pptr, "\n\t ", length - (pptr - optr));
}
}
return (1);
trunc:
ND_PRINT((ndo, "[|clnp]"));
return (1);
}
#define ESIS_PDU_REDIRECT 6
#define ESIS_PDU_ESH 2
#define ESIS_PDU_ISH 4
static const struct tok esis_pdu_values[] = {
{ ESIS_PDU_REDIRECT, "redirect"},
{ ESIS_PDU_ESH, "ESH"},
{ ESIS_PDU_ISH, "ISH"},
{ 0, NULL }
};
struct esis_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t reserved;
uint8_t type;
uint8_t holdtime[2];
uint8_t cksum[2];
};
static void
esis_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr;
u_int li,esis_pdu_type,source_address_length, source_address_number;
const struct esis_header_t *esis_header;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "ES-IS"));
if (length <= 2) {
ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!"));
return;
}
esis_header = (const struct esis_header_t *) pptr;
ND_TCHECK(*esis_header);
li = esis_header->length_indicator;
optr = pptr;
/*
* Sanity checking of the header.
*/
if (esis_header->nlpid != NLPID_ESIS) {
ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid));
return;
}
if (esis_header->version != ESIS_VERSION) {
ND_PRINT((ndo, " version %d packet not supported", esis_header->version));
return;
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return;
}
if (li < sizeof(struct esis_header_t) + 2) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return;
}
esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s, length %u",
ndo->ndo_eflag ? "" : ", ",
tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type),
length));
return;
} else
ND_PRINT((ndo, "%slength %u\n\t%s (%u)",
ndo->ndo_eflag ? "" : ", ",
length,
tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type),
esis_pdu_type));
ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" ));
ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum)));
osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li);
ND_PRINT((ndo, ", holding time: %us, length indicator: %u",
EXTRACT_16BITS(esis_header->holdtime), li));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t));
pptr += sizeof(struct esis_header_t);
li -= sizeof(struct esis_header_t);
switch (esis_pdu_type) {
case ESIS_PDU_REDIRECT: {
const uint8_t *dst, *snpa, *neta;
u_int dstl, snpal, netal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dstl = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, dstl);
if (li < dstl) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dst = pptr;
pptr += dstl;
li -= dstl;
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl)));
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpal = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, snpal);
if (li < snpal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpa = pptr;
pptr += snpal;
li -= snpal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
netal = *pptr;
pptr++;
ND_TCHECK2(*pptr, netal);
if (li < netal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
neta = pptr;
pptr += netal;
li -= netal;
if (snpal == 6)
ND_PRINT((ndo, "\n\t SNPA (length: %u): %s",
snpal,
etheraddr_string(ndo, snpa)));
else
ND_PRINT((ndo, "\n\t SNPA (length: %u): %s",
snpal,
linkaddr_string(ndo, snpa, LINKADDR_OTHER, snpal)));
if (netal != 0)
ND_PRINT((ndo, "\n\t NET (length: %u) %s",
netal,
isonsap_string(ndo, neta, netal)));
break;
}
case ESIS_PDU_ESH:
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_number = *pptr;
pptr++;
li--;
ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number));
while (source_address_number > 0) {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s",
source_address_length,
isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
source_address_number--;
}
break;
case ESIS_PDU_ISH: {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
break;
}
default:
if (ndo->ndo_vflag <= 1) {
if (pptr < ndo->ndo_snapend)
print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr);
}
return;
}
/* now walk the options */
while (li != 0) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return;
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return;
}
li -= opli;
tptr = pptr;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(esis_option_values,"Unknown",op),
op,
opli));
switch (op) {
case ESIS_OPTION_ES_CONF_TIME:
if (opli == 2) {
ND_TCHECK2(*pptr, 2);
ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr)));
} else
ND_PRINT((ndo, "(bad length)"));
break;
case ESIS_OPTION_PROTOCOLS:
while (opli>0) {
ND_TCHECK(*pptr);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (opli>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
opli--;
}
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
case ESIS_OPTION_QOS_MAINTENANCE:
case ESIS_OPTION_SECURITY:
case ESIS_OPTION_PRIORITY:
case ESIS_OPTION_ADDRESS_MASK:
case ESIS_OPTION_SNPA_MASK:
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
trunc:
return;
}
static void
isis_print_mcid(netdissect_options *ndo,
const struct isis_spb_mcid *mcid)
{
int i;
ND_TCHECK(*mcid);
ND_PRINT((ndo, "ID: %d, Name: ", mcid->format_id));
if (fn_printzp(ndo, mcid->name, 32, ndo->ndo_snapend))
goto trunc;
ND_PRINT((ndo, "\n\t Lvl: %d", EXTRACT_16BITS(mcid->revision_lvl)));
ND_PRINT((ndo, ", Digest: "));
for(i=0;i<16;i++)
ND_PRINT((ndo, "%.2x ", mcid->digest[i]));
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static int
isis_print_mt_port_cap_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len;
const struct isis_subtlv_spb_mcid *subtlv_spb_mcid;
int i;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
/*len -= TLV_TYPE_LEN_OFFSET;*/
len = len -2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_MCID:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN);
subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr;
ND_PRINT((ndo, "\n\t MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
ND_PRINT((ndo, "\n\t AUX-MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
tptr = tptr + sizeof(struct isis_subtlv_spb_mcid);
len = len - sizeof(struct isis_subtlv_spb_mcid);
break;
}
case ISIS_SUBTLV_SPB_DIGEST:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN);
ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d",
(*(tptr) >> 5), (((*tptr)>> 4) & 0x01),
((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03)));
tptr++;
ND_PRINT((ndo, "\n\t Digest: "));
for(i=1;i<=8; i++)
{
ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr)));
if (i%4 == 0 && i != 8)
ND_PRINT((ndo, "\n\t "));
tptr = tptr + 4;
}
len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_BVID:
{
ND_TCHECK2(*(tptr), stlv_len);
while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN)
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN);
ND_PRINT((ndo, "\n\t ECT: %08x",
EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ",
(EXTRACT_16BITS (tptr) >> 4) ,
(EXTRACT_16BITS (tptr) >> 3) & 0x01,
(EXTRACT_16BITS (tptr) >> 2) & 0x01));
tptr = tptr + 2;
len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
}
break;
}
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static int
isis_print_mt_capability_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len, tmp;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
len = len - 2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_INSTANCE:
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN);
ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr)));
tptr = tptr + 2;
ND_PRINT((ndo, "\n\t RES: %d",
EXTRACT_16BITS(tptr) >> 5));
ND_PRINT((ndo, ", V: %d",
(EXTRACT_16BITS(tptr) >> 4) & 0x0001));
ND_PRINT((ndo, ", SPSource-ID: %d",
(EXTRACT_32BITS(tptr) & 0x000fffff)));
tptr = tptr+4;
ND_PRINT((ndo, ", No of Trees: %x", *(tptr)));
tmp = *(tptr++);
len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
while (tmp)
{
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN);
ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d",
*(tptr) >> 7, (*(tptr) >> 6) & 0x01,
(*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f)));
tptr++;
ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr + 4;
ND_PRINT((ndo, ", BVID: %d, SPVID: %d",
(EXTRACT_24BITS(tptr) >> 12) & 0x000fff,
EXTRACT_24BITS(tptr) & 0x000fff));
tptr = tptr + 3;
len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
tmp--;
}
break;
case ISIS_SUBTLV_SPBM_SI:
ND_TCHECK2(*tptr, 8);
ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr)));
tptr = tptr+2;
ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12,
(EXTRACT_16BITS(tptr)) & 0x0fff));
tptr = tptr+2;
len = len - 8;
stlv_len = stlv_len - 8;
while (stlv_len >= 4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d",
(EXTRACT_32BITS(tptr) >> 31),
(EXTRACT_32BITS(tptr) >> 30) & 0x01,
(EXTRACT_32BITS(tptr) >> 24) & 0x03f,
(EXTRACT_32BITS(tptr)) & 0x0ffffff));
tptr = tptr + 4;
len = len - 4;
stlv_len = stlv_len - 4;
}
break;
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
/* shared routine for printing system, node and lsp-ids */
static char *
isis_print_id(const uint8_t *cp, int id_len)
{
int i;
static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")];
char *pos = id;
for (i = 1; i <= SYSTEM_ID_LEN; i++) {
snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++);
pos += strlen(pos);
if (i == 2 || i == 4)
*pos++ = '.';
}
if (id_len >= NODE_ID_LEN) {
snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++);
pos += strlen(pos);
}
if (id_len == LSP_ID_LEN)
snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp);
return (id);
}
/* print the 4-byte metric block which is common found in the old-style TLVs */
static int
isis_print_metric_block(netdissect_options *ndo,
const struct isis_metric_block *isis_metric_block)
{
ND_PRINT((ndo, ", Default Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_default),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_delay))
ND_PRINT((ndo, "\n\t\t Delay Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_delay),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_expense))
ND_PRINT((ndo, "\n\t\t Expense Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_expense),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_error))
ND_PRINT((ndo, "\n\t\t Error Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_error),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_error) ? "External" : "Internal"));
return(1); /* everything is ok */
}
static int
isis_print_tlv_ip_reach(netdissect_options *ndo,
const uint8_t *cp, const char *ident, int length)
{
int prefix_len;
const struct isis_tlv_ip_reach *tlv_ip_reach;
tlv_ip_reach = (const struct isis_tlv_ip_reach *)cp;
while (length > 0) {
if ((size_t)length < sizeof(*tlv_ip_reach)) {
ND_PRINT((ndo, "short IPv4 Reachability (%d vs %lu)",
length,
(unsigned long)sizeof(*tlv_ip_reach)));
return (0);
}
if (!ND_TTEST(*tlv_ip_reach))
return (0);
prefix_len = mask2plen(EXTRACT_32BITS(tlv_ip_reach->mask));
if (prefix_len == -1)
ND_PRINT((ndo, "%sIPv4 prefix: %s mask %s",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
ipaddr_string(ndo, (tlv_ip_reach->mask))));
else
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
prefix_len));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u, %s",
ISIS_LSP_TLV_METRIC_UPDOWN(tlv_ip_reach->isis_metric_block.metric_default) ? "down" : "up",
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_default),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_delay))
ND_PRINT((ndo, "%s Delay Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_delay),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_expense))
ND_PRINT((ndo, "%s Expense Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_expense),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_error))
ND_PRINT((ndo, "%s Error Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_error),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_error) ? "External" : "Internal"));
length -= sizeof(struct isis_tlv_ip_reach);
tlv_ip_reach++;
}
return (1);
}
/*
* this is the common IP-REACH subTLV decoder it is called
* from various EXTD-IP REACH TLVs (135,235,236,237)
*/
static int
isis_print_ip_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int subt, int subl,
const char *ident)
{
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_ip_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr,subl);
switch(subt) {
case ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR: /* fall through */
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32:
while (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x (=%u)",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr)));
tptr+=4;
subl-=4;
}
break;
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64:
while (subl >= 8) {
ND_PRINT((ndo, ", 0x%08x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr+4)));
tptr+=8;
subl-=8;
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
ND_PRINT((ndo, "%s", ident));
ND_PRINT((ndo, "%s", tstr));
return(0);
}
/*
* this is the common IS-REACH subTLV decoder it is called
* from isis_print_ext_is_reach()
*/
static int
isis_print_is_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, u_int subt, u_int subl,
const char *ident)
{
u_int te_class,priority_level,gmpls_switch_cap;
union { /* int to float conversion buffer for several subTLVs */
float f;
uint32_t i;
} bw;
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr, subl);
switch(subt) {
case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID:
if (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr)));
if (subl == 8) /* rfc4205 */
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR:
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR:
if (subl >= sizeof(struct in_addr))
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW :
case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW:
if (subl >= 4) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW :
if (subl >= 32) {
for (te_class = 0; te_class < 8; te_class++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD:
ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)",
ident,
tok2str(diffserv_te_bc_values, "unknown", *tptr),
*tptr));
tptr++;
/* decode BCs until the subTLV ends */
for (te_class = 0; te_class < (subl-1)/4; te_class++) {
ND_TCHECK2(*tptr, 4);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC:
if (subl >= 3)
ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE:
if (subl == 2) {
ND_PRINT((ndo, ", [ %s ] (0x%04x)",
bittok2str(isis_subtlv_link_attribute_values,
"Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE:
if (subl >= 2) {
ND_PRINT((ndo, ", %s, Priority %u",
bittok2str(gmpls_link_prot_values, "none", *tptr),
*(tptr+1)));
}
break;
case ISIS_SUBTLV_SPB_METRIC:
if (subl >= 6) {
ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr)));
tptr=tptr+3;
ND_PRINT((ndo, ", P: %u", *(tptr)));
tptr++;
ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR:
if (subl >= 36) {
gmpls_switch_cap = *tptr;
ND_PRINT((ndo, "%s Interface Switching Capability:%s",
ident,
tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap)));
ND_PRINT((ndo, ", LSP Encoding: %s",
tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1))));
tptr+=4;
ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident));
for (priority_level = 0; priority_level < 8; priority_level++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s priority level %d: %.3f Mbps",
ident,
priority_level,
bw.f * 8 / 1000000));
tptr+=4;
}
subl-=36;
switch (gmpls_switch_cap) {
case GMPLS_PSC1:
case GMPLS_PSC2:
case GMPLS_PSC3:
case GMPLS_PSC4:
ND_TCHECK2(*tptr, 6);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4)));
break;
case GMPLS_TSC:
ND_TCHECK2(*tptr, 8);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Indication %s", ident,
tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4))));
break;
default:
/* there is some optional stuff left to decode but this is as of yet
not specified so just lets hexdump what is left */
if(subl>0){
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
}
}
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
return(0);
}
/*
* this is the common IS-REACH decoder it is called
* from various EXTD-IS REACH style TLVs (22,24,222)
*/
static int
isis_print_ext_is_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, int tlv_type)
{
char ident_buffer[20];
int subtlv_type,subtlv_len,subtlv_sum_len;
int proc_bytes = 0; /* how many bytes did we process ? */
if (!ND_TTEST2(*tptr, NODE_ID_LEN))
return(0);
ND_PRINT((ndo, "%sIS Neighbor: %s", ident, isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
if (tlv_type != ISIS_TLV_IS_ALIAS_ID) { /* the Alias TLV Metric field is implicit 0 */
if (!ND_TTEST2(*tptr, 3)) /* and is therefore skipped */
return(0);
ND_PRINT((ndo, ", Metric: %d", EXTRACT_24BITS(tptr)));
tptr+=3;
}
if (!ND_TTEST2(*tptr, 1))
return(0);
subtlv_sum_len=*(tptr++); /* read out subTLV length */
proc_bytes=NODE_ID_LEN+3+1;
ND_PRINT((ndo, ", %ssub-TLVs present",subtlv_sum_len ? "" : "no "));
if (subtlv_sum_len) {
ND_PRINT((ndo, " (%u)", subtlv_sum_len));
while (subtlv_sum_len>0) {
if (!ND_TTEST2(*tptr,2))
return(0);
subtlv_type=*(tptr++);
subtlv_len=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_is_reach_subtlv(ndo, tptr, subtlv_type, subtlv_len, ident_buffer))
return(0);
tptr+=subtlv_len;
subtlv_sum_len-=(subtlv_len+2);
proc_bytes+=(subtlv_len+2);
}
}
return(proc_bytes);
}
/*
* this is the common Multi Topology ID decoder
* it is called from various MT-TLVs (222,229,235,237)
*/
static int
isis_print_mtid(netdissect_options *ndo,
const uint8_t *tptr, const char *ident)
{
if (!ND_TTEST2(*tptr, 2))
return(0);
ND_PRINT((ndo, "%s%s",
ident,
tok2str(isis_mt_values,
"Reserved for IETF Consensus",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)))));
ND_PRINT((ndo, " Topology (0x%03x), Flags: [%s]",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)),
bittok2str(isis_mt_flag_values, "none",ISIS_MASK_MTFLAGS(EXTRACT_16BITS(tptr)))));
return(2);
}
/*
* this is the common extended IP reach decoder
* it is called from TLVs (135,235,236,237)
* we process the TLV and optional subTLVs and return
* the amount of processed bytes
*/
static int
isis_print_extd_ip_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, uint16_t afi)
{
char ident_buffer[20];
uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */
u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen;
if (!ND_TTEST2(*tptr, 4))
return (0);
metric = EXTRACT_32BITS(tptr);
processed=4;
tptr+=4;
if (afi == AF_INET) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */
return (0);
status_byte=*(tptr++);
bit_length = status_byte&0x3f;
if (bit_length > 32) {
ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed++;
} else if (afi == AF_INET6) {
if (!ND_TTEST2(*tptr, 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_2702_0 |
crossvul-cpp_data_bad_4019_0 | /* exif-mnote-data-canon.c
*
* Copyright (c) 2002, 2003 Lutz Mueller <lutz@users.sourceforge.net>
* Copyright (c) 2003 Matthieu Castet <mat-c@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-canon.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <libexif/exif-byte-order.h>
#include <libexif/exif-utils.h>
#include <libexif/exif-data.h>
static void
exif_mnote_data_canon_clear (ExifMnoteDataCanon *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_canon_free (ExifMnoteData *n)
{
if (!n) return;
exif_mnote_data_canon_clear ((ExifMnoteDataCanon *) n);
}
static void
exif_mnote_data_canon_get_tags (ExifMnoteDataCanon *dc, unsigned int n,
unsigned int *m, unsigned int *s)
{
unsigned int from = 0, to;
if (!dc || !m) return;
for (*m = 0; *m < dc->count; (*m)++) {
to = from + mnote_canon_entry_count_values (&dc->entries[*m]);
if (to > n) {
if (s) *s = n - from;
break;
}
from = to;
}
}
static char *
exif_mnote_data_canon_get_value (ExifMnoteData *note, unsigned int n, char *val, unsigned int maxlen)
{
ExifMnoteDataCanon *dc = (ExifMnoteDataCanon *) note;
unsigned int m, s;
if (!dc) return NULL;
exif_mnote_data_canon_get_tags (dc, n, &m, &s);
if (m >= dc->count) return NULL;
return mnote_canon_entry_get_value (&dc->entries[m], s, val, maxlen);
}
static void
exif_mnote_data_canon_set_byte_order (ExifMnoteData *d, ExifByteOrder o)
{
ExifByteOrder o_orig;
ExifMnoteDataCanon *n = (ExifMnoteDataCanon *) 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_canon_set_offset (ExifMnoteData *n, unsigned int o)
{
if (n) ((ExifMnoteDataCanon *) n)->offset = o;
}
static void
exif_mnote_data_canon_save (ExifMnoteData *ne,
unsigned char **buf, unsigned int *buf_size)
{
ExifMnoteDataCanon *n = (ExifMnoteDataCanon *) ne;
size_t i, o, s, doff;
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 = 2 + n->count * 12 + 4;
*buf = exif_mem_alloc (ne->mem, sizeof (char) * *buf_size);
if (!*buf) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteCanon", *buf_size);
return;
}
/* Save the number of entries */
exif_set_short (*buf, n->order, (ExifShort) n->count);
/* Save each entry */
for (i = 0; i < n->count; i++) {
o = 2 + i * 12;
exif_set_short (*buf + o + 0, n->order, (ExifShort) n->entries[i].tag);
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) {
ts = *buf_size + s;
/* Ensure even offsets. Set padding bytes to 0. */
if (s & 1) ts += 1;
t = exif_mem_realloc (ne->mem, *buf,
sizeof (char) * ts);
if (!t) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteCanon", ts);
return;
}
*buf = t;
*buf_size = ts;
doff = *buf_size - s;
if (s & 1) { doff--; *(*buf + *buf_size - 1) = '\0'; }
exif_set_long (*buf + o, n->order, n->offset + doff);
} else
doff = o;
/*
* Write the data. Fill unneeded bytes with 0. Do not
* crash if data is NULL.
*/
if (!n->entries[i].data) memset (*buf + doff, 0, s);
else memcpy (*buf + doff, n->entries[i].data, s);
if (s < 4) memset (*buf + doff + s, 0, (4 - s));
}
}
/* XXX
* FIXME: exif_mnote_data_canon_load() may fail and there is no
* semantics to express that.
* See bug #1054323 for details, especially the comment by liblit
* after it has supposedly been fixed:
*
* https://sourceforge.net/tracker/?func=detail&aid=1054323&group_id=12272&atid=112272
* Unfortunately, the "return" statements aren't commented at
* all, so it isn't trivial to find out what is a normal
* return, and what is a reaction to an error condition.
*/
static void
exif_mnote_data_canon_load (ExifMnoteData *ne,
const unsigned char *buf, unsigned int buf_size)
{
ExifMnoteDataCanon *n = (ExifMnoteDataCanon *) ne;
ExifShort c;
size_t i, tcount, o, datao;
if (!n || !buf || !buf_size) {
exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteCanon", "Short MakerNote");
return;
}
datao = 6 + n->offset;
if ((datao + 2 < datao) || (datao + 2 < 2) || (datao + 2 > buf_size)) {
exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteCanon", "Short MakerNote");
return;
}
/* Read the number of tags */
c = exif_get_short (buf + datao, n->order);
datao += 2;
/* Remove any old entries */
exif_mnote_data_canon_clear (n);
/* Reserve enough space for all the possible MakerNote tags */
n->entries = exif_mem_alloc (ne->mem, sizeof (MnoteCanonEntry) * c);
if (!n->entries) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteCanon", sizeof (MnoteCanonEntry) * c);
return;
}
/* Parse the entries */
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 (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteCanon", "Short MakerNote");
break;
}
n->entries[tcount].tag = exif_get_short (buf + o, n->order);
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 (ne->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteCanon",
"Loading entry 0x%x ('%s')...", n->entries[tcount].tag,
mnote_canon_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) {
exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteCanon",
"Invalid zero-length tag size");
continue;
} else {
size_t dataofs = o + 8;
if (s > 4) dataofs = exif_get_long (buf + dataofs, n->order) + 6;
if ((dataofs + s < s) || (dataofs + s < dataofs) || (dataofs + s > buf_size)) {
exif_log (ne->log, EXIF_LOG_CODE_DEBUG,
"ExifMnoteCanon",
"Tag data past end of buffer (%u > %u)",
(unsigned)(dataofs + s), buf_size);
continue;
}
n->entries[tcount].data = exif_mem_alloc (ne->mem, s);
if (!n->entries[tcount].data) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteCanon", 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_canon_count (ExifMnoteData *n)
{
ExifMnoteDataCanon *dc = (ExifMnoteDataCanon *) n;
unsigned int i, c;
for (i = c = 0; dc && (i < dc->count); i++)
c += mnote_canon_entry_count_values (&dc->entries[i]);
return c;
}
static unsigned int
exif_mnote_data_canon_get_id (ExifMnoteData *d, unsigned int i)
{
ExifMnoteDataCanon *dc = (ExifMnoteDataCanon *) d;
unsigned int m;
if (!dc) return 0;
exif_mnote_data_canon_get_tags (dc, i, &m, NULL);
if (m >= dc->count) return 0;
return dc->entries[m].tag;
}
static const char *
exif_mnote_data_canon_get_name (ExifMnoteData *note, unsigned int i)
{
ExifMnoteDataCanon *dc = (ExifMnoteDataCanon *) note;
unsigned int m, s;
if (!dc) return NULL;
exif_mnote_data_canon_get_tags (dc, i, &m, &s);
if (m >= dc->count) return NULL;
return mnote_canon_tag_get_name_sub (dc->entries[m].tag, s, dc->options);
}
static const char *
exif_mnote_data_canon_get_title (ExifMnoteData *note, unsigned int i)
{
ExifMnoteDataCanon *dc = (ExifMnoteDataCanon *) note;
unsigned int m, s;
if (!dc) return NULL;
exif_mnote_data_canon_get_tags (dc, i, &m, &s);
if (m >= dc->count) return NULL;
return mnote_canon_tag_get_title_sub (dc->entries[m].tag, s, dc->options);
}
static const char *
exif_mnote_data_canon_get_description (ExifMnoteData *note, unsigned int i)
{
ExifMnoteDataCanon *dc = (ExifMnoteDataCanon *) note;
unsigned int m;
if (!dc) return NULL;
exif_mnote_data_canon_get_tags (dc, i, &m, NULL);
if (m >= dc->count) return NULL;
return mnote_canon_tag_get_description (dc->entries[m].tag);
}
int
exif_mnote_data_canon_identify (const ExifData *ed, const ExifEntry *e)
{
char value[8];
(void) e; /* unused */
ExifEntry *em = exif_data_get_entry (ed, EXIF_TAG_MAKE);
if (!em)
return 0;
return !strcmp (exif_entry_get_value (em, value, sizeof (value)), "Canon");
}
ExifMnoteData *
exif_mnote_data_canon_new (ExifMem *mem, ExifDataOption o)
{
ExifMnoteData *d;
ExifMnoteDataCanon *dc;
if (!mem) return NULL;
d = exif_mem_alloc (mem, sizeof (ExifMnoteDataCanon));
if (!d)
return NULL;
exif_mnote_data_construct (d, mem);
/* Set up function pointers */
d->methods.free = exif_mnote_data_canon_free;
d->methods.set_byte_order = exif_mnote_data_canon_set_byte_order;
d->methods.set_offset = exif_mnote_data_canon_set_offset;
d->methods.load = exif_mnote_data_canon_load;
d->methods.save = exif_mnote_data_canon_save;
d->methods.count = exif_mnote_data_canon_count;
d->methods.get_id = exif_mnote_data_canon_get_id;
d->methods.get_name = exif_mnote_data_canon_get_name;
d->methods.get_title = exif_mnote_data_canon_get_title;
d->methods.get_description = exif_mnote_data_canon_get_description;
d->methods.get_value = exif_mnote_data_canon_get_value;
dc = (ExifMnoteDataCanon*)d;
dc->options = o;
return d;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4019_0 |
crossvul-cpp_data_bad_2639_0 | /*
* Copyright (C) Andrew Tridgell 1995-1999
*
* This software may be distributed either under the terms of the
* BSD-style license that accompanies tcpdump or the GNU GPL version 2
* or later
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "netdissect.h"
#include "extract.h"
#include "smb.h"
static uint32_t stringlen;
extern const u_char *startbuf;
/*
* interpret a 32 bit dos packed date/time to some parameters
*/
static void
interpret_dos_date(uint32_t date, struct tm *tp)
{
uint32_t p0, p1, p2, p3;
p0 = date & 0xFF;
p1 = ((date & 0xFF00) >> 8) & 0xFF;
p2 = ((date & 0xFF0000) >> 16) & 0xFF;
p3 = ((date & 0xFF000000) >> 24) & 0xFF;
tp->tm_sec = 2 * (p0 & 0x1F);
tp->tm_min = ((p0 >> 5) & 0xFF) + ((p1 & 0x7) << 3);
tp->tm_hour = (p1 >> 3) & 0xFF;
tp->tm_mday = (p2 & 0x1F);
tp->tm_mon = ((p2 >> 5) & 0xFF) + ((p3 & 0x1) << 3) - 1;
tp->tm_year = ((p3 >> 1) & 0xFF) + 80;
}
/*
* common portion:
* create a unix date from a dos date
*/
static time_t
int_unix_date(uint32_t dos_date)
{
struct tm t;
if (dos_date == 0)
return(0);
interpret_dos_date(dos_date, &t);
t.tm_wday = 1;
t.tm_yday = 1;
t.tm_isdst = 0;
return (mktime(&t));
}
/*
* create a unix date from a dos date
* in network byte order
*/
static time_t
make_unix_date(const u_char *date_ptr)
{
uint32_t dos_date = 0;
dos_date = EXTRACT_LE_32BITS(date_ptr);
return int_unix_date(dos_date);
}
/*
* create a unix date from a dos date
* in halfword-swapped network byte order!
*/
static time_t
make_unix_date2(const u_char *date_ptr)
{
uint32_t x, x2;
x = EXTRACT_LE_32BITS(date_ptr);
x2 = ((x & 0xFFFF) << 16) | ((x & 0xFFFF0000) >> 16);
return int_unix_date(x2);
}
/*
* interpret an 8 byte "filetime" structure to a time_t
* It's originally in "100ns units since jan 1st 1601"
*/
static time_t
interpret_long_date(const u_char *p)
{
double d;
time_t ret;
/* this gives us seconds since jan 1st 1601 (approx) */
d = (EXTRACT_LE_32BITS(p + 4) * 256.0 + p[3]) * (1.0e-7 * (1 << 24));
/* now adjust by 369 years to make the secs since 1970 */
d -= 369.0 * 365.25 * 24 * 60 * 60;
/* and a fudge factor as we got it wrong by a few days */
d += (3 * 24 * 60 * 60 + 6 * 60 * 60 + 2);
if (d < 0)
return(0);
ret = (time_t)d;
return(ret);
}
/*
* interpret the weird netbios "name". Return the name type, or -1 if
* we run past the end of the buffer
*/
static int
name_interpret(netdissect_options *ndo,
const u_char *in, const u_char *maxbuf, char *out)
{
int ret;
int len;
if (in >= maxbuf)
return(-1); /* name goes past the end of the buffer */
ND_TCHECK2(*in, 1);
len = (*in++) / 2;
*out=0;
if (len > 30 || len < 1)
return(0);
while (len--) {
ND_TCHECK2(*in, 2);
if (in + 1 >= maxbuf)
return(-1); /* name goes past the end of the buffer */
if (in[0] < 'A' || in[0] > 'P' || in[1] < 'A' || in[1] > 'P') {
*out = 0;
return(0);
}
*out = ((in[0] - 'A') << 4) + (in[1] - 'A');
in += 2;
out++;
}
*out = 0;
ret = out[-1];
return(ret);
trunc:
return(-1);
}
/*
* find a pointer to a netbios name
*/
static const u_char *
name_ptr(netdissect_options *ndo,
const u_char *buf, int ofs, const u_char *maxbuf)
{
const u_char *p;
u_char c;
p = buf + ofs;
if (p >= maxbuf)
return(NULL); /* name goes past the end of the buffer */
ND_TCHECK2(*p, 1);
c = *p;
/* XXX - this should use the same code that the DNS dissector does */
if ((c & 0xC0) == 0xC0) {
uint16_t l;
ND_TCHECK2(*p, 2);
if ((p + 1) >= maxbuf)
return(NULL); /* name goes past the end of the buffer */
l = EXTRACT_16BITS(p) & 0x3FFF;
if (l == 0) {
/* We have a pointer that points to itself. */
return(NULL);
}
p = buf + l;
if (p >= maxbuf)
return(NULL); /* name goes past the end of the buffer */
ND_TCHECK2(*p, 1);
}
return(p);
trunc:
return(NULL); /* name goes past the end of the buffer */
}
/*
* extract a netbios name from a buf
*/
static int
name_extract(netdissect_options *ndo,
const u_char *buf, int ofs, const u_char *maxbuf, char *name)
{
const u_char *p = name_ptr(ndo, buf, ofs, maxbuf);
if (p == NULL)
return(-1); /* error (probably name going past end of buffer) */
name[0] = '\0';
return(name_interpret(ndo, p, maxbuf, name));
}
/*
* return the total storage length of a mangled name
*/
static int
name_len(netdissect_options *ndo,
const unsigned char *s, const unsigned char *maxbuf)
{
const unsigned char *s0 = s;
unsigned char c;
if (s >= maxbuf)
return(-1); /* name goes past the end of the buffer */
ND_TCHECK2(*s, 1);
c = *s;
if ((c & 0xC0) == 0xC0)
return(2);
while (*s) {
if (s >= maxbuf)
return(-1); /* name goes past the end of the buffer */
ND_TCHECK2(*s, 1);
s += (*s) + 1;
}
return(PTR_DIFF(s, s0) + 1);
trunc:
return(-1); /* name goes past the end of the buffer */
}
static void
print_asc(netdissect_options *ndo,
const unsigned char *buf, int len)
{
int i;
for (i = 0; i < len; i++)
safeputchar(ndo, buf[i]);
}
static const char *
name_type_str(int name_type)
{
const char *f = NULL;
switch (name_type) {
case 0: f = "Workstation"; break;
case 0x03: f = "Client?"; break;
case 0x20: f = "Server"; break;
case 0x1d: f = "Master Browser"; break;
case 0x1b: f = "Domain Controller"; break;
case 0x1e: f = "Browser Server"; break;
default: f = "Unknown"; break;
}
return(f);
}
void
smb_print_data(netdissect_options *ndo, const unsigned char *buf, int len)
{
int i = 0;
if (len <= 0)
return;
ND_PRINT((ndo, "[%03X] ", i));
for (i = 0; i < len; /*nothing*/) {
ND_TCHECK(buf[i]);
ND_PRINT((ndo, "%02X ", buf[i] & 0xff));
i++;
if (i%8 == 0)
ND_PRINT((ndo, " "));
if (i % 16 == 0) {
print_asc(ndo, &buf[i - 16], 8);
ND_PRINT((ndo, " "));
print_asc(ndo, &buf[i - 8], 8);
ND_PRINT((ndo, "\n"));
if (i < len)
ND_PRINT((ndo, "[%03X] ", i));
}
}
if (i % 16) {
int n;
n = 16 - (i % 16);
ND_PRINT((ndo, " "));
if (n>8)
ND_PRINT((ndo, " "));
while (n--)
ND_PRINT((ndo, " "));
n = min(8, i % 16);
print_asc(ndo, &buf[i - (i % 16)], n);
ND_PRINT((ndo, " "));
n = (i % 16) - n;
if (n > 0)
print_asc(ndo, &buf[i - n], n);
ND_PRINT((ndo, "\n"));
}
return;
trunc:
ND_PRINT((ndo, "\n"));
ND_PRINT((ndo, "WARNING: Short packet. Try increasing the snap length\n"));
}
static void
write_bits(netdissect_options *ndo,
unsigned int val, const char *fmt)
{
const char *p = fmt;
int i = 0;
while ((p = strchr(fmt, '|'))) {
size_t l = PTR_DIFF(p, fmt);
if (l && (val & (1 << i)))
ND_PRINT((ndo, "%.*s ", (int)l, fmt));
fmt = p + 1;
i++;
}
}
/* convert a UCS-2 string into an ASCII string */
#define MAX_UNISTR_SIZE 1000
static const char *
unistr(netdissect_options *ndo,
const u_char *s, uint32_t *len, int use_unicode)
{
static char buf[MAX_UNISTR_SIZE+1];
size_t l = 0;
uint32_t strsize;
const u_char *sp;
if (use_unicode) {
/*
* Skip padding that puts the string on an even boundary.
*/
if (((s - startbuf) % 2) != 0) {
ND_TCHECK(s[0]);
s++;
}
}
if (*len == 0) {
/*
* Null-terminated string.
*/
strsize = 0;
sp = s;
if (!use_unicode) {
for (;;) {
ND_TCHECK(sp[0]);
*len += 1;
if (sp[0] == 0)
break;
sp++;
}
strsize = *len - 1;
} else {
for (;;) {
ND_TCHECK2(sp[0], 2);
*len += 2;
if (sp[0] == 0 && sp[1] == 0)
break;
sp += 2;
}
strsize = *len - 2;
}
} else {
/*
* Counted string.
*/
strsize = *len;
}
if (!use_unicode) {
while (strsize != 0) {
ND_TCHECK(s[0]);
if (l >= MAX_UNISTR_SIZE)
break;
if (ND_ISPRINT(s[0]))
buf[l] = s[0];
else {
if (s[0] == 0)
break;
buf[l] = '.';
}
l++;
s++;
strsize--;
}
} else {
while (strsize != 0) {
ND_TCHECK2(s[0], 2);
if (l >= MAX_UNISTR_SIZE)
break;
if (s[1] == 0 && ND_ISPRINT(s[0])) {
/* It's a printable ASCII character */
buf[l] = s[0];
} else {
/* It's a non-ASCII character or a non-printable ASCII character */
if (s[0] == 0 && s[1] == 0)
break;
buf[l] = '.';
}
l++;
s += 2;
if (strsize == 1)
break;
strsize -= 2;
}
}
buf[l] = 0;
return buf;
trunc:
return NULL;
}
static const u_char *
smb_fdata1(netdissect_options *ndo,
const u_char *buf, const char *fmt, const u_char *maxbuf,
int unicodestr)
{
int reverse = 0;
const char *attrib_fmt = "READONLY|HIDDEN|SYSTEM|VOLUME|DIR|ARCHIVE|";
while (*fmt && buf<maxbuf) {
switch (*fmt) {
case 'a':
ND_TCHECK(buf[0]);
write_bits(ndo, buf[0], attrib_fmt);
buf++;
fmt++;
break;
case 'A':
ND_TCHECK2(buf[0], 2);
write_bits(ndo, EXTRACT_LE_16BITS(buf), attrib_fmt);
buf += 2;
fmt++;
break;
case '{':
{
char bitfmt[128];
char *p;
int l;
p = strchr(++fmt, '}');
l = PTR_DIFF(p, fmt);
if ((unsigned int)l > sizeof(bitfmt) - 1)
l = sizeof(bitfmt)-1;
strncpy(bitfmt, fmt, l);
bitfmt[l] = '\0';
fmt = p + 1;
ND_TCHECK(buf[0]);
write_bits(ndo, buf[0], bitfmt);
buf++;
break;
}
case 'P':
{
int l = atoi(fmt + 1);
ND_TCHECK2(buf[0], l);
buf += l;
fmt++;
while (isdigit((unsigned char)*fmt))
fmt++;
break;
}
case 'r':
reverse = !reverse;
fmt++;
break;
case 'b':
{
unsigned int x;
ND_TCHECK(buf[0]);
x = buf[0];
ND_PRINT((ndo, "%u (0x%x)", x, x));
buf += 1;
fmt++;
break;
}
case 'd':
{
unsigned int x;
ND_TCHECK2(buf[0], 2);
x = reverse ? EXTRACT_16BITS(buf) :
EXTRACT_LE_16BITS(buf);
ND_PRINT((ndo, "%d (0x%x)", x, x));
buf += 2;
fmt++;
break;
}
case 'D':
{
unsigned int x;
ND_TCHECK2(buf[0], 4);
x = reverse ? EXTRACT_32BITS(buf) :
EXTRACT_LE_32BITS(buf);
ND_PRINT((ndo, "%d (0x%x)", x, x));
buf += 4;
fmt++;
break;
}
case 'L':
{
uint64_t x;
ND_TCHECK2(buf[0], 8);
x = reverse ? EXTRACT_64BITS(buf) :
EXTRACT_LE_64BITS(buf);
ND_PRINT((ndo, "%" PRIu64 " (0x%" PRIx64 ")", x, x));
buf += 8;
fmt++;
break;
}
case 'M':
{
/* Weird mixed-endian length values in 64-bit locks */
uint32_t x1, x2;
uint64_t x;
ND_TCHECK2(buf[0], 8);
x1 = reverse ? EXTRACT_32BITS(buf) :
EXTRACT_LE_32BITS(buf);
x2 = reverse ? EXTRACT_32BITS(buf + 4) :
EXTRACT_LE_32BITS(buf + 4);
x = (((uint64_t)x1) << 32) | x2;
ND_PRINT((ndo, "%" PRIu64 " (0x%" PRIx64 ")", x, x));
buf += 8;
fmt++;
break;
}
case 'B':
{
unsigned int x;
ND_TCHECK(buf[0]);
x = buf[0];
ND_PRINT((ndo, "0x%X", x));
buf += 1;
fmt++;
break;
}
case 'w':
{
unsigned int x;
ND_TCHECK2(buf[0], 2);
x = reverse ? EXTRACT_16BITS(buf) :
EXTRACT_LE_16BITS(buf);
ND_PRINT((ndo, "0x%X", x));
buf += 2;
fmt++;
break;
}
case 'W':
{
unsigned int x;
ND_TCHECK2(buf[0], 4);
x = reverse ? EXTRACT_32BITS(buf) :
EXTRACT_LE_32BITS(buf);
ND_PRINT((ndo, "0x%X", x));
buf += 4;
fmt++;
break;
}
case 'l':
{
fmt++;
switch (*fmt) {
case 'b':
ND_TCHECK(buf[0]);
stringlen = buf[0];
ND_PRINT((ndo, "%u", stringlen));
buf += 1;
break;
case 'd':
ND_TCHECK2(buf[0], 2);
stringlen = reverse ? EXTRACT_16BITS(buf) :
EXTRACT_LE_16BITS(buf);
ND_PRINT((ndo, "%u", stringlen));
buf += 2;
break;
case 'D':
ND_TCHECK2(buf[0], 4);
stringlen = reverse ? EXTRACT_32BITS(buf) :
EXTRACT_LE_32BITS(buf);
ND_PRINT((ndo, "%u", stringlen));
buf += 4;
break;
}
fmt++;
break;
}
case 'S':
case 'R': /* like 'S', but always ASCII */
{
/*XXX unistr() */
const char *s;
uint32_t len;
len = 0;
s = unistr(ndo, buf, &len, (*fmt == 'R') ? 0 : unicodestr);
if (s == NULL)
goto trunc;
ND_PRINT((ndo, "%s", s));
buf += len;
fmt++;
break;
}
case 'Z':
case 'Y': /* like 'Z', but always ASCII */
{
const char *s;
uint32_t len;
ND_TCHECK(*buf);
if (*buf != 4 && *buf != 2) {
ND_PRINT((ndo, "Error! ASCIIZ buffer of type %u", *buf));
return maxbuf; /* give up */
}
len = 0;
s = unistr(ndo, buf + 1, &len, (*fmt == 'Y') ? 0 : unicodestr);
if (s == NULL)
goto trunc;
ND_PRINT((ndo, "%s", s));
buf += len + 1;
fmt++;
break;
}
case 's':
{
int l = atoi(fmt + 1);
ND_TCHECK2(*buf, l);
ND_PRINT((ndo, "%-*.*s", l, l, buf));
buf += l;
fmt++;
while (isdigit((unsigned char)*fmt))
fmt++;
break;
}
case 'c':
{
ND_TCHECK2(*buf, stringlen);
ND_PRINT((ndo, "%-*.*s", (int)stringlen, (int)stringlen, buf));
buf += stringlen;
fmt++;
while (isdigit((unsigned char)*fmt))
fmt++;
break;
}
case 'C':
{
const char *s;
s = unistr(ndo, buf, &stringlen, unicodestr);
if (s == NULL)
goto trunc;
ND_PRINT((ndo, "%s", s));
buf += stringlen;
fmt++;
break;
}
case 'h':
{
int l = atoi(fmt + 1);
ND_TCHECK2(*buf, l);
while (l--)
ND_PRINT((ndo, "%02x", *buf++));
fmt++;
while (isdigit((unsigned char)*fmt))
fmt++;
break;
}
case 'n':
{
int t = atoi(fmt+1);
char nbuf[255];
int name_type;
int len;
switch (t) {
case 1:
name_type = name_extract(ndo, startbuf, PTR_DIFF(buf, startbuf),
maxbuf, nbuf);
if (name_type < 0)
goto trunc;
len = name_len(ndo, buf, maxbuf);
if (len < 0)
goto trunc;
buf += len;
ND_PRINT((ndo, "%-15.15s NameType=0x%02X (%s)", nbuf, name_type,
name_type_str(name_type)));
break;
case 2:
ND_TCHECK(buf[15]);
name_type = buf[15];
ND_PRINT((ndo, "%-15.15s NameType=0x%02X (%s)", buf, name_type,
name_type_str(name_type)));
buf += 16;
break;
}
fmt++;
while (isdigit((unsigned char)*fmt))
fmt++;
break;
}
case 'T':
{
time_t t;
struct tm *lt;
const char *tstring;
uint32_t x;
switch (atoi(fmt + 1)) {
case 1:
ND_TCHECK2(buf[0], 4);
x = EXTRACT_LE_32BITS(buf);
if (x == 0 || x == 0xFFFFFFFF)
t = 0;
else
t = make_unix_date(buf);
buf += 4;
break;
case 2:
ND_TCHECK2(buf[0], 4);
x = EXTRACT_LE_32BITS(buf);
if (x == 0 || x == 0xFFFFFFFF)
t = 0;
else
t = make_unix_date2(buf);
buf += 4;
break;
case 3:
ND_TCHECK2(buf[0], 8);
t = interpret_long_date(buf);
buf += 8;
break;
default:
t = 0;
break;
}
if (t != 0) {
lt = localtime(&t);
if (lt != NULL)
tstring = asctime(lt);
else
tstring = "(Can't convert time)\n";
} else
tstring = "NULL\n";
ND_PRINT((ndo, "%s", tstring));
fmt++;
while (isdigit((unsigned char)*fmt))
fmt++;
break;
}
default:
ND_PRINT((ndo, "%c", *fmt));
fmt++;
break;
}
}
if (buf >= maxbuf && *fmt)
ND_PRINT((ndo, "END OF BUFFER\n"));
return(buf);
trunc:
ND_PRINT((ndo, "\n"));
ND_PRINT((ndo, "WARNING: Short packet. Try increasing the snap length\n"));
return(NULL);
}
const u_char *
smb_fdata(netdissect_options *ndo,
const u_char *buf, const char *fmt, const u_char *maxbuf,
int unicodestr)
{
static int depth = 0;
char s[128];
char *p;
while (*fmt) {
switch (*fmt) {
case '*':
fmt++;
while (buf < maxbuf) {
const u_char *buf2;
depth++;
buf2 = smb_fdata(ndo, buf, fmt, maxbuf, unicodestr);
depth--;
if (buf2 == NULL)
return(NULL);
if (buf2 == buf)
return(buf);
buf = buf2;
}
return(buf);
case '|':
fmt++;
if (buf >= maxbuf)
return(buf);
break;
case '%':
fmt++;
buf = maxbuf;
break;
case '#':
fmt++;
return(buf);
break;
case '[':
fmt++;
if (buf >= maxbuf)
return(buf);
memset(s, 0, sizeof(s));
p = strchr(fmt, ']');
if ((size_t)(p - fmt + 1) > sizeof(s)) {
/* overrun */
return(buf);
}
strncpy(s, fmt, p - fmt);
s[p - fmt] = '\0';
fmt = p + 1;
buf = smb_fdata1(ndo, buf, s, maxbuf, unicodestr);
if (buf == NULL)
return(NULL);
break;
default:
ND_PRINT((ndo, "%c", *fmt));
fmt++;
break;
}
}
if (!depth && buf < maxbuf) {
size_t len = PTR_DIFF(maxbuf, buf);
ND_PRINT((ndo, "Data: (%lu bytes)\n", (unsigned long)len));
smb_print_data(ndo, buf, len);
return(buf + len);
}
return(buf);
}
typedef struct {
const char *name;
int code;
const char *message;
} err_code_struct;
/* DOS Error Messages */
static const err_code_struct dos_msgs[] = {
{ "ERRbadfunc", 1, "Invalid function." },
{ "ERRbadfile", 2, "File not found." },
{ "ERRbadpath", 3, "Directory invalid." },
{ "ERRnofids", 4, "No file descriptors available" },
{ "ERRnoaccess", 5, "Access denied." },
{ "ERRbadfid", 6, "Invalid file handle." },
{ "ERRbadmcb", 7, "Memory control blocks destroyed." },
{ "ERRnomem", 8, "Insufficient server memory to perform the requested function." },
{ "ERRbadmem", 9, "Invalid memory block address." },
{ "ERRbadenv", 10, "Invalid environment." },
{ "ERRbadformat", 11, "Invalid format." },
{ "ERRbadaccess", 12, "Invalid open mode." },
{ "ERRbaddata", 13, "Invalid data." },
{ "ERR", 14, "reserved." },
{ "ERRbaddrive", 15, "Invalid drive specified." },
{ "ERRremcd", 16, "A Delete Directory request attempted to remove the server's current directory." },
{ "ERRdiffdevice", 17, "Not same device." },
{ "ERRnofiles", 18, "A File Search command can find no more files matching the specified criteria." },
{ "ERRbadshare", 32, "The sharing mode specified for an Open conflicts with existing FIDs on the file." },
{ "ERRlock", 33, "A Lock request conflicted with an existing lock or specified an invalid mode, or an Unlock requested attempted to remove a lock held by another process." },
{ "ERRfilexists", 80, "The file named in a Create Directory, Make New File or Link request already exists." },
{ "ERRbadpipe", 230, "Pipe invalid." },
{ "ERRpipebusy", 231, "All instances of the requested pipe are busy." },
{ "ERRpipeclosing", 232, "Pipe close in progress." },
{ "ERRnotconnected", 233, "No process on other end of pipe." },
{ "ERRmoredata", 234, "There is more data to be returned." },
{ NULL, -1, NULL }
};
/* Server Error Messages */
static const err_code_struct server_msgs[] = {
{ "ERRerror", 1, "Non-specific error code." },
{ "ERRbadpw", 2, "Bad password - name/password pair in a Tree Connect or Session Setup are invalid." },
{ "ERRbadtype", 3, "reserved." },
{ "ERRaccess", 4, "The requester does not have the necessary access rights within the specified context for the requested function. The context is defined by the TID or the UID." },
{ "ERRinvnid", 5, "The tree ID (TID) specified in a command was invalid." },
{ "ERRinvnetname", 6, "Invalid network name in tree connect." },
{ "ERRinvdevice", 7, "Invalid device - printer request made to non-printer connection or non-printer request made to printer connection." },
{ "ERRqfull", 49, "Print queue full (files) -- returned by open print file." },
{ "ERRqtoobig", 50, "Print queue full -- no space." },
{ "ERRqeof", 51, "EOF on print queue dump." },
{ "ERRinvpfid", 52, "Invalid print file FID." },
{ "ERRsmbcmd", 64, "The server did not recognize the command received." },
{ "ERRsrverror", 65, "The server encountered an internal error, e.g., system file unavailable." },
{ "ERRfilespecs", 67, "The file handle (FID) and pathname parameters contained an invalid combination of values." },
{ "ERRreserved", 68, "reserved." },
{ "ERRbadpermits", 69, "The access permissions specified for a file or directory are not a valid combination. The server cannot set the requested attribute." },
{ "ERRreserved", 70, "reserved." },
{ "ERRsetattrmode", 71, "The attribute mode in the Set File Attribute request is invalid." },
{ "ERRpaused", 81, "Server is paused." },
{ "ERRmsgoff", 82, "Not receiving messages." },
{ "ERRnoroom", 83, "No room to buffer message." },
{ "ERRrmuns", 87, "Too many remote user names." },
{ "ERRtimeout", 88, "Operation timed out." },
{ "ERRnoresource", 89, "No resources currently available for request." },
{ "ERRtoomanyuids", 90, "Too many UIDs active on this session." },
{ "ERRbaduid", 91, "The UID is not known as a valid ID on this session." },
{ "ERRusempx", 250, "Temp unable to support Raw, use MPX mode." },
{ "ERRusestd", 251, "Temp unable to support Raw, use standard read/write." },
{ "ERRcontmpx", 252, "Continue in MPX mode." },
{ "ERRreserved", 253, "reserved." },
{ "ERRreserved", 254, "reserved." },
{ "ERRnosupport", 0xFFFF, "Function not supported." },
{ NULL, -1, NULL }
};
/* Hard Error Messages */
static const err_code_struct hard_msgs[] = {
{ "ERRnowrite", 19, "Attempt to write on write-protected diskette." },
{ "ERRbadunit", 20, "Unknown unit." },
{ "ERRnotready", 21, "Drive not ready." },
{ "ERRbadcmd", 22, "Unknown command." },
{ "ERRdata", 23, "Data error (CRC)." },
{ "ERRbadreq", 24, "Bad request structure length." },
{ "ERRseek", 25 , "Seek error." },
{ "ERRbadmedia", 26, "Unknown media type." },
{ "ERRbadsector", 27, "Sector not found." },
{ "ERRnopaper", 28, "Printer out of paper." },
{ "ERRwrite", 29, "Write fault." },
{ "ERRread", 30, "Read fault." },
{ "ERRgeneral", 31, "General failure." },
{ "ERRbadshare", 32, "A open conflicts with an existing open." },
{ "ERRlock", 33, "A Lock request conflicted with an existing lock or specified an invalid mode, or an Unlock requested attempted to remove a lock held by another process." },
{ "ERRwrongdisk", 34, "The wrong disk was found in a drive." },
{ "ERRFCBUnavail", 35, "No FCBs are available to process request." },
{ "ERRsharebufexc", 36, "A sharing buffer has been exceeded." },
{ NULL, -1, NULL }
};
static const struct {
int code;
const char *class;
const err_code_struct *err_msgs;
} err_classes[] = {
{ 0, "SUCCESS", NULL },
{ 0x01, "ERRDOS", dos_msgs },
{ 0x02, "ERRSRV", server_msgs },
{ 0x03, "ERRHRD", hard_msgs },
{ 0x04, "ERRXOS", NULL },
{ 0xE1, "ERRRMX1", NULL },
{ 0xE2, "ERRRMX2", NULL },
{ 0xE3, "ERRRMX3", NULL },
{ 0xFF, "ERRCMD", NULL },
{ -1, NULL, NULL }
};
/*
* return a SMB error string from a SMB buffer
*/
char *
smb_errstr(int class, int num)
{
static char ret[128];
int i, j;
ret[0] = 0;
for (i = 0; err_classes[i].class; i++)
if (err_classes[i].code == class) {
if (err_classes[i].err_msgs) {
const err_code_struct *err = err_classes[i].err_msgs;
for (j = 0; err[j].name; j++)
if (num == err[j].code) {
snprintf(ret, sizeof(ret), "%s - %s (%s)",
err_classes[i].class, err[j].name, err[j].message);
return ret;
}
}
snprintf(ret, sizeof(ret), "%s - %d", err_classes[i].class, num);
return ret;
}
snprintf(ret, sizeof(ret), "ERROR: Unknown error (%d,%d)", class, num);
return(ret);
}
typedef struct {
uint32_t code;
const char *name;
} nt_err_code_struct;
/*
* NT Error codes
*/
static const nt_err_code_struct nt_errors[] = {
{ 0x00000000, "STATUS_SUCCESS" },
{ 0x00000000, "STATUS_WAIT_0" },
{ 0x00000001, "STATUS_WAIT_1" },
{ 0x00000002, "STATUS_WAIT_2" },
{ 0x00000003, "STATUS_WAIT_3" },
{ 0x0000003F, "STATUS_WAIT_63" },
{ 0x00000080, "STATUS_ABANDONED" },
{ 0x00000080, "STATUS_ABANDONED_WAIT_0" },
{ 0x000000BF, "STATUS_ABANDONED_WAIT_63" },
{ 0x000000C0, "STATUS_USER_APC" },
{ 0x00000100, "STATUS_KERNEL_APC" },
{ 0x00000101, "STATUS_ALERTED" },
{ 0x00000102, "STATUS_TIMEOUT" },
{ 0x00000103, "STATUS_PENDING" },
{ 0x00000104, "STATUS_REPARSE" },
{ 0x00000105, "STATUS_MORE_ENTRIES" },
{ 0x00000106, "STATUS_NOT_ALL_ASSIGNED" },
{ 0x00000107, "STATUS_SOME_NOT_MAPPED" },
{ 0x00000108, "STATUS_OPLOCK_BREAK_IN_PROGRESS" },
{ 0x00000109, "STATUS_VOLUME_MOUNTED" },
{ 0x0000010A, "STATUS_RXACT_COMMITTED" },
{ 0x0000010B, "STATUS_NOTIFY_CLEANUP" },
{ 0x0000010C, "STATUS_NOTIFY_ENUM_DIR" },
{ 0x0000010D, "STATUS_NO_QUOTAS_FOR_ACCOUNT" },
{ 0x0000010E, "STATUS_PRIMARY_TRANSPORT_CONNECT_FAILED" },
{ 0x00000110, "STATUS_PAGE_FAULT_TRANSITION" },
{ 0x00000111, "STATUS_PAGE_FAULT_DEMAND_ZERO" },
{ 0x00000112, "STATUS_PAGE_FAULT_COPY_ON_WRITE" },
{ 0x00000113, "STATUS_PAGE_FAULT_GUARD_PAGE" },
{ 0x00000114, "STATUS_PAGE_FAULT_PAGING_FILE" },
{ 0x00000115, "STATUS_CACHE_PAGE_LOCKED" },
{ 0x00000116, "STATUS_CRASH_DUMP" },
{ 0x00000117, "STATUS_BUFFER_ALL_ZEROS" },
{ 0x00000118, "STATUS_REPARSE_OBJECT" },
{ 0x0000045C, "STATUS_NO_SHUTDOWN_IN_PROGRESS" },
{ 0x40000000, "STATUS_OBJECT_NAME_EXISTS" },
{ 0x40000001, "STATUS_THREAD_WAS_SUSPENDED" },
{ 0x40000002, "STATUS_WORKING_SET_LIMIT_RANGE" },
{ 0x40000003, "STATUS_IMAGE_NOT_AT_BASE" },
{ 0x40000004, "STATUS_RXACT_STATE_CREATED" },
{ 0x40000005, "STATUS_SEGMENT_NOTIFICATION" },
{ 0x40000006, "STATUS_LOCAL_USER_SESSION_KEY" },
{ 0x40000007, "STATUS_BAD_CURRENT_DIRECTORY" },
{ 0x40000008, "STATUS_SERIAL_MORE_WRITES" },
{ 0x40000009, "STATUS_REGISTRY_RECOVERED" },
{ 0x4000000A, "STATUS_FT_READ_RECOVERY_FROM_BACKUP" },
{ 0x4000000B, "STATUS_FT_WRITE_RECOVERY" },
{ 0x4000000C, "STATUS_SERIAL_COUNTER_TIMEOUT" },
{ 0x4000000D, "STATUS_NULL_LM_PASSWORD" },
{ 0x4000000E, "STATUS_IMAGE_MACHINE_TYPE_MISMATCH" },
{ 0x4000000F, "STATUS_RECEIVE_PARTIAL" },
{ 0x40000010, "STATUS_RECEIVE_EXPEDITED" },
{ 0x40000011, "STATUS_RECEIVE_PARTIAL_EXPEDITED" },
{ 0x40000012, "STATUS_EVENT_DONE" },
{ 0x40000013, "STATUS_EVENT_PENDING" },
{ 0x40000014, "STATUS_CHECKING_FILE_SYSTEM" },
{ 0x40000015, "STATUS_FATAL_APP_EXIT" },
{ 0x40000016, "STATUS_PREDEFINED_HANDLE" },
{ 0x40000017, "STATUS_WAS_UNLOCKED" },
{ 0x40000018, "STATUS_SERVICE_NOTIFICATION" },
{ 0x40000019, "STATUS_WAS_LOCKED" },
{ 0x4000001A, "STATUS_LOG_HARD_ERROR" },
{ 0x4000001B, "STATUS_ALREADY_WIN32" },
{ 0x4000001C, "STATUS_WX86_UNSIMULATE" },
{ 0x4000001D, "STATUS_WX86_CONTINUE" },
{ 0x4000001E, "STATUS_WX86_SINGLE_STEP" },
{ 0x4000001F, "STATUS_WX86_BREAKPOINT" },
{ 0x40000020, "STATUS_WX86_EXCEPTION_CONTINUE" },
{ 0x40000021, "STATUS_WX86_EXCEPTION_LASTCHANCE" },
{ 0x40000022, "STATUS_WX86_EXCEPTION_CHAIN" },
{ 0x40000023, "STATUS_IMAGE_MACHINE_TYPE_MISMATCH_EXE" },
{ 0x40000024, "STATUS_NO_YIELD_PERFORMED" },
{ 0x40000025, "STATUS_TIMER_RESUME_IGNORED" },
{ 0x80000001, "STATUS_GUARD_PAGE_VIOLATION" },
{ 0x80000002, "STATUS_DATATYPE_MISALIGNMENT" },
{ 0x80000003, "STATUS_BREAKPOINT" },
{ 0x80000004, "STATUS_SINGLE_STEP" },
{ 0x80000005, "STATUS_BUFFER_OVERFLOW" },
{ 0x80000006, "STATUS_NO_MORE_FILES" },
{ 0x80000007, "STATUS_WAKE_SYSTEM_DEBUGGER" },
{ 0x8000000A, "STATUS_HANDLES_CLOSED" },
{ 0x8000000B, "STATUS_NO_INHERITANCE" },
{ 0x8000000C, "STATUS_GUID_SUBSTITUTION_MADE" },
{ 0x8000000D, "STATUS_PARTIAL_COPY" },
{ 0x8000000E, "STATUS_DEVICE_PAPER_EMPTY" },
{ 0x8000000F, "STATUS_DEVICE_POWERED_OFF" },
{ 0x80000010, "STATUS_DEVICE_OFF_LINE" },
{ 0x80000011, "STATUS_DEVICE_BUSY" },
{ 0x80000012, "STATUS_NO_MORE_EAS" },
{ 0x80000013, "STATUS_INVALID_EA_NAME" },
{ 0x80000014, "STATUS_EA_LIST_INCONSISTENT" },
{ 0x80000015, "STATUS_INVALID_EA_FLAG" },
{ 0x80000016, "STATUS_VERIFY_REQUIRED" },
{ 0x80000017, "STATUS_EXTRANEOUS_INFORMATION" },
{ 0x80000018, "STATUS_RXACT_COMMIT_NECESSARY" },
{ 0x8000001A, "STATUS_NO_MORE_ENTRIES" },
{ 0x8000001B, "STATUS_FILEMARK_DETECTED" },
{ 0x8000001C, "STATUS_MEDIA_CHANGED" },
{ 0x8000001D, "STATUS_BUS_RESET" },
{ 0x8000001E, "STATUS_END_OF_MEDIA" },
{ 0x8000001F, "STATUS_BEGINNING_OF_MEDIA" },
{ 0x80000020, "STATUS_MEDIA_CHECK" },
{ 0x80000021, "STATUS_SETMARK_DETECTED" },
{ 0x80000022, "STATUS_NO_DATA_DETECTED" },
{ 0x80000023, "STATUS_REDIRECTOR_HAS_OPEN_HANDLES" },
{ 0x80000024, "STATUS_SERVER_HAS_OPEN_HANDLES" },
{ 0x80000025, "STATUS_ALREADY_DISCONNECTED" },
{ 0x80000026, "STATUS_LONGJUMP" },
{ 0x80040111, "MAPI_E_LOGON_FAILED" },
{ 0x80090300, "SEC_E_INSUFFICIENT_MEMORY" },
{ 0x80090301, "SEC_E_INVALID_HANDLE" },
{ 0x80090302, "SEC_E_UNSUPPORTED_FUNCTION" },
{ 0x8009030B, "SEC_E_NO_IMPERSONATION" },
{ 0x8009030D, "SEC_E_UNKNOWN_CREDENTIALS" },
{ 0x8009030E, "SEC_E_NO_CREDENTIALS" },
{ 0x8009030F, "SEC_E_MESSAGE_ALTERED" },
{ 0x80090310, "SEC_E_OUT_OF_SEQUENCE" },
{ 0x80090311, "SEC_E_NO_AUTHENTICATING_AUTHORITY" },
{ 0xC0000001, "STATUS_UNSUCCESSFUL" },
{ 0xC0000002, "STATUS_NOT_IMPLEMENTED" },
{ 0xC0000003, "STATUS_INVALID_INFO_CLASS" },
{ 0xC0000004, "STATUS_INFO_LENGTH_MISMATCH" },
{ 0xC0000005, "STATUS_ACCESS_VIOLATION" },
{ 0xC0000006, "STATUS_IN_PAGE_ERROR" },
{ 0xC0000007, "STATUS_PAGEFILE_QUOTA" },
{ 0xC0000008, "STATUS_INVALID_HANDLE" },
{ 0xC0000009, "STATUS_BAD_INITIAL_STACK" },
{ 0xC000000A, "STATUS_BAD_INITIAL_PC" },
{ 0xC000000B, "STATUS_INVALID_CID" },
{ 0xC000000C, "STATUS_TIMER_NOT_CANCELED" },
{ 0xC000000D, "STATUS_INVALID_PARAMETER" },
{ 0xC000000E, "STATUS_NO_SUCH_DEVICE" },
{ 0xC000000F, "STATUS_NO_SUCH_FILE" },
{ 0xC0000010, "STATUS_INVALID_DEVICE_REQUEST" },
{ 0xC0000011, "STATUS_END_OF_FILE" },
{ 0xC0000012, "STATUS_WRONG_VOLUME" },
{ 0xC0000013, "STATUS_NO_MEDIA_IN_DEVICE" },
{ 0xC0000014, "STATUS_UNRECOGNIZED_MEDIA" },
{ 0xC0000015, "STATUS_NONEXISTENT_SECTOR" },
{ 0xC0000016, "STATUS_MORE_PROCESSING_REQUIRED" },
{ 0xC0000017, "STATUS_NO_MEMORY" },
{ 0xC0000018, "STATUS_CONFLICTING_ADDRESSES" },
{ 0xC0000019, "STATUS_NOT_MAPPED_VIEW" },
{ 0xC000001A, "STATUS_UNABLE_TO_FREE_VM" },
{ 0xC000001B, "STATUS_UNABLE_TO_DELETE_SECTION" },
{ 0xC000001C, "STATUS_INVALID_SYSTEM_SERVICE" },
{ 0xC000001D, "STATUS_ILLEGAL_INSTRUCTION" },
{ 0xC000001E, "STATUS_INVALID_LOCK_SEQUENCE" },
{ 0xC000001F, "STATUS_INVALID_VIEW_SIZE" },
{ 0xC0000020, "STATUS_INVALID_FILE_FOR_SECTION" },
{ 0xC0000021, "STATUS_ALREADY_COMMITTED" },
{ 0xC0000022, "STATUS_ACCESS_DENIED" },
{ 0xC0000023, "STATUS_BUFFER_TOO_SMALL" },
{ 0xC0000024, "STATUS_OBJECT_TYPE_MISMATCH" },
{ 0xC0000025, "STATUS_NONCONTINUABLE_EXCEPTION" },
{ 0xC0000026, "STATUS_INVALID_DISPOSITION" },
{ 0xC0000027, "STATUS_UNWIND" },
{ 0xC0000028, "STATUS_BAD_STACK" },
{ 0xC0000029, "STATUS_INVALID_UNWIND_TARGET" },
{ 0xC000002A, "STATUS_NOT_LOCKED" },
{ 0xC000002B, "STATUS_PARITY_ERROR" },
{ 0xC000002C, "STATUS_UNABLE_TO_DECOMMIT_VM" },
{ 0xC000002D, "STATUS_NOT_COMMITTED" },
{ 0xC000002E, "STATUS_INVALID_PORT_ATTRIBUTES" },
{ 0xC000002F, "STATUS_PORT_MESSAGE_TOO_LONG" },
{ 0xC0000030, "STATUS_INVALID_PARAMETER_MIX" },
{ 0xC0000031, "STATUS_INVALID_QUOTA_LOWER" },
{ 0xC0000032, "STATUS_DISK_CORRUPT_ERROR" },
{ 0xC0000033, "STATUS_OBJECT_NAME_INVALID" },
{ 0xC0000034, "STATUS_OBJECT_NAME_NOT_FOUND" },
{ 0xC0000035, "STATUS_OBJECT_NAME_COLLISION" },
{ 0xC0000037, "STATUS_PORT_DISCONNECTED" },
{ 0xC0000038, "STATUS_DEVICE_ALREADY_ATTACHED" },
{ 0xC0000039, "STATUS_OBJECT_PATH_INVALID" },
{ 0xC000003A, "STATUS_OBJECT_PATH_NOT_FOUND" },
{ 0xC000003B, "STATUS_OBJECT_PATH_SYNTAX_BAD" },
{ 0xC000003C, "STATUS_DATA_OVERRUN" },
{ 0xC000003D, "STATUS_DATA_LATE_ERROR" },
{ 0xC000003E, "STATUS_DATA_ERROR" },
{ 0xC000003F, "STATUS_CRC_ERROR" },
{ 0xC0000040, "STATUS_SECTION_TOO_BIG" },
{ 0xC0000041, "STATUS_PORT_CONNECTION_REFUSED" },
{ 0xC0000042, "STATUS_INVALID_PORT_HANDLE" },
{ 0xC0000043, "STATUS_SHARING_VIOLATION" },
{ 0xC0000044, "STATUS_QUOTA_EXCEEDED" },
{ 0xC0000045, "STATUS_INVALID_PAGE_PROTECTION" },
{ 0xC0000046, "STATUS_MUTANT_NOT_OWNED" },
{ 0xC0000047, "STATUS_SEMAPHORE_LIMIT_EXCEEDED" },
{ 0xC0000048, "STATUS_PORT_ALREADY_SET" },
{ 0xC0000049, "STATUS_SECTION_NOT_IMAGE" },
{ 0xC000004A, "STATUS_SUSPEND_COUNT_EXCEEDED" },
{ 0xC000004B, "STATUS_THREAD_IS_TERMINATING" },
{ 0xC000004C, "STATUS_BAD_WORKING_SET_LIMIT" },
{ 0xC000004D, "STATUS_INCOMPATIBLE_FILE_MAP" },
{ 0xC000004E, "STATUS_SECTION_PROTECTION" },
{ 0xC000004F, "STATUS_EAS_NOT_SUPPORTED" },
{ 0xC0000050, "STATUS_EA_TOO_LARGE" },
{ 0xC0000051, "STATUS_NONEXISTENT_EA_ENTRY" },
{ 0xC0000052, "STATUS_NO_EAS_ON_FILE" },
{ 0xC0000053, "STATUS_EA_CORRUPT_ERROR" },
{ 0xC0000054, "STATUS_FILE_LOCK_CONFLICT" },
{ 0xC0000055, "STATUS_LOCK_NOT_GRANTED" },
{ 0xC0000056, "STATUS_DELETE_PENDING" },
{ 0xC0000057, "STATUS_CTL_FILE_NOT_SUPPORTED" },
{ 0xC0000058, "STATUS_UNKNOWN_REVISION" },
{ 0xC0000059, "STATUS_REVISION_MISMATCH" },
{ 0xC000005A, "STATUS_INVALID_OWNER" },
{ 0xC000005B, "STATUS_INVALID_PRIMARY_GROUP" },
{ 0xC000005C, "STATUS_NO_IMPERSONATION_TOKEN" },
{ 0xC000005D, "STATUS_CANT_DISABLE_MANDATORY" },
{ 0xC000005E, "STATUS_NO_LOGON_SERVERS" },
{ 0xC000005F, "STATUS_NO_SUCH_LOGON_SESSION" },
{ 0xC0000060, "STATUS_NO_SUCH_PRIVILEGE" },
{ 0xC0000061, "STATUS_PRIVILEGE_NOT_HELD" },
{ 0xC0000062, "STATUS_INVALID_ACCOUNT_NAME" },
{ 0xC0000063, "STATUS_USER_EXISTS" },
{ 0xC0000064, "STATUS_NO_SUCH_USER" },
{ 0xC0000065, "STATUS_GROUP_EXISTS" },
{ 0xC0000066, "STATUS_NO_SUCH_GROUP" },
{ 0xC0000067, "STATUS_MEMBER_IN_GROUP" },
{ 0xC0000068, "STATUS_MEMBER_NOT_IN_GROUP" },
{ 0xC0000069, "STATUS_LAST_ADMIN" },
{ 0xC000006A, "STATUS_WRONG_PASSWORD" },
{ 0xC000006B, "STATUS_ILL_FORMED_PASSWORD" },
{ 0xC000006C, "STATUS_PASSWORD_RESTRICTION" },
{ 0xC000006D, "STATUS_LOGON_FAILURE" },
{ 0xC000006E, "STATUS_ACCOUNT_RESTRICTION" },
{ 0xC000006F, "STATUS_INVALID_LOGON_HOURS" },
{ 0xC0000070, "STATUS_INVALID_WORKSTATION" },
{ 0xC0000071, "STATUS_PASSWORD_EXPIRED" },
{ 0xC0000072, "STATUS_ACCOUNT_DISABLED" },
{ 0xC0000073, "STATUS_NONE_MAPPED" },
{ 0xC0000074, "STATUS_TOO_MANY_LUIDS_REQUESTED" },
{ 0xC0000075, "STATUS_LUIDS_EXHAUSTED" },
{ 0xC0000076, "STATUS_INVALID_SUB_AUTHORITY" },
{ 0xC0000077, "STATUS_INVALID_ACL" },
{ 0xC0000078, "STATUS_INVALID_SID" },
{ 0xC0000079, "STATUS_INVALID_SECURITY_DESCR" },
{ 0xC000007A, "STATUS_PROCEDURE_NOT_FOUND" },
{ 0xC000007B, "STATUS_INVALID_IMAGE_FORMAT" },
{ 0xC000007C, "STATUS_NO_TOKEN" },
{ 0xC000007D, "STATUS_BAD_INHERITANCE_ACL" },
{ 0xC000007E, "STATUS_RANGE_NOT_LOCKED" },
{ 0xC000007F, "STATUS_DISK_FULL" },
{ 0xC0000080, "STATUS_SERVER_DISABLED" },
{ 0xC0000081, "STATUS_SERVER_NOT_DISABLED" },
{ 0xC0000082, "STATUS_TOO_MANY_GUIDS_REQUESTED" },
{ 0xC0000083, "STATUS_GUIDS_EXHAUSTED" },
{ 0xC0000084, "STATUS_INVALID_ID_AUTHORITY" },
{ 0xC0000085, "STATUS_AGENTS_EXHAUSTED" },
{ 0xC0000086, "STATUS_INVALID_VOLUME_LABEL" },
{ 0xC0000087, "STATUS_SECTION_NOT_EXTENDED" },
{ 0xC0000088, "STATUS_NOT_MAPPED_DATA" },
{ 0xC0000089, "STATUS_RESOURCE_DATA_NOT_FOUND" },
{ 0xC000008A, "STATUS_RESOURCE_TYPE_NOT_FOUND" },
{ 0xC000008B, "STATUS_RESOURCE_NAME_NOT_FOUND" },
{ 0xC000008C, "STATUS_ARRAY_BOUNDS_EXCEEDED" },
{ 0xC000008D, "STATUS_FLOAT_DENORMAL_OPERAND" },
{ 0xC000008E, "STATUS_FLOAT_DIVIDE_BY_ZERO" },
{ 0xC000008F, "STATUS_FLOAT_INEXACT_RESULT" },
{ 0xC0000090, "STATUS_FLOAT_INVALID_OPERATION" },
{ 0xC0000091, "STATUS_FLOAT_OVERFLOW" },
{ 0xC0000092, "STATUS_FLOAT_STACK_CHECK" },
{ 0xC0000093, "STATUS_FLOAT_UNDERFLOW" },
{ 0xC0000094, "STATUS_INTEGER_DIVIDE_BY_ZERO" },
{ 0xC0000095, "STATUS_INTEGER_OVERFLOW" },
{ 0xC0000096, "STATUS_PRIVILEGED_INSTRUCTION" },
{ 0xC0000097, "STATUS_TOO_MANY_PAGING_FILES" },
{ 0xC0000098, "STATUS_FILE_INVALID" },
{ 0xC0000099, "STATUS_ALLOTTED_SPACE_EXCEEDED" },
{ 0xC000009A, "STATUS_INSUFFICIENT_RESOURCES" },
{ 0xC000009B, "STATUS_DFS_EXIT_PATH_FOUND" },
{ 0xC000009C, "STATUS_DEVICE_DATA_ERROR" },
{ 0xC000009D, "STATUS_DEVICE_NOT_CONNECTED" },
{ 0xC000009E, "STATUS_DEVICE_POWER_FAILURE" },
{ 0xC000009F, "STATUS_FREE_VM_NOT_AT_BASE" },
{ 0xC00000A0, "STATUS_MEMORY_NOT_ALLOCATED" },
{ 0xC00000A1, "STATUS_WORKING_SET_QUOTA" },
{ 0xC00000A2, "STATUS_MEDIA_WRITE_PROTECTED" },
{ 0xC00000A3, "STATUS_DEVICE_NOT_READY" },
{ 0xC00000A4, "STATUS_INVALID_GROUP_ATTRIBUTES" },
{ 0xC00000A5, "STATUS_BAD_IMPERSONATION_LEVEL" },
{ 0xC00000A6, "STATUS_CANT_OPEN_ANONYMOUS" },
{ 0xC00000A7, "STATUS_BAD_VALIDATION_CLASS" },
{ 0xC00000A8, "STATUS_BAD_TOKEN_TYPE" },
{ 0xC00000A9, "STATUS_BAD_MASTER_BOOT_RECORD" },
{ 0xC00000AA, "STATUS_INSTRUCTION_MISALIGNMENT" },
{ 0xC00000AB, "STATUS_INSTANCE_NOT_AVAILABLE" },
{ 0xC00000AC, "STATUS_PIPE_NOT_AVAILABLE" },
{ 0xC00000AD, "STATUS_INVALID_PIPE_STATE" },
{ 0xC00000AE, "STATUS_PIPE_BUSY" },
{ 0xC00000AF, "STATUS_ILLEGAL_FUNCTION" },
{ 0xC00000B0, "STATUS_PIPE_DISCONNECTED" },
{ 0xC00000B1, "STATUS_PIPE_CLOSING" },
{ 0xC00000B2, "STATUS_PIPE_CONNECTED" },
{ 0xC00000B3, "STATUS_PIPE_LISTENING" },
{ 0xC00000B4, "STATUS_INVALID_READ_MODE" },
{ 0xC00000B5, "STATUS_IO_TIMEOUT" },
{ 0xC00000B6, "STATUS_FILE_FORCED_CLOSED" },
{ 0xC00000B7, "STATUS_PROFILING_NOT_STARTED" },
{ 0xC00000B8, "STATUS_PROFILING_NOT_STOPPED" },
{ 0xC00000B9, "STATUS_COULD_NOT_INTERPRET" },
{ 0xC00000BA, "STATUS_FILE_IS_A_DIRECTORY" },
{ 0xC00000BB, "STATUS_NOT_SUPPORTED" },
{ 0xC00000BC, "STATUS_REMOTE_NOT_LISTENING" },
{ 0xC00000BD, "STATUS_DUPLICATE_NAME" },
{ 0xC00000BE, "STATUS_BAD_NETWORK_PATH" },
{ 0xC00000BF, "STATUS_NETWORK_BUSY" },
{ 0xC00000C0, "STATUS_DEVICE_DOES_NOT_EXIST" },
{ 0xC00000C1, "STATUS_TOO_MANY_COMMANDS" },
{ 0xC00000C2, "STATUS_ADAPTER_HARDWARE_ERROR" },
{ 0xC00000C3, "STATUS_INVALID_NETWORK_RESPONSE" },
{ 0xC00000C4, "STATUS_UNEXPECTED_NETWORK_ERROR" },
{ 0xC00000C5, "STATUS_BAD_REMOTE_ADAPTER" },
{ 0xC00000C6, "STATUS_PRINT_QUEUE_FULL" },
{ 0xC00000C7, "STATUS_NO_SPOOL_SPACE" },
{ 0xC00000C8, "STATUS_PRINT_CANCELLED" },
{ 0xC00000C9, "STATUS_NETWORK_NAME_DELETED" },
{ 0xC00000CA, "STATUS_NETWORK_ACCESS_DENIED" },
{ 0xC00000CB, "STATUS_BAD_DEVICE_TYPE" },
{ 0xC00000CC, "STATUS_BAD_NETWORK_NAME" },
{ 0xC00000CD, "STATUS_TOO_MANY_NAMES" },
{ 0xC00000CE, "STATUS_TOO_MANY_SESSIONS" },
{ 0xC00000CF, "STATUS_SHARING_PAUSED" },
{ 0xC00000D0, "STATUS_REQUEST_NOT_ACCEPTED" },
{ 0xC00000D1, "STATUS_REDIRECTOR_PAUSED" },
{ 0xC00000D2, "STATUS_NET_WRITE_FAULT" },
{ 0xC00000D3, "STATUS_PROFILING_AT_LIMIT" },
{ 0xC00000D4, "STATUS_NOT_SAME_DEVICE" },
{ 0xC00000D5, "STATUS_FILE_RENAMED" },
{ 0xC00000D6, "STATUS_VIRTUAL_CIRCUIT_CLOSED" },
{ 0xC00000D7, "STATUS_NO_SECURITY_ON_OBJECT" },
{ 0xC00000D8, "STATUS_CANT_WAIT" },
{ 0xC00000D9, "STATUS_PIPE_EMPTY" },
{ 0xC00000DA, "STATUS_CANT_ACCESS_DOMAIN_INFO" },
{ 0xC00000DB, "STATUS_CANT_TERMINATE_SELF" },
{ 0xC00000DC, "STATUS_INVALID_SERVER_STATE" },
{ 0xC00000DD, "STATUS_INVALID_DOMAIN_STATE" },
{ 0xC00000DE, "STATUS_INVALID_DOMAIN_ROLE" },
{ 0xC00000DF, "STATUS_NO_SUCH_DOMAIN" },
{ 0xC00000E0, "STATUS_DOMAIN_EXISTS" },
{ 0xC00000E1, "STATUS_DOMAIN_LIMIT_EXCEEDED" },
{ 0xC00000E2, "STATUS_OPLOCK_NOT_GRANTED" },
{ 0xC00000E3, "STATUS_INVALID_OPLOCK_PROTOCOL" },
{ 0xC00000E4, "STATUS_INTERNAL_DB_CORRUPTION" },
{ 0xC00000E5, "STATUS_INTERNAL_ERROR" },
{ 0xC00000E6, "STATUS_GENERIC_NOT_MAPPED" },
{ 0xC00000E7, "STATUS_BAD_DESCRIPTOR_FORMAT" },
{ 0xC00000E8, "STATUS_INVALID_USER_BUFFER" },
{ 0xC00000E9, "STATUS_UNEXPECTED_IO_ERROR" },
{ 0xC00000EA, "STATUS_UNEXPECTED_MM_CREATE_ERR" },
{ 0xC00000EB, "STATUS_UNEXPECTED_MM_MAP_ERROR" },
{ 0xC00000EC, "STATUS_UNEXPECTED_MM_EXTEND_ERR" },
{ 0xC00000ED, "STATUS_NOT_LOGON_PROCESS" },
{ 0xC00000EE, "STATUS_LOGON_SESSION_EXISTS" },
{ 0xC00000EF, "STATUS_INVALID_PARAMETER_1" },
{ 0xC00000F0, "STATUS_INVALID_PARAMETER_2" },
{ 0xC00000F1, "STATUS_INVALID_PARAMETER_3" },
{ 0xC00000F2, "STATUS_INVALID_PARAMETER_4" },
{ 0xC00000F3, "STATUS_INVALID_PARAMETER_5" },
{ 0xC00000F4, "STATUS_INVALID_PARAMETER_6" },
{ 0xC00000F5, "STATUS_INVALID_PARAMETER_7" },
{ 0xC00000F6, "STATUS_INVALID_PARAMETER_8" },
{ 0xC00000F7, "STATUS_INVALID_PARAMETER_9" },
{ 0xC00000F8, "STATUS_INVALID_PARAMETER_10" },
{ 0xC00000F9, "STATUS_INVALID_PARAMETER_11" },
{ 0xC00000FA, "STATUS_INVALID_PARAMETER_12" },
{ 0xC00000FB, "STATUS_REDIRECTOR_NOT_STARTED" },
{ 0xC00000FC, "STATUS_REDIRECTOR_STARTED" },
{ 0xC00000FD, "STATUS_STACK_OVERFLOW" },
{ 0xC00000FE, "STATUS_NO_SUCH_PACKAGE" },
{ 0xC00000FF, "STATUS_BAD_FUNCTION_TABLE" },
{ 0xC0000100, "STATUS_VARIABLE_NOT_FOUND" },
{ 0xC0000101, "STATUS_DIRECTORY_NOT_EMPTY" },
{ 0xC0000102, "STATUS_FILE_CORRUPT_ERROR" },
{ 0xC0000103, "STATUS_NOT_A_DIRECTORY" },
{ 0xC0000104, "STATUS_BAD_LOGON_SESSION_STATE" },
{ 0xC0000105, "STATUS_LOGON_SESSION_COLLISION" },
{ 0xC0000106, "STATUS_NAME_TOO_LONG" },
{ 0xC0000107, "STATUS_FILES_OPEN" },
{ 0xC0000108, "STATUS_CONNECTION_IN_USE" },
{ 0xC0000109, "STATUS_MESSAGE_NOT_FOUND" },
{ 0xC000010A, "STATUS_PROCESS_IS_TERMINATING" },
{ 0xC000010B, "STATUS_INVALID_LOGON_TYPE" },
{ 0xC000010C, "STATUS_NO_GUID_TRANSLATION" },
{ 0xC000010D, "STATUS_CANNOT_IMPERSONATE" },
{ 0xC000010E, "STATUS_IMAGE_ALREADY_LOADED" },
{ 0xC000010F, "STATUS_ABIOS_NOT_PRESENT" },
{ 0xC0000110, "STATUS_ABIOS_LID_NOT_EXIST" },
{ 0xC0000111, "STATUS_ABIOS_LID_ALREADY_OWNED" },
{ 0xC0000112, "STATUS_ABIOS_NOT_LID_OWNER" },
{ 0xC0000113, "STATUS_ABIOS_INVALID_COMMAND" },
{ 0xC0000114, "STATUS_ABIOS_INVALID_LID" },
{ 0xC0000115, "STATUS_ABIOS_SELECTOR_NOT_AVAILABLE" },
{ 0xC0000116, "STATUS_ABIOS_INVALID_SELECTOR" },
{ 0xC0000117, "STATUS_NO_LDT" },
{ 0xC0000118, "STATUS_INVALID_LDT_SIZE" },
{ 0xC0000119, "STATUS_INVALID_LDT_OFFSET" },
{ 0xC000011A, "STATUS_INVALID_LDT_DESCRIPTOR" },
{ 0xC000011B, "STATUS_INVALID_IMAGE_NE_FORMAT" },
{ 0xC000011C, "STATUS_RXACT_INVALID_STATE" },
{ 0xC000011D, "STATUS_RXACT_COMMIT_FAILURE" },
{ 0xC000011E, "STATUS_MAPPED_FILE_SIZE_ZERO" },
{ 0xC000011F, "STATUS_TOO_MANY_OPENED_FILES" },
{ 0xC0000120, "STATUS_CANCELLED" },
{ 0xC0000121, "STATUS_CANNOT_DELETE" },
{ 0xC0000122, "STATUS_INVALID_COMPUTER_NAME" },
{ 0xC0000123, "STATUS_FILE_DELETED" },
{ 0xC0000124, "STATUS_SPECIAL_ACCOUNT" },
{ 0xC0000125, "STATUS_SPECIAL_GROUP" },
{ 0xC0000126, "STATUS_SPECIAL_USER" },
{ 0xC0000127, "STATUS_MEMBERS_PRIMARY_GROUP" },
{ 0xC0000128, "STATUS_FILE_CLOSED" },
{ 0xC0000129, "STATUS_TOO_MANY_THREADS" },
{ 0xC000012A, "STATUS_THREAD_NOT_IN_PROCESS" },
{ 0xC000012B, "STATUS_TOKEN_ALREADY_IN_USE" },
{ 0xC000012C, "STATUS_PAGEFILE_QUOTA_EXCEEDED" },
{ 0xC000012D, "STATUS_COMMITMENT_LIMIT" },
{ 0xC000012E, "STATUS_INVALID_IMAGE_LE_FORMAT" },
{ 0xC000012F, "STATUS_INVALID_IMAGE_NOT_MZ" },
{ 0xC0000130, "STATUS_INVALID_IMAGE_PROTECT" },
{ 0xC0000131, "STATUS_INVALID_IMAGE_WIN_16" },
{ 0xC0000132, "STATUS_LOGON_SERVER_CONFLICT" },
{ 0xC0000133, "STATUS_TIME_DIFFERENCE_AT_DC" },
{ 0xC0000134, "STATUS_SYNCHRONIZATION_REQUIRED" },
{ 0xC0000135, "STATUS_DLL_NOT_FOUND" },
{ 0xC0000136, "STATUS_OPEN_FAILED" },
{ 0xC0000137, "STATUS_IO_PRIVILEGE_FAILED" },
{ 0xC0000138, "STATUS_ORDINAL_NOT_FOUND" },
{ 0xC0000139, "STATUS_ENTRYPOINT_NOT_FOUND" },
{ 0xC000013A, "STATUS_CONTROL_C_EXIT" },
{ 0xC000013B, "STATUS_LOCAL_DISCONNECT" },
{ 0xC000013C, "STATUS_REMOTE_DISCONNECT" },
{ 0xC000013D, "STATUS_REMOTE_RESOURCES" },
{ 0xC000013E, "STATUS_LINK_FAILED" },
{ 0xC000013F, "STATUS_LINK_TIMEOUT" },
{ 0xC0000140, "STATUS_INVALID_CONNECTION" },
{ 0xC0000141, "STATUS_INVALID_ADDRESS" },
{ 0xC0000142, "STATUS_DLL_INIT_FAILED" },
{ 0xC0000143, "STATUS_MISSING_SYSTEMFILE" },
{ 0xC0000144, "STATUS_UNHANDLED_EXCEPTION" },
{ 0xC0000145, "STATUS_APP_INIT_FAILURE" },
{ 0xC0000146, "STATUS_PAGEFILE_CREATE_FAILED" },
{ 0xC0000147, "STATUS_NO_PAGEFILE" },
{ 0xC0000148, "STATUS_INVALID_LEVEL" },
{ 0xC0000149, "STATUS_WRONG_PASSWORD_CORE" },
{ 0xC000014A, "STATUS_ILLEGAL_FLOAT_CONTEXT" },
{ 0xC000014B, "STATUS_PIPE_BROKEN" },
{ 0xC000014C, "STATUS_REGISTRY_CORRUPT" },
{ 0xC000014D, "STATUS_REGISTRY_IO_FAILED" },
{ 0xC000014E, "STATUS_NO_EVENT_PAIR" },
{ 0xC000014F, "STATUS_UNRECOGNIZED_VOLUME" },
{ 0xC0000150, "STATUS_SERIAL_NO_DEVICE_INITED" },
{ 0xC0000151, "STATUS_NO_SUCH_ALIAS" },
{ 0xC0000152, "STATUS_MEMBER_NOT_IN_ALIAS" },
{ 0xC0000153, "STATUS_MEMBER_IN_ALIAS" },
{ 0xC0000154, "STATUS_ALIAS_EXISTS" },
{ 0xC0000155, "STATUS_LOGON_NOT_GRANTED" },
{ 0xC0000156, "STATUS_TOO_MANY_SECRETS" },
{ 0xC0000157, "STATUS_SECRET_TOO_LONG" },
{ 0xC0000158, "STATUS_INTERNAL_DB_ERROR" },
{ 0xC0000159, "STATUS_FULLSCREEN_MODE" },
{ 0xC000015A, "STATUS_TOO_MANY_CONTEXT_IDS" },
{ 0xC000015B, "STATUS_LOGON_TYPE_NOT_GRANTED" },
{ 0xC000015C, "STATUS_NOT_REGISTRY_FILE" },
{ 0xC000015D, "STATUS_NT_CROSS_ENCRYPTION_REQUIRED" },
{ 0xC000015E, "STATUS_DOMAIN_CTRLR_CONFIG_ERROR" },
{ 0xC000015F, "STATUS_FT_MISSING_MEMBER" },
{ 0xC0000160, "STATUS_ILL_FORMED_SERVICE_ENTRY" },
{ 0xC0000161, "STATUS_ILLEGAL_CHARACTER" },
{ 0xC0000162, "STATUS_UNMAPPABLE_CHARACTER" },
{ 0xC0000163, "STATUS_UNDEFINED_CHARACTER" },
{ 0xC0000164, "STATUS_FLOPPY_VOLUME" },
{ 0xC0000165, "STATUS_FLOPPY_ID_MARK_NOT_FOUND" },
{ 0xC0000166, "STATUS_FLOPPY_WRONG_CYLINDER" },
{ 0xC0000167, "STATUS_FLOPPY_UNKNOWN_ERROR" },
{ 0xC0000168, "STATUS_FLOPPY_BAD_REGISTERS" },
{ 0xC0000169, "STATUS_DISK_RECALIBRATE_FAILED" },
{ 0xC000016A, "STATUS_DISK_OPERATION_FAILED" },
{ 0xC000016B, "STATUS_DISK_RESET_FAILED" },
{ 0xC000016C, "STATUS_SHARED_IRQ_BUSY" },
{ 0xC000016D, "STATUS_FT_ORPHANING" },
{ 0xC000016E, "STATUS_BIOS_FAILED_TO_CONNECT_INTERRUPT" },
{ 0xC0000172, "STATUS_PARTITION_FAILURE" },
{ 0xC0000173, "STATUS_INVALID_BLOCK_LENGTH" },
{ 0xC0000174, "STATUS_DEVICE_NOT_PARTITIONED" },
{ 0xC0000175, "STATUS_UNABLE_TO_LOCK_MEDIA" },
{ 0xC0000176, "STATUS_UNABLE_TO_UNLOAD_MEDIA" },
{ 0xC0000177, "STATUS_EOM_OVERFLOW" },
{ 0xC0000178, "STATUS_NO_MEDIA" },
{ 0xC000017A, "STATUS_NO_SUCH_MEMBER" },
{ 0xC000017B, "STATUS_INVALID_MEMBER" },
{ 0xC000017C, "STATUS_KEY_DELETED" },
{ 0xC000017D, "STATUS_NO_LOG_SPACE" },
{ 0xC000017E, "STATUS_TOO_MANY_SIDS" },
{ 0xC000017F, "STATUS_LM_CROSS_ENCRYPTION_REQUIRED" },
{ 0xC0000180, "STATUS_KEY_HAS_CHILDREN" },
{ 0xC0000181, "STATUS_CHILD_MUST_BE_VOLATILE" },
{ 0xC0000182, "STATUS_DEVICE_CONFIGURATION_ERROR" },
{ 0xC0000183, "STATUS_DRIVER_INTERNAL_ERROR" },
{ 0xC0000184, "STATUS_INVALID_DEVICE_STATE" },
{ 0xC0000185, "STATUS_IO_DEVICE_ERROR" },
{ 0xC0000186, "STATUS_DEVICE_PROTOCOL_ERROR" },
{ 0xC0000187, "STATUS_BACKUP_CONTROLLER" },
{ 0xC0000188, "STATUS_LOG_FILE_FULL" },
{ 0xC0000189, "STATUS_TOO_LATE" },
{ 0xC000018A, "STATUS_NO_TRUST_LSA_SECRET" },
{ 0xC000018B, "STATUS_NO_TRUST_SAM_ACCOUNT" },
{ 0xC000018C, "STATUS_TRUSTED_DOMAIN_FAILURE" },
{ 0xC000018D, "STATUS_TRUSTED_RELATIONSHIP_FAILURE" },
{ 0xC000018E, "STATUS_EVENTLOG_FILE_CORRUPT" },
{ 0xC000018F, "STATUS_EVENTLOG_CANT_START" },
{ 0xC0000190, "STATUS_TRUST_FAILURE" },
{ 0xC0000191, "STATUS_MUTANT_LIMIT_EXCEEDED" },
{ 0xC0000192, "STATUS_NETLOGON_NOT_STARTED" },
{ 0xC0000193, "STATUS_ACCOUNT_EXPIRED" },
{ 0xC0000194, "STATUS_POSSIBLE_DEADLOCK" },
{ 0xC0000195, "STATUS_NETWORK_CREDENTIAL_CONFLICT" },
{ 0xC0000196, "STATUS_REMOTE_SESSION_LIMIT" },
{ 0xC0000197, "STATUS_EVENTLOG_FILE_CHANGED" },
{ 0xC0000198, "STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT" },
{ 0xC0000199, "STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT" },
{ 0xC000019A, "STATUS_NOLOGON_SERVER_TRUST_ACCOUNT" },
{ 0xC000019B, "STATUS_DOMAIN_TRUST_INCONSISTENT" },
{ 0xC000019C, "STATUS_FS_DRIVER_REQUIRED" },
{ 0xC0000202, "STATUS_NO_USER_SESSION_KEY" },
{ 0xC0000203, "STATUS_USER_SESSION_DELETED" },
{ 0xC0000204, "STATUS_RESOURCE_LANG_NOT_FOUND" },
{ 0xC0000205, "STATUS_INSUFF_SERVER_RESOURCES" },
{ 0xC0000206, "STATUS_INVALID_BUFFER_SIZE" },
{ 0xC0000207, "STATUS_INVALID_ADDRESS_COMPONENT" },
{ 0xC0000208, "STATUS_INVALID_ADDRESS_WILDCARD" },
{ 0xC0000209, "STATUS_TOO_MANY_ADDRESSES" },
{ 0xC000020A, "STATUS_ADDRESS_ALREADY_EXISTS" },
{ 0xC000020B, "STATUS_ADDRESS_CLOSED" },
{ 0xC000020C, "STATUS_CONNECTION_DISCONNECTED" },
{ 0xC000020D, "STATUS_CONNECTION_RESET" },
{ 0xC000020E, "STATUS_TOO_MANY_NODES" },
{ 0xC000020F, "STATUS_TRANSACTION_ABORTED" },
{ 0xC0000210, "STATUS_TRANSACTION_TIMED_OUT" },
{ 0xC0000211, "STATUS_TRANSACTION_NO_RELEASE" },
{ 0xC0000212, "STATUS_TRANSACTION_NO_MATCH" },
{ 0xC0000213, "STATUS_TRANSACTION_RESPONDED" },
{ 0xC0000214, "STATUS_TRANSACTION_INVALID_ID" },
{ 0xC0000215, "STATUS_TRANSACTION_INVALID_TYPE" },
{ 0xC0000216, "STATUS_NOT_SERVER_SESSION" },
{ 0xC0000217, "STATUS_NOT_CLIENT_SESSION" },
{ 0xC0000218, "STATUS_CANNOT_LOAD_REGISTRY_FILE" },
{ 0xC0000219, "STATUS_DEBUG_ATTACH_FAILED" },
{ 0xC000021A, "STATUS_SYSTEM_PROCESS_TERMINATED" },
{ 0xC000021B, "STATUS_DATA_NOT_ACCEPTED" },
{ 0xC000021C, "STATUS_NO_BROWSER_SERVERS_FOUND" },
{ 0xC000021D, "STATUS_VDM_HARD_ERROR" },
{ 0xC000021E, "STATUS_DRIVER_CANCEL_TIMEOUT" },
{ 0xC000021F, "STATUS_REPLY_MESSAGE_MISMATCH" },
{ 0xC0000220, "STATUS_MAPPED_ALIGNMENT" },
{ 0xC0000221, "STATUS_IMAGE_CHECKSUM_MISMATCH" },
{ 0xC0000222, "STATUS_LOST_WRITEBEHIND_DATA" },
{ 0xC0000223, "STATUS_CLIENT_SERVER_PARAMETERS_INVALID" },
{ 0xC0000224, "STATUS_PASSWORD_MUST_CHANGE" },
{ 0xC0000225, "STATUS_NOT_FOUND" },
{ 0xC0000226, "STATUS_NOT_TINY_STREAM" },
{ 0xC0000227, "STATUS_RECOVERY_FAILURE" },
{ 0xC0000228, "STATUS_STACK_OVERFLOW_READ" },
{ 0xC0000229, "STATUS_FAIL_CHECK" },
{ 0xC000022A, "STATUS_DUPLICATE_OBJECTID" },
{ 0xC000022B, "STATUS_OBJECTID_EXISTS" },
{ 0xC000022C, "STATUS_CONVERT_TO_LARGE" },
{ 0xC000022D, "STATUS_RETRY" },
{ 0xC000022E, "STATUS_FOUND_OUT_OF_SCOPE" },
{ 0xC000022F, "STATUS_ALLOCATE_BUCKET" },
{ 0xC0000230, "STATUS_PROPSET_NOT_FOUND" },
{ 0xC0000231, "STATUS_MARSHALL_OVERFLOW" },
{ 0xC0000232, "STATUS_INVALID_VARIANT" },
{ 0xC0000233, "STATUS_DOMAIN_CONTROLLER_NOT_FOUND" },
{ 0xC0000234, "STATUS_ACCOUNT_LOCKED_OUT" },
{ 0xC0000235, "STATUS_HANDLE_NOT_CLOSABLE" },
{ 0xC0000236, "STATUS_CONNECTION_REFUSED" },
{ 0xC0000237, "STATUS_GRACEFUL_DISCONNECT" },
{ 0xC0000238, "STATUS_ADDRESS_ALREADY_ASSOCIATED" },
{ 0xC0000239, "STATUS_ADDRESS_NOT_ASSOCIATED" },
{ 0xC000023A, "STATUS_CONNECTION_INVALID" },
{ 0xC000023B, "STATUS_CONNECTION_ACTIVE" },
{ 0xC000023C, "STATUS_NETWORK_UNREACHABLE" },
{ 0xC000023D, "STATUS_HOST_UNREACHABLE" },
{ 0xC000023E, "STATUS_PROTOCOL_UNREACHABLE" },
{ 0xC000023F, "STATUS_PORT_UNREACHABLE" },
{ 0xC0000240, "STATUS_REQUEST_ABORTED" },
{ 0xC0000241, "STATUS_CONNECTION_ABORTED" },
{ 0xC0000242, "STATUS_BAD_COMPRESSION_BUFFER" },
{ 0xC0000243, "STATUS_USER_MAPPED_FILE" },
{ 0xC0000244, "STATUS_AUDIT_FAILED" },
{ 0xC0000245, "STATUS_TIMER_RESOLUTION_NOT_SET" },
{ 0xC0000246, "STATUS_CONNECTION_COUNT_LIMIT" },
{ 0xC0000247, "STATUS_LOGIN_TIME_RESTRICTION" },
{ 0xC0000248, "STATUS_LOGIN_WKSTA_RESTRICTION" },
{ 0xC0000249, "STATUS_IMAGE_MP_UP_MISMATCH" },
{ 0xC0000250, "STATUS_INSUFFICIENT_LOGON_INFO" },
{ 0xC0000251, "STATUS_BAD_DLL_ENTRYPOINT" },
{ 0xC0000252, "STATUS_BAD_SERVICE_ENTRYPOINT" },
{ 0xC0000253, "STATUS_LPC_REPLY_LOST" },
{ 0xC0000254, "STATUS_IP_ADDRESS_CONFLICT1" },
{ 0xC0000255, "STATUS_IP_ADDRESS_CONFLICT2" },
{ 0xC0000256, "STATUS_REGISTRY_QUOTA_LIMIT" },
{ 0xC0000257, "STATUS_PATH_NOT_COVERED" },
{ 0xC0000258, "STATUS_NO_CALLBACK_ACTIVE" },
{ 0xC0000259, "STATUS_LICENSE_QUOTA_EXCEEDED" },
{ 0xC000025A, "STATUS_PWD_TOO_SHORT" },
{ 0xC000025B, "STATUS_PWD_TOO_RECENT" },
{ 0xC000025C, "STATUS_PWD_HISTORY_CONFLICT" },
{ 0xC000025E, "STATUS_PLUGPLAY_NO_DEVICE" },
{ 0xC000025F, "STATUS_UNSUPPORTED_COMPRESSION" },
{ 0xC0000260, "STATUS_INVALID_HW_PROFILE" },
{ 0xC0000261, "STATUS_INVALID_PLUGPLAY_DEVICE_PATH" },
{ 0xC0000262, "STATUS_DRIVER_ORDINAL_NOT_FOUND" },
{ 0xC0000263, "STATUS_DRIVER_ENTRYPOINT_NOT_FOUND" },
{ 0xC0000264, "STATUS_RESOURCE_NOT_OWNED" },
{ 0xC0000265, "STATUS_TOO_MANY_LINKS" },
{ 0xC0000266, "STATUS_QUOTA_LIST_INCONSISTENT" },
{ 0xC0000267, "STATUS_FILE_IS_OFFLINE" },
{ 0xC0000268, "STATUS_EVALUATION_EXPIRATION" },
{ 0xC0000269, "STATUS_ILLEGAL_DLL_RELOCATION" },
{ 0xC000026A, "STATUS_LICENSE_VIOLATION" },
{ 0xC000026B, "STATUS_DLL_INIT_FAILED_LOGOFF" },
{ 0xC000026C, "STATUS_DRIVER_UNABLE_TO_LOAD" },
{ 0xC000026D, "STATUS_DFS_UNAVAILABLE" },
{ 0xC000026E, "STATUS_VOLUME_DISMOUNTED" },
{ 0xC000026F, "STATUS_WX86_INTERNAL_ERROR" },
{ 0xC0000270, "STATUS_WX86_FLOAT_STACK_CHECK" },
{ 0xC0000271, "STATUS_VALIDATE_CONTINUE" },
{ 0xC0000272, "STATUS_NO_MATCH" },
{ 0xC0000273, "STATUS_NO_MORE_MATCHES" },
{ 0xC0000275, "STATUS_NOT_A_REPARSE_POINT" },
{ 0xC0000276, "STATUS_IO_REPARSE_TAG_INVALID" },
{ 0xC0000277, "STATUS_IO_REPARSE_TAG_MISMATCH" },
{ 0xC0000278, "STATUS_IO_REPARSE_DATA_INVALID" },
{ 0xC0000279, "STATUS_IO_REPARSE_TAG_NOT_HANDLED" },
{ 0xC0000280, "STATUS_REPARSE_POINT_NOT_RESOLVED" },
{ 0xC0000281, "STATUS_DIRECTORY_IS_A_REPARSE_POINT" },
{ 0xC0000282, "STATUS_RANGE_LIST_CONFLICT" },
{ 0xC0000283, "STATUS_SOURCE_ELEMENT_EMPTY" },
{ 0xC0000284, "STATUS_DESTINATION_ELEMENT_FULL" },
{ 0xC0000285, "STATUS_ILLEGAL_ELEMENT_ADDRESS" },
{ 0xC0000286, "STATUS_MAGAZINE_NOT_PRESENT" },
{ 0xC0000287, "STATUS_REINITIALIZATION_NEEDED" },
{ 0x80000288, "STATUS_DEVICE_REQUIRES_CLEANING" },
{ 0x80000289, "STATUS_DEVICE_DOOR_OPEN" },
{ 0xC000028A, "STATUS_ENCRYPTION_FAILED" },
{ 0xC000028B, "STATUS_DECRYPTION_FAILED" },
{ 0xC000028C, "STATUS_RANGE_NOT_FOUND" },
{ 0xC000028D, "STATUS_NO_RECOVERY_POLICY" },
{ 0xC000028E, "STATUS_NO_EFS" },
{ 0xC000028F, "STATUS_WRONG_EFS" },
{ 0xC0000290, "STATUS_NO_USER_KEYS" },
{ 0xC0000291, "STATUS_FILE_NOT_ENCRYPTED" },
{ 0xC0000292, "STATUS_NOT_EXPORT_FORMAT" },
{ 0xC0000293, "STATUS_FILE_ENCRYPTED" },
{ 0x40000294, "STATUS_WAKE_SYSTEM" },
{ 0xC0000295, "STATUS_WMI_GUID_NOT_FOUND" },
{ 0xC0000296, "STATUS_WMI_INSTANCE_NOT_FOUND" },
{ 0xC0000297, "STATUS_WMI_ITEMID_NOT_FOUND" },
{ 0xC0000298, "STATUS_WMI_TRY_AGAIN" },
{ 0xC0000299, "STATUS_SHARED_POLICY" },
{ 0xC000029A, "STATUS_POLICY_OBJECT_NOT_FOUND" },
{ 0xC000029B, "STATUS_POLICY_ONLY_IN_DS" },
{ 0xC000029C, "STATUS_VOLUME_NOT_UPGRADED" },
{ 0xC000029D, "STATUS_REMOTE_STORAGE_NOT_ACTIVE" },
{ 0xC000029E, "STATUS_REMOTE_STORAGE_MEDIA_ERROR" },
{ 0xC000029F, "STATUS_NO_TRACKING_SERVICE" },
{ 0xC00002A0, "STATUS_SERVER_SID_MISMATCH" },
{ 0xC00002A1, "STATUS_DS_NO_ATTRIBUTE_OR_VALUE" },
{ 0xC00002A2, "STATUS_DS_INVALID_ATTRIBUTE_SYNTAX" },
{ 0xC00002A3, "STATUS_DS_ATTRIBUTE_TYPE_UNDEFINED" },
{ 0xC00002A4, "STATUS_DS_ATTRIBUTE_OR_VALUE_EXISTS" },
{ 0xC00002A5, "STATUS_DS_BUSY" },
{ 0xC00002A6, "STATUS_DS_UNAVAILABLE" },
{ 0xC00002A7, "STATUS_DS_NO_RIDS_ALLOCATED" },
{ 0xC00002A8, "STATUS_DS_NO_MORE_RIDS" },
{ 0xC00002A9, "STATUS_DS_INCORRECT_ROLE_OWNER" },
{ 0xC00002AA, "STATUS_DS_RIDMGR_INIT_ERROR" },
{ 0xC00002AB, "STATUS_DS_OBJ_CLASS_VIOLATION" },
{ 0xC00002AC, "STATUS_DS_CANT_ON_NON_LEAF" },
{ 0xC00002AD, "STATUS_DS_CANT_ON_RDN" },
{ 0xC00002AE, "STATUS_DS_CANT_MOD_OBJ_CLASS" },
{ 0xC00002AF, "STATUS_DS_CROSS_DOM_MOVE_FAILED" },
{ 0xC00002B0, "STATUS_DS_GC_NOT_AVAILABLE" },
{ 0xC00002B1, "STATUS_DIRECTORY_SERVICE_REQUIRED" },
{ 0xC00002B2, "STATUS_REPARSE_ATTRIBUTE_CONFLICT" },
{ 0xC00002B3, "STATUS_CANT_ENABLE_DENY_ONLY" },
{ 0xC00002B4, "STATUS_FLOAT_MULTIPLE_FAULTS" },
{ 0xC00002B5, "STATUS_FLOAT_MULTIPLE_TRAPS" },
{ 0xC00002B6, "STATUS_DEVICE_REMOVED" },
{ 0xC00002B7, "STATUS_JOURNAL_DELETE_IN_PROGRESS" },
{ 0xC00002B8, "STATUS_JOURNAL_NOT_ACTIVE" },
{ 0xC00002B9, "STATUS_NOINTERFACE" },
{ 0xC00002C1, "STATUS_DS_ADMIN_LIMIT_EXCEEDED" },
{ 0xC00002C2, "STATUS_DRIVER_FAILED_SLEEP" },
{ 0xC00002C3, "STATUS_MUTUAL_AUTHENTICATION_FAILED" },
{ 0xC00002C4, "STATUS_CORRUPT_SYSTEM_FILE" },
{ 0xC00002C5, "STATUS_DATATYPE_MISALIGNMENT_ERROR" },
{ 0xC00002C6, "STATUS_WMI_READ_ONLY" },
{ 0xC00002C7, "STATUS_WMI_SET_FAILURE" },
{ 0xC00002C8, "STATUS_COMMITMENT_MINIMUM" },
{ 0xC00002C9, "STATUS_REG_NAT_CONSUMPTION" },
{ 0xC00002CA, "STATUS_TRANSPORT_FULL" },
{ 0xC00002CB, "STATUS_DS_SAM_INIT_FAILURE" },
{ 0xC00002CC, "STATUS_ONLY_IF_CONNECTED" },
{ 0xC00002CD, "STATUS_DS_SENSITIVE_GROUP_VIOLATION" },
{ 0xC00002CE, "STATUS_PNP_RESTART_ENUMERATION" },
{ 0xC00002CF, "STATUS_JOURNAL_ENTRY_DELETED" },
{ 0xC00002D0, "STATUS_DS_CANT_MOD_PRIMARYGROUPID" },
{ 0xC00002D1, "STATUS_SYSTEM_IMAGE_BAD_SIGNATURE" },
{ 0xC00002D2, "STATUS_PNP_REBOOT_REQUIRED" },
{ 0xC00002D3, "STATUS_POWER_STATE_INVALID" },
{ 0xC00002D4, "STATUS_DS_INVALID_GROUP_TYPE" },
{ 0xC00002D5, "STATUS_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN" },
{ 0xC00002D6, "STATUS_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN" },
{ 0xC00002D7, "STATUS_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER" },
{ 0xC00002D8, "STATUS_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER" },
{ 0xC00002D9, "STATUS_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER" },
{ 0xC00002DA, "STATUS_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER" },
{ 0xC00002DB, "STATUS_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER" },
{ 0xC00002DC, "STATUS_DS_HAVE_PRIMARY_MEMBERS" },
{ 0xC00002DD, "STATUS_WMI_NOT_SUPPORTED" },
{ 0xC00002DE, "STATUS_INSUFFICIENT_POWER" },
{ 0xC00002DF, "STATUS_SAM_NEED_BOOTKEY_PASSWORD" },
{ 0xC00002E0, "STATUS_SAM_NEED_BOOTKEY_FLOPPY" },
{ 0xC00002E1, "STATUS_DS_CANT_START" },
{ 0xC00002E2, "STATUS_DS_INIT_FAILURE" },
{ 0xC00002E3, "STATUS_SAM_INIT_FAILURE" },
{ 0xC00002E4, "STATUS_DS_GC_REQUIRED" },
{ 0xC00002E5, "STATUS_DS_LOCAL_MEMBER_OF_LOCAL_ONLY" },
{ 0xC00002E6, "STATUS_DS_NO_FPO_IN_UNIVERSAL_GROUPS" },
{ 0xC00002E7, "STATUS_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED" },
{ 0xC00002E8, "STATUS_MULTIPLE_FAULT_VIOLATION" },
{ 0xC0000300, "STATUS_NOT_SUPPORTED_ON_SBS" },
{ 0xC0009898, "STATUS_WOW_ASSERTION" },
{ 0xC0020001, "RPC_NT_INVALID_STRING_BINDING" },
{ 0xC0020002, "RPC_NT_WRONG_KIND_OF_BINDING" },
{ 0xC0020003, "RPC_NT_INVALID_BINDING" },
{ 0xC0020004, "RPC_NT_PROTSEQ_NOT_SUPPORTED" },
{ 0xC0020005, "RPC_NT_INVALID_RPC_PROTSEQ" },
{ 0xC0020006, "RPC_NT_INVALID_STRING_UUID" },
{ 0xC0020007, "RPC_NT_INVALID_ENDPOINT_FORMAT" },
{ 0xC0020008, "RPC_NT_INVALID_NET_ADDR" },
{ 0xC0020009, "RPC_NT_NO_ENDPOINT_FOUND" },
{ 0xC002000A, "RPC_NT_INVALID_TIMEOUT" },
{ 0xC002000B, "RPC_NT_OBJECT_NOT_FOUND" },
{ 0xC002000C, "RPC_NT_ALREADY_REGISTERED" },
{ 0xC002000D, "RPC_NT_TYPE_ALREADY_REGISTERED" },
{ 0xC002000E, "RPC_NT_ALREADY_LISTENING" },
{ 0xC002000F, "RPC_NT_NO_PROTSEQS_REGISTERED" },
{ 0xC0020010, "RPC_NT_NOT_LISTENING" },
{ 0xC0020011, "RPC_NT_UNKNOWN_MGR_TYPE" },
{ 0xC0020012, "RPC_NT_UNKNOWN_IF" },
{ 0xC0020013, "RPC_NT_NO_BINDINGS" },
{ 0xC0020014, "RPC_NT_NO_PROTSEQS" },
{ 0xC0020015, "RPC_NT_CANT_CREATE_ENDPOINT" },
{ 0xC0020016, "RPC_NT_OUT_OF_RESOURCES" },
{ 0xC0020017, "RPC_NT_SERVER_UNAVAILABLE" },
{ 0xC0020018, "RPC_NT_SERVER_TOO_BUSY" },
{ 0xC0020019, "RPC_NT_INVALID_NETWORK_OPTIONS" },
{ 0xC002001A, "RPC_NT_NO_CALL_ACTIVE" },
{ 0xC002001B, "RPC_NT_CALL_FAILED" },
{ 0xC002001C, "RPC_NT_CALL_FAILED_DNE" },
{ 0xC002001D, "RPC_NT_PROTOCOL_ERROR" },
{ 0xC002001F, "RPC_NT_UNSUPPORTED_TRANS_SYN" },
{ 0xC0020021, "RPC_NT_UNSUPPORTED_TYPE" },
{ 0xC0020022, "RPC_NT_INVALID_TAG" },
{ 0xC0020023, "RPC_NT_INVALID_BOUND" },
{ 0xC0020024, "RPC_NT_NO_ENTRY_NAME" },
{ 0xC0020025, "RPC_NT_INVALID_NAME_SYNTAX" },
{ 0xC0020026, "RPC_NT_UNSUPPORTED_NAME_SYNTAX" },
{ 0xC0020028, "RPC_NT_UUID_NO_ADDRESS" },
{ 0xC0020029, "RPC_NT_DUPLICATE_ENDPOINT" },
{ 0xC002002A, "RPC_NT_UNKNOWN_AUTHN_TYPE" },
{ 0xC002002B, "RPC_NT_MAX_CALLS_TOO_SMALL" },
{ 0xC002002C, "RPC_NT_STRING_TOO_LONG" },
{ 0xC002002D, "RPC_NT_PROTSEQ_NOT_FOUND" },
{ 0xC002002E, "RPC_NT_PROCNUM_OUT_OF_RANGE" },
{ 0xC002002F, "RPC_NT_BINDING_HAS_NO_AUTH" },
{ 0xC0020030, "RPC_NT_UNKNOWN_AUTHN_SERVICE" },
{ 0xC0020031, "RPC_NT_UNKNOWN_AUTHN_LEVEL" },
{ 0xC0020032, "RPC_NT_INVALID_AUTH_IDENTITY" },
{ 0xC0020033, "RPC_NT_UNKNOWN_AUTHZ_SERVICE" },
{ 0xC0020034, "EPT_NT_INVALID_ENTRY" },
{ 0xC0020035, "EPT_NT_CANT_PERFORM_OP" },
{ 0xC0020036, "EPT_NT_NOT_REGISTERED" },
{ 0xC0020037, "RPC_NT_NOTHING_TO_EXPORT" },
{ 0xC0020038, "RPC_NT_INCOMPLETE_NAME" },
{ 0xC0020039, "RPC_NT_INVALID_VERS_OPTION" },
{ 0xC002003A, "RPC_NT_NO_MORE_MEMBERS" },
{ 0xC002003B, "RPC_NT_NOT_ALL_OBJS_UNEXPORTED" },
{ 0xC002003C, "RPC_NT_INTERFACE_NOT_FOUND" },
{ 0xC002003D, "RPC_NT_ENTRY_ALREADY_EXISTS" },
{ 0xC002003E, "RPC_NT_ENTRY_NOT_FOUND" },
{ 0xC002003F, "RPC_NT_NAME_SERVICE_UNAVAILABLE" },
{ 0xC0020040, "RPC_NT_INVALID_NAF_ID" },
{ 0xC0020041, "RPC_NT_CANNOT_SUPPORT" },
{ 0xC0020042, "RPC_NT_NO_CONTEXT_AVAILABLE" },
{ 0xC0020043, "RPC_NT_INTERNAL_ERROR" },
{ 0xC0020044, "RPC_NT_ZERO_DIVIDE" },
{ 0xC0020045, "RPC_NT_ADDRESS_ERROR" },
{ 0xC0020046, "RPC_NT_FP_DIV_ZERO" },
{ 0xC0020047, "RPC_NT_FP_UNDERFLOW" },
{ 0xC0020048, "RPC_NT_FP_OVERFLOW" },
{ 0xC0021007, "RPC_P_RECEIVE_ALERTED" },
{ 0xC0021008, "RPC_P_CONNECTION_CLOSED" },
{ 0xC0021009, "RPC_P_RECEIVE_FAILED" },
{ 0xC002100A, "RPC_P_SEND_FAILED" },
{ 0xC002100B, "RPC_P_TIMEOUT" },
{ 0xC002100C, "RPC_P_SERVER_TRANSPORT_ERROR" },
{ 0xC002100E, "RPC_P_EXCEPTION_OCCURED" },
{ 0xC0021012, "RPC_P_CONNECTION_SHUTDOWN" },
{ 0xC0021015, "RPC_P_THREAD_LISTENING" },
{ 0xC0030001, "RPC_NT_NO_MORE_ENTRIES" },
{ 0xC0030002, "RPC_NT_SS_CHAR_TRANS_OPEN_FAIL" },
{ 0xC0030003, "RPC_NT_SS_CHAR_TRANS_SHORT_FILE" },
{ 0xC0030004, "RPC_NT_SS_IN_NULL_CONTEXT" },
{ 0xC0030005, "RPC_NT_SS_CONTEXT_MISMATCH" },
{ 0xC0030006, "RPC_NT_SS_CONTEXT_DAMAGED" },
{ 0xC0030007, "RPC_NT_SS_HANDLES_MISMATCH" },
{ 0xC0030008, "RPC_NT_SS_CANNOT_GET_CALL_HANDLE" },
{ 0xC0030009, "RPC_NT_NULL_REF_POINTER" },
{ 0xC003000A, "RPC_NT_ENUM_VALUE_OUT_OF_RANGE" },
{ 0xC003000B, "RPC_NT_BYTE_COUNT_TOO_SMALL" },
{ 0xC003000C, "RPC_NT_BAD_STUB_DATA" },
{ 0xC0020049, "RPC_NT_CALL_IN_PROGRESS" },
{ 0xC002004A, "RPC_NT_NO_MORE_BINDINGS" },
{ 0xC002004B, "RPC_NT_GROUP_MEMBER_NOT_FOUND" },
{ 0xC002004C, "EPT_NT_CANT_CREATE" },
{ 0xC002004D, "RPC_NT_INVALID_OBJECT" },
{ 0xC002004F, "RPC_NT_NO_INTERFACES" },
{ 0xC0020050, "RPC_NT_CALL_CANCELLED" },
{ 0xC0020051, "RPC_NT_BINDING_INCOMPLETE" },
{ 0xC0020052, "RPC_NT_COMM_FAILURE" },
{ 0xC0020053, "RPC_NT_UNSUPPORTED_AUTHN_LEVEL" },
{ 0xC0020054, "RPC_NT_NO_PRINC_NAME" },
{ 0xC0020055, "RPC_NT_NOT_RPC_ERROR" },
{ 0x40020056, "RPC_NT_UUID_LOCAL_ONLY" },
{ 0xC0020057, "RPC_NT_SEC_PKG_ERROR" },
{ 0xC0020058, "RPC_NT_NOT_CANCELLED" },
{ 0xC0030059, "RPC_NT_INVALID_ES_ACTION" },
{ 0xC003005A, "RPC_NT_WRONG_ES_VERSION" },
{ 0xC003005B, "RPC_NT_WRONG_STUB_VERSION" },
{ 0xC003005C, "RPC_NT_INVALID_PIPE_OBJECT" },
{ 0xC003005D, "RPC_NT_INVALID_PIPE_OPERATION" },
{ 0xC003005E, "RPC_NT_WRONG_PIPE_VERSION" },
{ 0x400200AF, "RPC_NT_SEND_INCOMPLETE" },
{ 0, NULL }
};
/*
* return an NT error string from a SMB buffer
*/
const char *
nt_errstr(uint32_t err)
{
static char ret[128];
int i;
ret[0] = 0;
for (i = 0; nt_errors[i].name; i++) {
if (err == nt_errors[i].code)
return nt_errors[i].name;
}
snprintf(ret, sizeof(ret), "0x%08x", err);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2639_0 |
crossvul-cpp_data_good_3032_0 | /*
* linux/kernel/posix-timers.c
*
*
* 2002-10-15 Posix Clocks & timers
* by George Anzinger george@mvista.com
*
* Copyright (C) 2002 2003 by MontaVista Software.
*
* 2004-06-01 Fix CLOCK_REALTIME clock/timer TIMER_ABSTIME bug.
* Copyright (C) 2004 Boris Hu
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* MontaVista Software | 1237 East Arques Avenue | Sunnyvale | CA 94085 | USA
*/
/* These are all the functions necessary to implement
* POSIX clocks & timers
*/
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/mutex.h>
#include <linux/sched/task.h>
#include <linux/uaccess.h>
#include <linux/list.h>
#include <linux/init.h>
#include <linux/compiler.h>
#include <linux/hash.h>
#include <linux/posix-clock.h>
#include <linux/posix-timers.h>
#include <linux/syscalls.h>
#include <linux/wait.h>
#include <linux/workqueue.h>
#include <linux/export.h>
#include <linux/hashtable.h>
#include <linux/compat.h>
#include "timekeeping.h"
#include "posix-timers.h"
/*
* Management arrays for POSIX timers. Timers are now kept in static hash table
* with 512 entries.
* Timer ids are allocated by local routine, which selects proper hash head by
* key, constructed from current->signal address and per signal struct counter.
* This keeps timer ids unique per process, but now they can intersect between
* processes.
*/
/*
* Lets keep our timers in a slab cache :-)
*/
static struct kmem_cache *posix_timers_cache;
static DEFINE_HASHTABLE(posix_timers_hashtable, 9);
static DEFINE_SPINLOCK(hash_lock);
static const struct k_clock * const posix_clocks[];
static const struct k_clock *clockid_to_kclock(const clockid_t id);
static const struct k_clock clock_realtime, clock_monotonic;
/*
* we assume that the new SIGEV_THREAD_ID shares no bits with the other
* SIGEV values. Here we put out an error if this assumption fails.
*/
#if SIGEV_THREAD_ID != (SIGEV_THREAD_ID & \
~(SIGEV_SIGNAL | SIGEV_NONE | SIGEV_THREAD))
#error "SIGEV_THREAD_ID must not share bit with other SIGEV values!"
#endif
/*
* parisc wants ENOTSUP instead of EOPNOTSUPP
*/
#ifndef ENOTSUP
# define ENANOSLEEP_NOTSUP EOPNOTSUPP
#else
# define ENANOSLEEP_NOTSUP ENOTSUP
#endif
/*
* The timer ID is turned into a timer address by idr_find().
* Verifying a valid ID consists of:
*
* a) checking that idr_find() returns other than -1.
* b) checking that the timer id matches the one in the timer itself.
* c) that the timer owner is in the callers thread group.
*/
/*
* CLOCKs: The POSIX standard calls for a couple of clocks and allows us
* to implement others. This structure defines the various
* clocks.
*
* RESOLUTION: Clock resolution is used to round up timer and interval
* times, NOT to report clock times, which are reported with as
* much resolution as the system can muster. In some cases this
* resolution may depend on the underlying clock hardware and
* may not be quantifiable until run time, and only then is the
* necessary code is written. The standard says we should say
* something about this issue in the documentation...
*
* FUNCTIONS: The CLOCKs structure defines possible functions to
* handle various clock functions.
*
* The standard POSIX timer management code assumes the
* following: 1.) The k_itimer struct (sched.h) is used for
* the timer. 2.) The list, it_lock, it_clock, it_id and
* it_pid fields are not modified by timer code.
*
* Permissions: It is assumed that the clock_settime() function defined
* for each clock will take care of permission checks. Some
* clocks may be set able by any user (i.e. local process
* clocks) others not. Currently the only set able clock we
* have is CLOCK_REALTIME and its high res counter part, both of
* which we beg off on and pass to do_sys_settimeofday().
*/
static struct k_itimer *__lock_timer(timer_t timer_id, unsigned long *flags);
#define lock_timer(tid, flags) \
({ struct k_itimer *__timr; \
__cond_lock(&__timr->it_lock, __timr = __lock_timer(tid, flags)); \
__timr; \
})
static int hash(struct signal_struct *sig, unsigned int nr)
{
return hash_32(hash32_ptr(sig) ^ nr, HASH_BITS(posix_timers_hashtable));
}
static struct k_itimer *__posix_timers_find(struct hlist_head *head,
struct signal_struct *sig,
timer_t id)
{
struct k_itimer *timer;
hlist_for_each_entry_rcu(timer, head, t_hash) {
if ((timer->it_signal == sig) && (timer->it_id == id))
return timer;
}
return NULL;
}
static struct k_itimer *posix_timer_by_id(timer_t id)
{
struct signal_struct *sig = current->signal;
struct hlist_head *head = &posix_timers_hashtable[hash(sig, id)];
return __posix_timers_find(head, sig, id);
}
static int posix_timer_add(struct k_itimer *timer)
{
struct signal_struct *sig = current->signal;
int first_free_id = sig->posix_timer_id;
struct hlist_head *head;
int ret = -ENOENT;
do {
spin_lock(&hash_lock);
head = &posix_timers_hashtable[hash(sig, sig->posix_timer_id)];
if (!__posix_timers_find(head, sig, sig->posix_timer_id)) {
hlist_add_head_rcu(&timer->t_hash, head);
ret = sig->posix_timer_id;
}
if (++sig->posix_timer_id < 0)
sig->posix_timer_id = 0;
if ((sig->posix_timer_id == first_free_id) && (ret == -ENOENT))
/* Loop over all possible ids completed */
ret = -EAGAIN;
spin_unlock(&hash_lock);
} while (ret == -ENOENT);
return ret;
}
static inline void unlock_timer(struct k_itimer *timr, unsigned long flags)
{
spin_unlock_irqrestore(&timr->it_lock, flags);
}
/* Get clock_realtime */
static int posix_clock_realtime_get(clockid_t which_clock, struct timespec64 *tp)
{
ktime_get_real_ts64(tp);
return 0;
}
/* Set clock_realtime */
static int posix_clock_realtime_set(const clockid_t which_clock,
const struct timespec64 *tp)
{
return do_sys_settimeofday64(tp, NULL);
}
static int posix_clock_realtime_adj(const clockid_t which_clock,
struct timex *t)
{
return do_adjtimex(t);
}
/*
* Get monotonic time for posix timers
*/
static int posix_ktime_get_ts(clockid_t which_clock, struct timespec64 *tp)
{
ktime_get_ts64(tp);
return 0;
}
/*
* Get monotonic-raw time for posix timers
*/
static int posix_get_monotonic_raw(clockid_t which_clock, struct timespec64 *tp)
{
getrawmonotonic64(tp);
return 0;
}
static int posix_get_realtime_coarse(clockid_t which_clock, struct timespec64 *tp)
{
*tp = current_kernel_time64();
return 0;
}
static int posix_get_monotonic_coarse(clockid_t which_clock,
struct timespec64 *tp)
{
*tp = get_monotonic_coarse64();
return 0;
}
static int posix_get_coarse_res(const clockid_t which_clock, struct timespec64 *tp)
{
*tp = ktime_to_timespec64(KTIME_LOW_RES);
return 0;
}
static int posix_get_boottime(const clockid_t which_clock, struct timespec64 *tp)
{
get_monotonic_boottime64(tp);
return 0;
}
static int posix_get_tai(clockid_t which_clock, struct timespec64 *tp)
{
timekeeping_clocktai64(tp);
return 0;
}
static int posix_get_hrtimer_res(clockid_t which_clock, struct timespec64 *tp)
{
tp->tv_sec = 0;
tp->tv_nsec = hrtimer_resolution;
return 0;
}
/*
* Initialize everything, well, just everything in Posix clocks/timers ;)
*/
static __init int init_posix_timers(void)
{
posix_timers_cache = kmem_cache_create("posix_timers_cache",
sizeof (struct k_itimer), 0, SLAB_PANIC,
NULL);
return 0;
}
__initcall(init_posix_timers);
static void common_hrtimer_rearm(struct k_itimer *timr)
{
struct hrtimer *timer = &timr->it.real.timer;
if (!timr->it_interval)
return;
timr->it_overrun += (unsigned int) hrtimer_forward(timer,
timer->base->get_time(),
timr->it_interval);
hrtimer_restart(timer);
}
/*
* This function is exported for use by the signal deliver code. It is
* called just prior to the info block being released and passes that
* block to us. It's function is to update the overrun entry AND to
* restart the timer. It should only be called if the timer is to be
* restarted (i.e. we have flagged this in the sys_private entry of the
* info block).
*
* To protect against the timer going away while the interrupt is queued,
* we require that the it_requeue_pending flag be set.
*/
void posixtimer_rearm(struct siginfo *info)
{
struct k_itimer *timr;
unsigned long flags;
timr = lock_timer(info->si_tid, &flags);
if (!timr)
return;
if (timr->it_requeue_pending == info->si_sys_private) {
timr->kclock->timer_rearm(timr);
timr->it_active = 1;
timr->it_overrun_last = timr->it_overrun;
timr->it_overrun = -1;
++timr->it_requeue_pending;
info->si_overrun += timr->it_overrun_last;
}
unlock_timer(timr, flags);
}
int posix_timer_event(struct k_itimer *timr, int si_private)
{
struct task_struct *task;
int shared, ret = -1;
/*
* FIXME: if ->sigq is queued we can race with
* dequeue_signal()->posixtimer_rearm().
*
* If dequeue_signal() sees the "right" value of
* si_sys_private it calls posixtimer_rearm().
* We re-queue ->sigq and drop ->it_lock().
* posixtimer_rearm() locks the timer
* and re-schedules it while ->sigq is pending.
* Not really bad, but not that we want.
*/
timr->sigq->info.si_sys_private = si_private;
rcu_read_lock();
task = pid_task(timr->it_pid, PIDTYPE_PID);
if (task) {
shared = !(timr->it_sigev_notify & SIGEV_THREAD_ID);
ret = send_sigqueue(timr->sigq, task, shared);
}
rcu_read_unlock();
/* If we failed to send the signal the timer stops. */
return ret > 0;
}
/*
* This function gets called when a POSIX.1b interval timer expires. It
* is used as a callback from the kernel internal timer. The
* run_timer_list code ALWAYS calls with interrupts on.
* This code is for CLOCK_REALTIME* and CLOCK_MONOTONIC* timers.
*/
static enum hrtimer_restart posix_timer_fn(struct hrtimer *timer)
{
struct k_itimer *timr;
unsigned long flags;
int si_private = 0;
enum hrtimer_restart ret = HRTIMER_NORESTART;
timr = container_of(timer, struct k_itimer, it.real.timer);
spin_lock_irqsave(&timr->it_lock, flags);
timr->it_active = 0;
if (timr->it_interval != 0)
si_private = ++timr->it_requeue_pending;
if (posix_timer_event(timr, si_private)) {
/*
* signal was not sent because of sig_ignor
* we will not get a call back to restart it AND
* it should be restarted.
*/
if (timr->it_interval != 0) {
ktime_t now = hrtimer_cb_get_time(timer);
/*
* FIXME: What we really want, is to stop this
* timer completely and restart it in case the
* SIG_IGN is removed. This is a non trivial
* change which involves sighand locking
* (sigh !), which we don't want to do late in
* the release cycle.
*
* For now we just let timers with an interval
* less than a jiffie expire every jiffie to
* avoid softirq starvation in case of SIG_IGN
* and a very small interval, which would put
* the timer right back on the softirq pending
* list. By moving now ahead of time we trick
* hrtimer_forward() to expire the timer
* later, while we still maintain the overrun
* accuracy, but have some inconsistency in
* the timer_gettime() case. This is at least
* better than a starved softirq. A more
* complex fix which solves also another related
* inconsistency is already in the pipeline.
*/
#ifdef CONFIG_HIGH_RES_TIMERS
{
ktime_t kj = NSEC_PER_SEC / HZ;
if (timr->it_interval < kj)
now = ktime_add(now, kj);
}
#endif
timr->it_overrun += (unsigned int)
hrtimer_forward(timer, now,
timr->it_interval);
ret = HRTIMER_RESTART;
++timr->it_requeue_pending;
timr->it_active = 1;
}
}
unlock_timer(timr, flags);
return ret;
}
static struct pid *good_sigevent(sigevent_t * event)
{
struct task_struct *rtn = current->group_leader;
switch (event->sigev_notify) {
case SIGEV_SIGNAL | SIGEV_THREAD_ID:
rtn = find_task_by_vpid(event->sigev_notify_thread_id);
if (!rtn || !same_thread_group(rtn, current))
return NULL;
/* FALLTHRU */
case SIGEV_SIGNAL:
case SIGEV_THREAD:
if (event->sigev_signo <= 0 || event->sigev_signo > SIGRTMAX)
return NULL;
/* FALLTHRU */
case SIGEV_NONE:
return task_pid(rtn);
default:
return NULL;
}
}
static struct k_itimer * alloc_posix_timer(void)
{
struct k_itimer *tmr;
tmr = kmem_cache_zalloc(posix_timers_cache, GFP_KERNEL);
if (!tmr)
return tmr;
if (unlikely(!(tmr->sigq = sigqueue_alloc()))) {
kmem_cache_free(posix_timers_cache, tmr);
return NULL;
}
memset(&tmr->sigq->info, 0, sizeof(siginfo_t));
return tmr;
}
static void k_itimer_rcu_free(struct rcu_head *head)
{
struct k_itimer *tmr = container_of(head, struct k_itimer, it.rcu);
kmem_cache_free(posix_timers_cache, tmr);
}
#define IT_ID_SET 1
#define IT_ID_NOT_SET 0
static void release_posix_timer(struct k_itimer *tmr, int it_id_set)
{
if (it_id_set) {
unsigned long flags;
spin_lock_irqsave(&hash_lock, flags);
hlist_del_rcu(&tmr->t_hash);
spin_unlock_irqrestore(&hash_lock, flags);
}
put_pid(tmr->it_pid);
sigqueue_free(tmr->sigq);
call_rcu(&tmr->it.rcu, k_itimer_rcu_free);
}
static int common_timer_create(struct k_itimer *new_timer)
{
hrtimer_init(&new_timer->it.real.timer, new_timer->it_clock, 0);
return 0;
}
/* Create a POSIX.1b interval timer. */
static int do_timer_create(clockid_t which_clock, struct sigevent *event,
timer_t __user *created_timer_id)
{
const struct k_clock *kc = clockid_to_kclock(which_clock);
struct k_itimer *new_timer;
int error, new_timer_id;
int it_id_set = IT_ID_NOT_SET;
if (!kc)
return -EINVAL;
if (!kc->timer_create)
return -EOPNOTSUPP;
new_timer = alloc_posix_timer();
if (unlikely(!new_timer))
return -EAGAIN;
spin_lock_init(&new_timer->it_lock);
new_timer_id = posix_timer_add(new_timer);
if (new_timer_id < 0) {
error = new_timer_id;
goto out;
}
it_id_set = IT_ID_SET;
new_timer->it_id = (timer_t) new_timer_id;
new_timer->it_clock = which_clock;
new_timer->kclock = kc;
new_timer->it_overrun = -1;
if (event) {
rcu_read_lock();
new_timer->it_pid = get_pid(good_sigevent(event));
rcu_read_unlock();
if (!new_timer->it_pid) {
error = -EINVAL;
goto out;
}
new_timer->it_sigev_notify = event->sigev_notify;
new_timer->sigq->info.si_signo = event->sigev_signo;
new_timer->sigq->info.si_value = event->sigev_value;
} else {
new_timer->it_sigev_notify = SIGEV_SIGNAL;
new_timer->sigq->info.si_signo = SIGALRM;
memset(&new_timer->sigq->info.si_value, 0, sizeof(sigval_t));
new_timer->sigq->info.si_value.sival_int = new_timer->it_id;
new_timer->it_pid = get_pid(task_tgid(current));
}
new_timer->sigq->info.si_tid = new_timer->it_id;
new_timer->sigq->info.si_code = SI_TIMER;
if (copy_to_user(created_timer_id,
&new_timer_id, sizeof (new_timer_id))) {
error = -EFAULT;
goto out;
}
error = kc->timer_create(new_timer);
if (error)
goto out;
spin_lock_irq(¤t->sighand->siglock);
new_timer->it_signal = current->signal;
list_add(&new_timer->list, ¤t->signal->posix_timers);
spin_unlock_irq(¤t->sighand->siglock);
return 0;
/*
* In the case of the timer belonging to another task, after
* the task is unlocked, the timer is owned by the other task
* and may cease to exist at any time. Don't use or modify
* new_timer after the unlock call.
*/
out:
release_posix_timer(new_timer, it_id_set);
return error;
}
SYSCALL_DEFINE3(timer_create, const clockid_t, which_clock,
struct sigevent __user *, timer_event_spec,
timer_t __user *, created_timer_id)
{
if (timer_event_spec) {
sigevent_t event;
if (copy_from_user(&event, timer_event_spec, sizeof (event)))
return -EFAULT;
return do_timer_create(which_clock, &event, created_timer_id);
}
return do_timer_create(which_clock, NULL, created_timer_id);
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE3(timer_create, clockid_t, which_clock,
struct compat_sigevent __user *, timer_event_spec,
timer_t __user *, created_timer_id)
{
if (timer_event_spec) {
sigevent_t event;
if (get_compat_sigevent(&event, timer_event_spec))
return -EFAULT;
return do_timer_create(which_clock, &event, created_timer_id);
}
return do_timer_create(which_clock, NULL, created_timer_id);
}
#endif
/*
* Locking issues: We need to protect the result of the id look up until
* we get the timer locked down so it is not deleted under us. The
* removal is done under the idr spinlock so we use that here to bridge
* the find to the timer lock. To avoid a dead lock, the timer id MUST
* be release with out holding the timer lock.
*/
static struct k_itimer *__lock_timer(timer_t timer_id, unsigned long *flags)
{
struct k_itimer *timr;
/*
* timer_t could be any type >= int and we want to make sure any
* @timer_id outside positive int range fails lookup.
*/
if ((unsigned long long)timer_id > INT_MAX)
return NULL;
rcu_read_lock();
timr = posix_timer_by_id(timer_id);
if (timr) {
spin_lock_irqsave(&timr->it_lock, *flags);
if (timr->it_signal == current->signal) {
rcu_read_unlock();
return timr;
}
spin_unlock_irqrestore(&timr->it_lock, *flags);
}
rcu_read_unlock();
return NULL;
}
static ktime_t common_hrtimer_remaining(struct k_itimer *timr, ktime_t now)
{
struct hrtimer *timer = &timr->it.real.timer;
return __hrtimer_expires_remaining_adjusted(timer, now);
}
static int common_hrtimer_forward(struct k_itimer *timr, ktime_t now)
{
struct hrtimer *timer = &timr->it.real.timer;
return (int)hrtimer_forward(timer, now, timr->it_interval);
}
/*
* Get the time remaining on a POSIX.1b interval timer. This function
* is ALWAYS called with spin_lock_irq on the timer, thus it must not
* mess with irq.
*
* We have a couple of messes to clean up here. First there is the case
* of a timer that has a requeue pending. These timers should appear to
* be in the timer list with an expiry as if we were to requeue them
* now.
*
* The second issue is the SIGEV_NONE timer which may be active but is
* not really ever put in the timer list (to save system resources).
* This timer may be expired, and if so, we will do it here. Otherwise
* it is the same as a requeue pending timer WRT to what we should
* report.
*/
void common_timer_get(struct k_itimer *timr, struct itimerspec64 *cur_setting)
{
const struct k_clock *kc = timr->kclock;
ktime_t now, remaining, iv;
struct timespec64 ts64;
bool sig_none;
sig_none = timr->it_sigev_notify == SIGEV_NONE;
iv = timr->it_interval;
/* interval timer ? */
if (iv) {
cur_setting->it_interval = ktime_to_timespec64(iv);
} else if (!timr->it_active) {
/*
* SIGEV_NONE oneshot timers are never queued. Check them
* below.
*/
if (!sig_none)
return;
}
/*
* The timespec64 based conversion is suboptimal, but it's not
* worth to implement yet another callback.
*/
kc->clock_get(timr->it_clock, &ts64);
now = timespec64_to_ktime(ts64);
/*
* When a requeue is pending or this is a SIGEV_NONE timer move the
* expiry time forward by intervals, so expiry is > now.
*/
if (iv && (timr->it_requeue_pending & REQUEUE_PENDING || sig_none))
timr->it_overrun += kc->timer_forward(timr, now);
remaining = kc->timer_remaining(timr, now);
/* Return 0 only, when the timer is expired and not pending */
if (remaining <= 0) {
/*
* A single shot SIGEV_NONE timer must return 0, when
* it is expired !
*/
if (!sig_none)
cur_setting->it_value.tv_nsec = 1;
} else {
cur_setting->it_value = ktime_to_timespec64(remaining);
}
}
/* Get the time remaining on a POSIX.1b interval timer. */
static int do_timer_gettime(timer_t timer_id, struct itimerspec64 *setting)
{
struct k_itimer *timr;
const struct k_clock *kc;
unsigned long flags;
int ret = 0;
timr = lock_timer(timer_id, &flags);
if (!timr)
return -EINVAL;
memset(setting, 0, sizeof(*setting));
kc = timr->kclock;
if (WARN_ON_ONCE(!kc || !kc->timer_get))
ret = -EINVAL;
else
kc->timer_get(timr, setting);
unlock_timer(timr, flags);
return ret;
}
/* Get the time remaining on a POSIX.1b interval timer. */
SYSCALL_DEFINE2(timer_gettime, timer_t, timer_id,
struct itimerspec __user *, setting)
{
struct itimerspec64 cur_setting;
int ret = do_timer_gettime(timer_id, &cur_setting);
if (!ret) {
if (put_itimerspec64(&cur_setting, setting))
ret = -EFAULT;
}
return ret;
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE2(timer_gettime, timer_t, timer_id,
struct compat_itimerspec __user *, setting)
{
struct itimerspec64 cur_setting;
int ret = do_timer_gettime(timer_id, &cur_setting);
if (!ret) {
if (put_compat_itimerspec64(&cur_setting, setting))
ret = -EFAULT;
}
return ret;
}
#endif
/*
* Get the number of overruns of a POSIX.1b interval timer. This is to
* be the overrun of the timer last delivered. At the same time we are
* accumulating overruns on the next timer. The overrun is frozen when
* the signal is delivered, either at the notify time (if the info block
* is not queued) or at the actual delivery time (as we are informed by
* the call back to posixtimer_rearm(). So all we need to do is
* to pick up the frozen overrun.
*/
SYSCALL_DEFINE1(timer_getoverrun, timer_t, timer_id)
{
struct k_itimer *timr;
int overrun;
unsigned long flags;
timr = lock_timer(timer_id, &flags);
if (!timr)
return -EINVAL;
overrun = timr->it_overrun_last;
unlock_timer(timr, flags);
return overrun;
}
static void common_hrtimer_arm(struct k_itimer *timr, ktime_t expires,
bool absolute, bool sigev_none)
{
struct hrtimer *timer = &timr->it.real.timer;
enum hrtimer_mode mode;
mode = absolute ? HRTIMER_MODE_ABS : HRTIMER_MODE_REL;
/*
* Posix magic: Relative CLOCK_REALTIME timers are not affected by
* clock modifications, so they become CLOCK_MONOTONIC based under the
* hood. See hrtimer_init(). Update timr->kclock, so the generic
* functions which use timr->kclock->clock_get() work.
*
* Note: it_clock stays unmodified, because the next timer_set() might
* use ABSTIME, so it needs to switch back.
*/
if (timr->it_clock == CLOCK_REALTIME)
timr->kclock = absolute ? &clock_realtime : &clock_monotonic;
hrtimer_init(&timr->it.real.timer, timr->it_clock, mode);
timr->it.real.timer.function = posix_timer_fn;
if (!absolute)
expires = ktime_add_safe(expires, timer->base->get_time());
hrtimer_set_expires(timer, expires);
if (!sigev_none)
hrtimer_start_expires(timer, HRTIMER_MODE_ABS);
}
static int common_hrtimer_try_to_cancel(struct k_itimer *timr)
{
return hrtimer_try_to_cancel(&timr->it.real.timer);
}
/* Set a POSIX.1b interval timer. */
int common_timer_set(struct k_itimer *timr, int flags,
struct itimerspec64 *new_setting,
struct itimerspec64 *old_setting)
{
const struct k_clock *kc = timr->kclock;
bool sigev_none;
ktime_t expires;
if (old_setting)
common_timer_get(timr, old_setting);
/* Prevent rearming by clearing the interval */
timr->it_interval = 0;
/*
* Careful here. On SMP systems the timer expiry function could be
* active and spinning on timr->it_lock.
*/
if (kc->timer_try_to_cancel(timr) < 0)
return TIMER_RETRY;
timr->it_active = 0;
timr->it_requeue_pending = (timr->it_requeue_pending + 2) &
~REQUEUE_PENDING;
timr->it_overrun_last = 0;
/* Switch off the timer when it_value is zero */
if (!new_setting->it_value.tv_sec && !new_setting->it_value.tv_nsec)
return 0;
timr->it_interval = timespec64_to_ktime(new_setting->it_interval);
expires = timespec64_to_ktime(new_setting->it_value);
sigev_none = timr->it_sigev_notify == SIGEV_NONE;
kc->timer_arm(timr, expires, flags & TIMER_ABSTIME, sigev_none);
timr->it_active = !sigev_none;
return 0;
}
static int do_timer_settime(timer_t timer_id, int flags,
struct itimerspec64 *new_spec64,
struct itimerspec64 *old_spec64)
{
const struct k_clock *kc;
struct k_itimer *timr;
unsigned long flag;
int error = 0;
if (!timespec64_valid(&new_spec64->it_interval) ||
!timespec64_valid(&new_spec64->it_value))
return -EINVAL;
if (old_spec64)
memset(old_spec64, 0, sizeof(*old_spec64));
retry:
timr = lock_timer(timer_id, &flag);
if (!timr)
return -EINVAL;
kc = timr->kclock;
if (WARN_ON_ONCE(!kc || !kc->timer_set))
error = -EINVAL;
else
error = kc->timer_set(timr, flags, new_spec64, old_spec64);
unlock_timer(timr, flag);
if (error == TIMER_RETRY) {
old_spec64 = NULL; // We already got the old time...
goto retry;
}
return error;
}
/* Set a POSIX.1b interval timer */
SYSCALL_DEFINE4(timer_settime, timer_t, timer_id, int, flags,
const struct itimerspec __user *, new_setting,
struct itimerspec __user *, old_setting)
{
struct itimerspec64 new_spec, old_spec;
struct itimerspec64 *rtn = old_setting ? &old_spec : NULL;
int error = 0;
if (!new_setting)
return -EINVAL;
if (get_itimerspec64(&new_spec, new_setting))
return -EFAULT;
error = do_timer_settime(timer_id, flags, &new_spec, rtn);
if (!error && old_setting) {
if (put_itimerspec64(&old_spec, old_setting))
error = -EFAULT;
}
return error;
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE4(timer_settime, timer_t, timer_id, int, flags,
struct compat_itimerspec __user *, new,
struct compat_itimerspec __user *, old)
{
struct itimerspec64 new_spec, old_spec;
struct itimerspec64 *rtn = old ? &old_spec : NULL;
int error = 0;
if (!new)
return -EINVAL;
if (get_compat_itimerspec64(&new_spec, new))
return -EFAULT;
error = do_timer_settime(timer_id, flags, &new_spec, rtn);
if (!error && old) {
if (put_compat_itimerspec64(&old_spec, old))
error = -EFAULT;
}
return error;
}
#endif
int common_timer_del(struct k_itimer *timer)
{
const struct k_clock *kc = timer->kclock;
timer->it_interval = 0;
if (kc->timer_try_to_cancel(timer) < 0)
return TIMER_RETRY;
timer->it_active = 0;
return 0;
}
static inline int timer_delete_hook(struct k_itimer *timer)
{
const struct k_clock *kc = timer->kclock;
if (WARN_ON_ONCE(!kc || !kc->timer_del))
return -EINVAL;
return kc->timer_del(timer);
}
/* Delete a POSIX.1b interval timer. */
SYSCALL_DEFINE1(timer_delete, timer_t, timer_id)
{
struct k_itimer *timer;
unsigned long flags;
retry_delete:
timer = lock_timer(timer_id, &flags);
if (!timer)
return -EINVAL;
if (timer_delete_hook(timer) == TIMER_RETRY) {
unlock_timer(timer, flags);
goto retry_delete;
}
spin_lock(¤t->sighand->siglock);
list_del(&timer->list);
spin_unlock(¤t->sighand->siglock);
/*
* This keeps any tasks waiting on the spin lock from thinking
* they got something (see the lock code above).
*/
timer->it_signal = NULL;
unlock_timer(timer, flags);
release_posix_timer(timer, IT_ID_SET);
return 0;
}
/*
* return timer owned by the process, used by exit_itimers
*/
static void itimer_delete(struct k_itimer *timer)
{
unsigned long flags;
retry_delete:
spin_lock_irqsave(&timer->it_lock, flags);
if (timer_delete_hook(timer) == TIMER_RETRY) {
unlock_timer(timer, flags);
goto retry_delete;
}
list_del(&timer->list);
/*
* This keeps any tasks waiting on the spin lock from thinking
* they got something (see the lock code above).
*/
timer->it_signal = NULL;
unlock_timer(timer, flags);
release_posix_timer(timer, IT_ID_SET);
}
/*
* This is called by do_exit or de_thread, only when there are no more
* references to the shared signal_struct.
*/
void exit_itimers(struct signal_struct *sig)
{
struct k_itimer *tmr;
while (!list_empty(&sig->posix_timers)) {
tmr = list_entry(sig->posix_timers.next, struct k_itimer, list);
itimer_delete(tmr);
}
}
SYSCALL_DEFINE2(clock_settime, const clockid_t, which_clock,
const struct timespec __user *, tp)
{
const struct k_clock *kc = clockid_to_kclock(which_clock);
struct timespec64 new_tp;
if (!kc || !kc->clock_set)
return -EINVAL;
if (get_timespec64(&new_tp, tp))
return -EFAULT;
return kc->clock_set(which_clock, &new_tp);
}
SYSCALL_DEFINE2(clock_gettime, const clockid_t, which_clock,
struct timespec __user *,tp)
{
const struct k_clock *kc = clockid_to_kclock(which_clock);
struct timespec64 kernel_tp;
int error;
if (!kc)
return -EINVAL;
error = kc->clock_get(which_clock, &kernel_tp);
if (!error && put_timespec64(&kernel_tp, tp))
error = -EFAULT;
return error;
}
SYSCALL_DEFINE2(clock_adjtime, const clockid_t, which_clock,
struct timex __user *, utx)
{
const struct k_clock *kc = clockid_to_kclock(which_clock);
struct timex ktx;
int err;
if (!kc)
return -EINVAL;
if (!kc->clock_adj)
return -EOPNOTSUPP;
if (copy_from_user(&ktx, utx, sizeof(ktx)))
return -EFAULT;
err = kc->clock_adj(which_clock, &ktx);
if (err >= 0 && copy_to_user(utx, &ktx, sizeof(ktx)))
return -EFAULT;
return err;
}
SYSCALL_DEFINE2(clock_getres, const clockid_t, which_clock,
struct timespec __user *, tp)
{
const struct k_clock *kc = clockid_to_kclock(which_clock);
struct timespec64 rtn_tp;
int error;
if (!kc)
return -EINVAL;
error = kc->clock_getres(which_clock, &rtn_tp);
if (!error && tp && put_timespec64(&rtn_tp, tp))
error = -EFAULT;
return error;
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE2(clock_settime, clockid_t, which_clock,
struct compat_timespec __user *, tp)
{
const struct k_clock *kc = clockid_to_kclock(which_clock);
struct timespec64 ts;
if (!kc || !kc->clock_set)
return -EINVAL;
if (compat_get_timespec64(&ts, tp))
return -EFAULT;
return kc->clock_set(which_clock, &ts);
}
COMPAT_SYSCALL_DEFINE2(clock_gettime, clockid_t, which_clock,
struct compat_timespec __user *, tp)
{
const struct k_clock *kc = clockid_to_kclock(which_clock);
struct timespec64 ts;
int err;
if (!kc)
return -EINVAL;
err = kc->clock_get(which_clock, &ts);
if (!err && compat_put_timespec64(&ts, tp))
err = -EFAULT;
return err;
}
COMPAT_SYSCALL_DEFINE2(clock_adjtime, clockid_t, which_clock,
struct compat_timex __user *, utp)
{
const struct k_clock *kc = clockid_to_kclock(which_clock);
struct timex ktx;
int err;
if (!kc)
return -EINVAL;
if (!kc->clock_adj)
return -EOPNOTSUPP;
err = compat_get_timex(&ktx, utp);
if (err)
return err;
err = kc->clock_adj(which_clock, &ktx);
if (err >= 0)
err = compat_put_timex(utp, &ktx);
return err;
}
COMPAT_SYSCALL_DEFINE2(clock_getres, clockid_t, which_clock,
struct compat_timespec __user *, tp)
{
const struct k_clock *kc = clockid_to_kclock(which_clock);
struct timespec64 ts;
int err;
if (!kc)
return -EINVAL;
err = kc->clock_getres(which_clock, &ts);
if (!err && tp && compat_put_timespec64(&ts, tp))
return -EFAULT;
return err;
}
#endif
/*
* nanosleep for monotonic and realtime clocks
*/
static int common_nsleep(const clockid_t which_clock, int flags,
const struct timespec64 *rqtp)
{
return hrtimer_nanosleep(rqtp, flags & TIMER_ABSTIME ?
HRTIMER_MODE_ABS : HRTIMER_MODE_REL,
which_clock);
}
SYSCALL_DEFINE4(clock_nanosleep, const clockid_t, which_clock, int, flags,
const struct timespec __user *, rqtp,
struct timespec __user *, rmtp)
{
const struct k_clock *kc = clockid_to_kclock(which_clock);
struct timespec64 t;
if (!kc)
return -EINVAL;
if (!kc->nsleep)
return -ENANOSLEEP_NOTSUP;
if (get_timespec64(&t, rqtp))
return -EFAULT;
if (!timespec64_valid(&t))
return -EINVAL;
if (flags & TIMER_ABSTIME)
rmtp = NULL;
current->restart_block.nanosleep.type = rmtp ? TT_NATIVE : TT_NONE;
current->restart_block.nanosleep.rmtp = rmtp;
return kc->nsleep(which_clock, flags, &t);
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE4(clock_nanosleep, clockid_t, which_clock, int, flags,
struct compat_timespec __user *, rqtp,
struct compat_timespec __user *, rmtp)
{
const struct k_clock *kc = clockid_to_kclock(which_clock);
struct timespec64 t;
if (!kc)
return -EINVAL;
if (!kc->nsleep)
return -ENANOSLEEP_NOTSUP;
if (compat_get_timespec64(&t, rqtp))
return -EFAULT;
if (!timespec64_valid(&t))
return -EINVAL;
if (flags & TIMER_ABSTIME)
rmtp = NULL;
current->restart_block.nanosleep.type = rmtp ? TT_COMPAT : TT_NONE;
current->restart_block.nanosleep.compat_rmtp = rmtp;
return kc->nsleep(which_clock, flags, &t);
}
#endif
static const struct k_clock clock_realtime = {
.clock_getres = posix_get_hrtimer_res,
.clock_get = posix_clock_realtime_get,
.clock_set = posix_clock_realtime_set,
.clock_adj = posix_clock_realtime_adj,
.nsleep = common_nsleep,
.timer_create = common_timer_create,
.timer_set = common_timer_set,
.timer_get = common_timer_get,
.timer_del = common_timer_del,
.timer_rearm = common_hrtimer_rearm,
.timer_forward = common_hrtimer_forward,
.timer_remaining = common_hrtimer_remaining,
.timer_try_to_cancel = common_hrtimer_try_to_cancel,
.timer_arm = common_hrtimer_arm,
};
static const struct k_clock clock_monotonic = {
.clock_getres = posix_get_hrtimer_res,
.clock_get = posix_ktime_get_ts,
.nsleep = common_nsleep,
.timer_create = common_timer_create,
.timer_set = common_timer_set,
.timer_get = common_timer_get,
.timer_del = common_timer_del,
.timer_rearm = common_hrtimer_rearm,
.timer_forward = common_hrtimer_forward,
.timer_remaining = common_hrtimer_remaining,
.timer_try_to_cancel = common_hrtimer_try_to_cancel,
.timer_arm = common_hrtimer_arm,
};
static const struct k_clock clock_monotonic_raw = {
.clock_getres = posix_get_hrtimer_res,
.clock_get = posix_get_monotonic_raw,
};
static const struct k_clock clock_realtime_coarse = {
.clock_getres = posix_get_coarse_res,
.clock_get = posix_get_realtime_coarse,
};
static const struct k_clock clock_monotonic_coarse = {
.clock_getres = posix_get_coarse_res,
.clock_get = posix_get_monotonic_coarse,
};
static const struct k_clock clock_tai = {
.clock_getres = posix_get_hrtimer_res,
.clock_get = posix_get_tai,
.nsleep = common_nsleep,
.timer_create = common_timer_create,
.timer_set = common_timer_set,
.timer_get = common_timer_get,
.timer_del = common_timer_del,
.timer_rearm = common_hrtimer_rearm,
.timer_forward = common_hrtimer_forward,
.timer_remaining = common_hrtimer_remaining,
.timer_try_to_cancel = common_hrtimer_try_to_cancel,
.timer_arm = common_hrtimer_arm,
};
static const struct k_clock clock_boottime = {
.clock_getres = posix_get_hrtimer_res,
.clock_get = posix_get_boottime,
.nsleep = common_nsleep,
.timer_create = common_timer_create,
.timer_set = common_timer_set,
.timer_get = common_timer_get,
.timer_del = common_timer_del,
.timer_rearm = common_hrtimer_rearm,
.timer_forward = common_hrtimer_forward,
.timer_remaining = common_hrtimer_remaining,
.timer_try_to_cancel = common_hrtimer_try_to_cancel,
.timer_arm = common_hrtimer_arm,
};
static const struct k_clock * const posix_clocks[] = {
[CLOCK_REALTIME] = &clock_realtime,
[CLOCK_MONOTONIC] = &clock_monotonic,
[CLOCK_PROCESS_CPUTIME_ID] = &clock_process,
[CLOCK_THREAD_CPUTIME_ID] = &clock_thread,
[CLOCK_MONOTONIC_RAW] = &clock_monotonic_raw,
[CLOCK_REALTIME_COARSE] = &clock_realtime_coarse,
[CLOCK_MONOTONIC_COARSE] = &clock_monotonic_coarse,
[CLOCK_BOOTTIME] = &clock_boottime,
[CLOCK_REALTIME_ALARM] = &alarm_clock,
[CLOCK_BOOTTIME_ALARM] = &alarm_clock,
[CLOCK_TAI] = &clock_tai,
};
static const struct k_clock *clockid_to_kclock(const clockid_t id)
{
if (id < 0)
return (id & CLOCKFD_MASK) == CLOCKFD ?
&clock_posix_dynamic : &clock_posix_cpu;
if (id >= ARRAY_SIZE(posix_clocks) || !posix_clocks[id])
return NULL;
return posix_clocks[id];
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3032_0 |
crossvul-cpp_data_bad_1878_0 | /*
Conexant cx24116/cx24118 - DVBS/S2 Satellite demod/tuner driver
Copyright (C) 2006-2008 Steven Toth <stoth@hauppauge.com>
Copyright (C) 2006-2007 Georg Acher
Copyright (C) 2007-2008 Darron Broad
March 2007
Fixed some bugs.
Added diseqc support.
Added corrected signal strength support.
August 2007
Sync with legacy version.
Some clean ups.
Copyright (C) 2008 Igor Liplianin
September, 9th 2008
Fixed locking on high symbol rates (>30000).
Implement MPEG initialization parameter.
January, 17th 2009
Fill set_voltage with actually control voltage code.
Correct set tone to not affect voltage.
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/firmware.h>
#include "dvb_frontend.h"
#include "cx24116.h"
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Activates frontend debugging (default:0)");
#define dprintk(args...) \
do { \
if (debug) \
printk(KERN_INFO "cx24116: " args); \
} while (0)
#define CX24116_DEFAULT_FIRMWARE "dvb-fe-cx24116.fw"
#define CX24116_SEARCH_RANGE_KHZ 5000
/* known registers */
#define CX24116_REG_COMMAND (0x00) /* command args 0x00..0x1e */
#define CX24116_REG_EXECUTE (0x1f) /* execute command */
#define CX24116_REG_MAILBOX (0x96) /* FW or multipurpose mailbox? */
#define CX24116_REG_RESET (0x20) /* reset status > 0 */
#define CX24116_REG_SIGNAL (0x9e) /* signal low */
#define CX24116_REG_SSTATUS (0x9d) /* signal high / status */
#define CX24116_REG_QUALITY8 (0xa3)
#define CX24116_REG_QSTATUS (0xbc)
#define CX24116_REG_QUALITY0 (0xd5)
#define CX24116_REG_BER0 (0xc9)
#define CX24116_REG_BER8 (0xc8)
#define CX24116_REG_BER16 (0xc7)
#define CX24116_REG_BER24 (0xc6)
#define CX24116_REG_UCB0 (0xcb)
#define CX24116_REG_UCB8 (0xca)
#define CX24116_REG_CLKDIV (0xf3)
#define CX24116_REG_RATEDIV (0xf9)
/* configured fec (not tuned) or actual FEC (tuned) 1=1/2 2=2/3 etc */
#define CX24116_REG_FECSTATUS (0x9c)
/* FECSTATUS bits */
/* mask to determine configured fec (not tuned) or actual fec (tuned) */
#define CX24116_FEC_FECMASK (0x1f)
/* Select DVB-S demodulator, else DVB-S2 */
#define CX24116_FEC_DVBS (0x20)
#define CX24116_FEC_UNKNOWN (0x40) /* Unknown/unused */
/* Pilot mode requested when tuning else always reset when tuned */
#define CX24116_FEC_PILOT (0x80)
/* arg buffer size */
#define CX24116_ARGLEN (0x1e)
/* rolloff */
#define CX24116_ROLLOFF_020 (0x00)
#define CX24116_ROLLOFF_025 (0x01)
#define CX24116_ROLLOFF_035 (0x02)
/* pilot bit */
#define CX24116_PILOT_OFF (0x00)
#define CX24116_PILOT_ON (0x40)
/* signal status */
#define CX24116_HAS_SIGNAL (0x01)
#define CX24116_HAS_CARRIER (0x02)
#define CX24116_HAS_VITERBI (0x04)
#define CX24116_HAS_SYNCLOCK (0x08)
#define CX24116_HAS_UNKNOWN1 (0x10)
#define CX24116_HAS_UNKNOWN2 (0x20)
#define CX24116_STATUS_MASK (0x0f)
#define CX24116_SIGNAL_MASK (0xc0)
#define CX24116_DISEQC_TONEOFF (0) /* toneburst never sent */
#define CX24116_DISEQC_TONECACHE (1) /* toneburst cached */
#define CX24116_DISEQC_MESGCACHE (2) /* message cached */
/* arg offset for DiSEqC */
#define CX24116_DISEQC_BURST (1)
#define CX24116_DISEQC_ARG2_2 (2) /* unknown value=2 */
#define CX24116_DISEQC_ARG3_0 (3) /* unknown value=0 */
#define CX24116_DISEQC_ARG4_0 (4) /* unknown value=0 */
#define CX24116_DISEQC_MSGLEN (5)
#define CX24116_DISEQC_MSGOFS (6)
/* DiSEqC burst */
#define CX24116_DISEQC_MINI_A (0)
#define CX24116_DISEQC_MINI_B (1)
/* DiSEqC tone burst */
static int toneburst = 1;
module_param(toneburst, int, 0644);
MODULE_PARM_DESC(toneburst, "DiSEqC toneburst 0=OFF, 1=TONE CACHE, "\
"2=MESSAGE CACHE (default:1)");
/* SNR measurements */
static int esno_snr;
module_param(esno_snr, int, 0644);
MODULE_PARM_DESC(esno_snr, "SNR return units, 0=PERCENTAGE 0-100, "\
"1=ESNO(db * 10) (default:0)");
enum cmds {
CMD_SET_VCO = 0x10,
CMD_TUNEREQUEST = 0x11,
CMD_MPEGCONFIG = 0x13,
CMD_TUNERINIT = 0x14,
CMD_BANDWIDTH = 0x15,
CMD_GETAGC = 0x19,
CMD_LNBCONFIG = 0x20,
CMD_LNBSEND = 0x21, /* Formerly CMD_SEND_DISEQC */
CMD_LNBDCLEVEL = 0x22,
CMD_SET_TONE = 0x23,
CMD_UPDFWVERS = 0x35,
CMD_TUNERSLEEP = 0x36,
CMD_AGCCONTROL = 0x3b, /* Unknown */
};
/* The Demod/Tuner can't easily provide these, we cache them */
struct cx24116_tuning {
u32 frequency;
u32 symbol_rate;
fe_spectral_inversion_t inversion;
fe_code_rate_t fec;
fe_delivery_system_t delsys;
fe_modulation_t modulation;
fe_pilot_t pilot;
fe_rolloff_t rolloff;
/* Demod values */
u8 fec_val;
u8 fec_mask;
u8 inversion_val;
u8 pilot_val;
u8 rolloff_val;
};
/* Basic commands that are sent to the firmware */
struct cx24116_cmd {
u8 len;
u8 args[CX24116_ARGLEN];
};
struct cx24116_state {
struct i2c_adapter *i2c;
const struct cx24116_config *config;
struct dvb_frontend frontend;
struct cx24116_tuning dcur;
struct cx24116_tuning dnxt;
u8 skip_fw_load;
u8 burst;
struct cx24116_cmd dsec_cmd;
};
static int cx24116_writereg(struct cx24116_state *state, int reg, int data)
{
u8 buf[] = { reg, data };
struct i2c_msg msg = { .addr = state->config->demod_address,
.flags = 0, .buf = buf, .len = 2 };
int err;
if (debug > 1)
printk("cx24116: %s: write reg 0x%02x, value 0x%02x\n",
__func__, reg, data);
err = i2c_transfer(state->i2c, &msg, 1);
if (err != 1) {
printk(KERN_ERR "%s: writereg error(err == %i, reg == 0x%02x,"
" value == 0x%02x)\n", __func__, err, reg, data);
return -EREMOTEIO;
}
return 0;
}
/* Bulk byte writes to a single I2C address, for 32k firmware load */
static int cx24116_writeregN(struct cx24116_state *state, int reg,
const u8 *data, u16 len)
{
int ret = -EREMOTEIO;
struct i2c_msg msg;
u8 *buf;
buf = kmalloc(len + 1, GFP_KERNEL);
if (buf == NULL) {
printk("Unable to kmalloc\n");
ret = -ENOMEM;
goto error;
}
*(buf) = reg;
memcpy(buf + 1, data, len);
msg.addr = state->config->demod_address;
msg.flags = 0;
msg.buf = buf;
msg.len = len + 1;
if (debug > 1)
printk(KERN_INFO "cx24116: %s: write regN 0x%02x, len = %d\n",
__func__, reg, len);
ret = i2c_transfer(state->i2c, &msg, 1);
if (ret != 1) {
printk(KERN_ERR "%s: writereg error(err == %i, reg == 0x%02x\n",
__func__, ret, reg);
ret = -EREMOTEIO;
}
error:
kfree(buf);
return ret;
}
static int cx24116_readreg(struct cx24116_state *state, u8 reg)
{
int ret;
u8 b0[] = { reg };
u8 b1[] = { 0 };
struct i2c_msg msg[] = {
{ .addr = state->config->demod_address, .flags = 0,
.buf = b0, .len = 1 },
{ .addr = state->config->demod_address, .flags = I2C_M_RD,
.buf = b1, .len = 1 }
};
ret = i2c_transfer(state->i2c, msg, 2);
if (ret != 2) {
printk(KERN_ERR "%s: reg=0x%x (error=%d)\n",
__func__, reg, ret);
return ret;
}
if (debug > 1)
printk(KERN_INFO "cx24116: read reg 0x%02x, value 0x%02x\n",
reg, b1[0]);
return b1[0];
}
static int cx24116_set_inversion(struct cx24116_state *state,
fe_spectral_inversion_t inversion)
{
dprintk("%s(%d)\n", __func__, inversion);
switch (inversion) {
case INVERSION_OFF:
state->dnxt.inversion_val = 0x00;
break;
case INVERSION_ON:
state->dnxt.inversion_val = 0x04;
break;
case INVERSION_AUTO:
state->dnxt.inversion_val = 0x0C;
break;
default:
return -EINVAL;
}
state->dnxt.inversion = inversion;
return 0;
}
/*
* modfec (modulation and FEC)
* ===========================
*
* MOD FEC mask/val standard
* ---- -------- ----------- --------
* QPSK FEC_1_2 0x02 0x02+X DVB-S
* QPSK FEC_2_3 0x04 0x02+X DVB-S
* QPSK FEC_3_4 0x08 0x02+X DVB-S
* QPSK FEC_4_5 0x10 0x02+X DVB-S (?)
* QPSK FEC_5_6 0x20 0x02+X DVB-S
* QPSK FEC_6_7 0x40 0x02+X DVB-S
* QPSK FEC_7_8 0x80 0x02+X DVB-S
* QPSK FEC_8_9 0x01 0x02+X DVB-S (?) (NOT SUPPORTED?)
* QPSK AUTO 0xff 0x02+X DVB-S
*
* For DVB-S high byte probably represents FEC
* and low byte selects the modulator. The high
* byte is search range mask. Bit 5 may turn
* on DVB-S and remaining bits represent some
* kind of calibration (how/what i do not know).
*
* Eg.(2/3) szap "Zone Horror"
*
* mask/val = 0x04, 0x20
* status 1f | signal c3c0 | snr a333 | ber 00000098 | unc 0 | FE_HAS_LOCK
*
* mask/val = 0x04, 0x30
* status 1f | signal c3c0 | snr a333 | ber 00000000 | unc 0 | FE_HAS_LOCK
*
* After tuning FECSTATUS contains actual FEC
* in use numbered 1 through to 8 for 1/2 .. 2/3 etc
*
* NBC=NOT/NON BACKWARD COMPATIBLE WITH DVB-S (DVB-S2 only)
*
* NBC-QPSK FEC_1_2 0x00, 0x04 DVB-S2
* NBC-QPSK FEC_3_5 0x00, 0x05 DVB-S2
* NBC-QPSK FEC_2_3 0x00, 0x06 DVB-S2
* NBC-QPSK FEC_3_4 0x00, 0x07 DVB-S2
* NBC-QPSK FEC_4_5 0x00, 0x08 DVB-S2
* NBC-QPSK FEC_5_6 0x00, 0x09 DVB-S2
* NBC-QPSK FEC_8_9 0x00, 0x0a DVB-S2
* NBC-QPSK FEC_9_10 0x00, 0x0b DVB-S2
*
* NBC-8PSK FEC_3_5 0x00, 0x0c DVB-S2
* NBC-8PSK FEC_2_3 0x00, 0x0d DVB-S2
* NBC-8PSK FEC_3_4 0x00, 0x0e DVB-S2
* NBC-8PSK FEC_5_6 0x00, 0x0f DVB-S2
* NBC-8PSK FEC_8_9 0x00, 0x10 DVB-S2
* NBC-8PSK FEC_9_10 0x00, 0x11 DVB-S2
*
* For DVB-S2 low bytes selects both modulator
* and FEC. High byte is meaningless here. To
* set pilot, bit 6 (0x40) is set. When inspecting
* FECSTATUS bit 7 (0x80) represents the pilot
* selection whilst not tuned. When tuned, actual FEC
* in use is found in FECSTATUS as per above. Pilot
* value is reset.
*/
/* A table of modulation, fec and configuration bytes for the demod.
* Not all S2 mmodulation schemes are support and not all rates with
* a scheme are support. Especially, no auto detect when in S2 mode.
*/
static struct cx24116_modfec {
fe_delivery_system_t delivery_system;
fe_modulation_t modulation;
fe_code_rate_t fec;
u8 mask; /* In DVBS mode this is used to autodetect */
u8 val; /* Passed to the firmware to indicate mode selection */
} CX24116_MODFEC_MODES[] = {
/* QPSK. For unknown rates we set hardware to auto detect 0xfe 0x30 */
/*mod fec mask val */
{ SYS_DVBS, QPSK, FEC_NONE, 0xfe, 0x30 },
{ SYS_DVBS, QPSK, FEC_1_2, 0x02, 0x2e }, /* 00000010 00101110 */
{ SYS_DVBS, QPSK, FEC_2_3, 0x04, 0x2f }, /* 00000100 00101111 */
{ SYS_DVBS, QPSK, FEC_3_4, 0x08, 0x30 }, /* 00001000 00110000 */
{ SYS_DVBS, QPSK, FEC_4_5, 0xfe, 0x30 }, /* 000?0000 ? */
{ SYS_DVBS, QPSK, FEC_5_6, 0x20, 0x31 }, /* 00100000 00110001 */
{ SYS_DVBS, QPSK, FEC_6_7, 0xfe, 0x30 }, /* 0?000000 ? */
{ SYS_DVBS, QPSK, FEC_7_8, 0x80, 0x32 }, /* 10000000 00110010 */
{ SYS_DVBS, QPSK, FEC_8_9, 0xfe, 0x30 }, /* 0000000? ? */
{ SYS_DVBS, QPSK, FEC_AUTO, 0xfe, 0x30 },
/* NBC-QPSK */
{ SYS_DVBS2, QPSK, FEC_1_2, 0x00, 0x04 },
{ SYS_DVBS2, QPSK, FEC_3_5, 0x00, 0x05 },
{ SYS_DVBS2, QPSK, FEC_2_3, 0x00, 0x06 },
{ SYS_DVBS2, QPSK, FEC_3_4, 0x00, 0x07 },
{ SYS_DVBS2, QPSK, FEC_4_5, 0x00, 0x08 },
{ SYS_DVBS2, QPSK, FEC_5_6, 0x00, 0x09 },
{ SYS_DVBS2, QPSK, FEC_8_9, 0x00, 0x0a },
{ SYS_DVBS2, QPSK, FEC_9_10, 0x00, 0x0b },
/* 8PSK */
{ SYS_DVBS2, PSK_8, FEC_3_5, 0x00, 0x0c },
{ SYS_DVBS2, PSK_8, FEC_2_3, 0x00, 0x0d },
{ SYS_DVBS2, PSK_8, FEC_3_4, 0x00, 0x0e },
{ SYS_DVBS2, PSK_8, FEC_5_6, 0x00, 0x0f },
{ SYS_DVBS2, PSK_8, FEC_8_9, 0x00, 0x10 },
{ SYS_DVBS2, PSK_8, FEC_9_10, 0x00, 0x11 },
/*
* `val' can be found in the FECSTATUS register when tuning.
* FECSTATUS will give the actual FEC in use if tuning was successful.
*/
};
static int cx24116_lookup_fecmod(struct cx24116_state *state,
fe_delivery_system_t d, fe_modulation_t m, fe_code_rate_t f)
{
int i, ret = -EOPNOTSUPP;
dprintk("%s(0x%02x,0x%02x)\n", __func__, m, f);
for (i = 0; i < ARRAY_SIZE(CX24116_MODFEC_MODES); i++) {
if ((d == CX24116_MODFEC_MODES[i].delivery_system) &&
(m == CX24116_MODFEC_MODES[i].modulation) &&
(f == CX24116_MODFEC_MODES[i].fec)) {
ret = i;
break;
}
}
return ret;
}
static int cx24116_set_fec(struct cx24116_state *state,
fe_delivery_system_t delsys, fe_modulation_t mod, fe_code_rate_t fec)
{
int ret = 0;
dprintk("%s(0x%02x,0x%02x)\n", __func__, mod, fec);
ret = cx24116_lookup_fecmod(state, delsys, mod, fec);
if (ret < 0)
return ret;
state->dnxt.fec = fec;
state->dnxt.fec_val = CX24116_MODFEC_MODES[ret].val;
state->dnxt.fec_mask = CX24116_MODFEC_MODES[ret].mask;
dprintk("%s() mask/val = 0x%02x/0x%02x\n", __func__,
state->dnxt.fec_mask, state->dnxt.fec_val);
return 0;
}
static int cx24116_set_symbolrate(struct cx24116_state *state, u32 rate)
{
dprintk("%s(%d)\n", __func__, rate);
/* check if symbol rate is within limits */
if ((rate > state->frontend.ops.info.symbol_rate_max) ||
(rate < state->frontend.ops.info.symbol_rate_min)) {
dprintk("%s() unsupported symbol_rate = %d\n", __func__, rate);
return -EOPNOTSUPP;
}
state->dnxt.symbol_rate = rate;
dprintk("%s() symbol_rate = %d\n", __func__, rate);
return 0;
}
static int cx24116_load_firmware(struct dvb_frontend *fe,
const struct firmware *fw);
static int cx24116_firmware_ondemand(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
const struct firmware *fw;
int ret = 0;
dprintk("%s()\n", __func__);
if (cx24116_readreg(state, 0x20) > 0) {
if (state->skip_fw_load)
return 0;
/* Load firmware */
/* request the firmware, this will block until loaded */
printk(KERN_INFO "%s: Waiting for firmware upload (%s)...\n",
__func__, CX24116_DEFAULT_FIRMWARE);
ret = request_firmware(&fw, CX24116_DEFAULT_FIRMWARE,
state->i2c->dev.parent);
printk(KERN_INFO "%s: Waiting for firmware upload(2)...\n",
__func__);
if (ret) {
printk(KERN_ERR "%s: No firmware uploaded "
"(timeout or file not found?)\n", __func__);
return ret;
}
/* Make sure we don't recurse back through here
* during loading */
state->skip_fw_load = 1;
ret = cx24116_load_firmware(fe, fw);
if (ret)
printk(KERN_ERR "%s: Writing firmware to device failed\n",
__func__);
release_firmware(fw);
printk(KERN_INFO "%s: Firmware upload %s\n", __func__,
ret == 0 ? "complete" : "failed");
/* Ensure firmware is always loaded if required */
state->skip_fw_load = 0;
}
return ret;
}
/* Take a basic firmware command structure, format it
* and forward it for processing
*/
static int cx24116_cmd_execute(struct dvb_frontend *fe, struct cx24116_cmd *cmd)
{
struct cx24116_state *state = fe->demodulator_priv;
int i, ret;
dprintk("%s()\n", __func__);
/* Load the firmware if required */
ret = cx24116_firmware_ondemand(fe);
if (ret != 0) {
printk(KERN_ERR "%s(): Unable initialise the firmware\n",
__func__);
return ret;
}
/* Write the command */
for (i = 0; i < cmd->len ; i++) {
dprintk("%s: 0x%02x == 0x%02x\n", __func__, i, cmd->args[i]);
cx24116_writereg(state, i, cmd->args[i]);
}
/* Start execution and wait for cmd to terminate */
cx24116_writereg(state, CX24116_REG_EXECUTE, 0x01);
while (cx24116_readreg(state, CX24116_REG_EXECUTE)) {
msleep(10);
if (i++ > 64) {
/* Avoid looping forever if the firmware does
not respond */
printk(KERN_WARNING "%s() Firmware not responding\n",
__func__);
return -EREMOTEIO;
}
}
return 0;
}
static int cx24116_load_firmware(struct dvb_frontend *fe,
const struct firmware *fw)
{
struct cx24116_state *state = fe->demodulator_priv;
struct cx24116_cmd cmd;
int i, ret, len, max, remaining;
unsigned char vers[4];
dprintk("%s\n", __func__);
dprintk("Firmware is %zu bytes (%02x %02x .. %02x %02x)\n",
fw->size,
fw->data[0],
fw->data[1],
fw->data[fw->size-2],
fw->data[fw->size-1]);
/* Toggle 88x SRST pin to reset demod */
if (state->config->reset_device)
state->config->reset_device(fe);
/* Begin the firmware load process */
/* Prepare the demod, load the firmware, cleanup after load */
/* Init PLL */
cx24116_writereg(state, 0xE5, 0x00);
cx24116_writereg(state, 0xF1, 0x08);
cx24116_writereg(state, 0xF2, 0x13);
/* Start PLL */
cx24116_writereg(state, 0xe0, 0x03);
cx24116_writereg(state, 0xe0, 0x00);
/* Unknown */
cx24116_writereg(state, CX24116_REG_CLKDIV, 0x46);
cx24116_writereg(state, CX24116_REG_RATEDIV, 0x00);
/* Unknown */
cx24116_writereg(state, 0xF0, 0x03);
cx24116_writereg(state, 0xF4, 0x81);
cx24116_writereg(state, 0xF5, 0x00);
cx24116_writereg(state, 0xF6, 0x00);
/* Split firmware to the max I2C write len and write.
* Writes whole firmware as one write when i2c_wr_max is set to 0. */
if (state->config->i2c_wr_max)
max = state->config->i2c_wr_max;
else
max = INT_MAX; /* enough for 32k firmware */
for (remaining = fw->size; remaining > 0; remaining -= max - 1) {
len = remaining;
if (len > max - 1)
len = max - 1;
cx24116_writeregN(state, 0xF7, &fw->data[fw->size - remaining],
len);
}
cx24116_writereg(state, 0xF4, 0x10);
cx24116_writereg(state, 0xF0, 0x00);
cx24116_writereg(state, 0xF8, 0x06);
/* Firmware CMD 10: VCO config */
cmd.args[0x00] = CMD_SET_VCO;
cmd.args[0x01] = 0x05;
cmd.args[0x02] = 0xdc;
cmd.args[0x03] = 0xda;
cmd.args[0x04] = 0xae;
cmd.args[0x05] = 0xaa;
cmd.args[0x06] = 0x04;
cmd.args[0x07] = 0x9d;
cmd.args[0x08] = 0xfc;
cmd.args[0x09] = 0x06;
cmd.len = 0x0a;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
cx24116_writereg(state, CX24116_REG_SSTATUS, 0x00);
/* Firmware CMD 14: Tuner config */
cmd.args[0x00] = CMD_TUNERINIT;
cmd.args[0x01] = 0x00;
cmd.args[0x02] = 0x00;
cmd.len = 0x03;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
cx24116_writereg(state, 0xe5, 0x00);
/* Firmware CMD 13: MPEG config */
cmd.args[0x00] = CMD_MPEGCONFIG;
cmd.args[0x01] = 0x01;
cmd.args[0x02] = 0x75;
cmd.args[0x03] = 0x00;
if (state->config->mpg_clk_pos_pol)
cmd.args[0x04] = state->config->mpg_clk_pos_pol;
else
cmd.args[0x04] = 0x02;
cmd.args[0x05] = 0x00;
cmd.len = 0x06;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
/* Firmware CMD 35: Get firmware version */
cmd.args[0x00] = CMD_UPDFWVERS;
cmd.len = 0x02;
for (i = 0; i < 4; i++) {
cmd.args[0x01] = i;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
vers[i] = cx24116_readreg(state, CX24116_REG_MAILBOX);
}
printk(KERN_INFO "%s: FW version %i.%i.%i.%i\n", __func__,
vers[0], vers[1], vers[2], vers[3]);
return 0;
}
static int cx24116_read_status(struct dvb_frontend *fe, fe_status_t *status)
{
struct cx24116_state *state = fe->demodulator_priv;
int lock = cx24116_readreg(state, CX24116_REG_SSTATUS) &
CX24116_STATUS_MASK;
dprintk("%s: status = 0x%02x\n", __func__, lock);
*status = 0;
if (lock & CX24116_HAS_SIGNAL)
*status |= FE_HAS_SIGNAL;
if (lock & CX24116_HAS_CARRIER)
*status |= FE_HAS_CARRIER;
if (lock & CX24116_HAS_VITERBI)
*status |= FE_HAS_VITERBI;
if (lock & CX24116_HAS_SYNCLOCK)
*status |= FE_HAS_SYNC | FE_HAS_LOCK;
return 0;
}
static int cx24116_read_ber(struct dvb_frontend *fe, u32 *ber)
{
struct cx24116_state *state = fe->demodulator_priv;
dprintk("%s()\n", __func__);
*ber = (cx24116_readreg(state, CX24116_REG_BER24) << 24) |
(cx24116_readreg(state, CX24116_REG_BER16) << 16) |
(cx24116_readreg(state, CX24116_REG_BER8) << 8) |
cx24116_readreg(state, CX24116_REG_BER0);
return 0;
}
/* TODO Determine function and scale appropriately */
static int cx24116_read_signal_strength(struct dvb_frontend *fe,
u16 *signal_strength)
{
struct cx24116_state *state = fe->demodulator_priv;
struct cx24116_cmd cmd;
int ret;
u16 sig_reading;
dprintk("%s()\n", __func__);
/* Firmware CMD 19: Get AGC */
cmd.args[0x00] = CMD_GETAGC;
cmd.len = 0x01;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
sig_reading =
(cx24116_readreg(state,
CX24116_REG_SSTATUS) & CX24116_SIGNAL_MASK) |
(cx24116_readreg(state, CX24116_REG_SIGNAL) << 6);
*signal_strength = 0 - sig_reading;
dprintk("%s: raw / cooked = 0x%04x / 0x%04x\n",
__func__, sig_reading, *signal_strength);
return 0;
}
/* SNR (0..100)% = (sig & 0xf0) * 10 + (sig & 0x0f) * 10 / 16 */
static int cx24116_read_snr_pct(struct dvb_frontend *fe, u16 *snr)
{
struct cx24116_state *state = fe->demodulator_priv;
u8 snr_reading;
static const u32 snr_tab[] = { /* 10 x Table (rounded up) */
0x00000, 0x0199A, 0x03333, 0x04ccD, 0x06667,
0x08000, 0x0999A, 0x0b333, 0x0cccD, 0x0e667,
0x10000, 0x1199A, 0x13333, 0x14ccD, 0x16667,
0x18000 };
dprintk("%s()\n", __func__);
snr_reading = cx24116_readreg(state, CX24116_REG_QUALITY0);
if (snr_reading >= 0xa0 /* 100% */)
*snr = 0xffff;
else
*snr = snr_tab[(snr_reading & 0xf0) >> 4] +
(snr_tab[(snr_reading & 0x0f)] >> 4);
dprintk("%s: raw / cooked = 0x%02x / 0x%04x\n", __func__,
snr_reading, *snr);
return 0;
}
/* The reelbox patches show the value in the registers represents
* ESNO, from 0->30db (values 0->300). We provide this value by
* default.
*/
static int cx24116_read_snr_esno(struct dvb_frontend *fe, u16 *snr)
{
struct cx24116_state *state = fe->demodulator_priv;
dprintk("%s()\n", __func__);
*snr = cx24116_readreg(state, CX24116_REG_QUALITY8) << 8 |
cx24116_readreg(state, CX24116_REG_QUALITY0);
dprintk("%s: raw 0x%04x\n", __func__, *snr);
return 0;
}
static int cx24116_read_snr(struct dvb_frontend *fe, u16 *snr)
{
if (esno_snr == 1)
return cx24116_read_snr_esno(fe, snr);
else
return cx24116_read_snr_pct(fe, snr);
}
static int cx24116_read_ucblocks(struct dvb_frontend *fe, u32 *ucblocks)
{
struct cx24116_state *state = fe->demodulator_priv;
dprintk("%s()\n", __func__);
*ucblocks = (cx24116_readreg(state, CX24116_REG_UCB8) << 8) |
cx24116_readreg(state, CX24116_REG_UCB0);
return 0;
}
/* Overwrite the current tuning params, we are about to tune */
static void cx24116_clone_params(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
state->dcur = state->dnxt;
}
/* Wait for LNB */
static int cx24116_wait_for_lnb(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
int i;
dprintk("%s() qstatus = 0x%02x\n", __func__,
cx24116_readreg(state, CX24116_REG_QSTATUS));
/* Wait for up to 300 ms */
for (i = 0; i < 30 ; i++) {
if (cx24116_readreg(state, CX24116_REG_QSTATUS) & 0x20)
return 0;
msleep(10);
}
dprintk("%s(): LNB not ready\n", __func__);
return -ETIMEDOUT; /* -EBUSY ? */
}
static int cx24116_set_voltage(struct dvb_frontend *fe,
fe_sec_voltage_t voltage)
{
struct cx24116_cmd cmd;
int ret;
dprintk("%s: %s\n", __func__,
voltage == SEC_VOLTAGE_13 ? "SEC_VOLTAGE_13" :
voltage == SEC_VOLTAGE_18 ? "SEC_VOLTAGE_18" : "??");
/* Wait for LNB ready */
ret = cx24116_wait_for_lnb(fe);
if (ret != 0)
return ret;
/* Wait for voltage/min repeat delay */
msleep(100);
cmd.args[0x00] = CMD_LNBDCLEVEL;
cmd.args[0x01] = (voltage == SEC_VOLTAGE_18 ? 0x01 : 0x00);
cmd.len = 0x02;
/* Min delay time before DiSEqC send */
msleep(15);
return cx24116_cmd_execute(fe, &cmd);
}
static int cx24116_set_tone(struct dvb_frontend *fe,
fe_sec_tone_mode_t tone)
{
struct cx24116_cmd cmd;
int ret;
dprintk("%s(%d)\n", __func__, tone);
if ((tone != SEC_TONE_ON) && (tone != SEC_TONE_OFF)) {
printk(KERN_ERR "%s: Invalid, tone=%d\n", __func__, tone);
return -EINVAL;
}
/* Wait for LNB ready */
ret = cx24116_wait_for_lnb(fe);
if (ret != 0)
return ret;
/* Min delay time after DiSEqC send */
msleep(15); /* XXX determine is FW does this, see send_diseqc/burst */
/* Now we set the tone */
cmd.args[0x00] = CMD_SET_TONE;
cmd.args[0x01] = 0x00;
cmd.args[0x02] = 0x00;
switch (tone) {
case SEC_TONE_ON:
dprintk("%s: setting tone on\n", __func__);
cmd.args[0x03] = 0x01;
break;
case SEC_TONE_OFF:
dprintk("%s: setting tone off\n", __func__);
cmd.args[0x03] = 0x00;
break;
}
cmd.len = 0x04;
/* Min delay time before DiSEqC send */
msleep(15); /* XXX determine is FW does this, see send_diseqc/burst */
return cx24116_cmd_execute(fe, &cmd);
}
/* Initialise DiSEqC */
static int cx24116_diseqc_init(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
struct cx24116_cmd cmd;
int ret;
/* Firmware CMD 20: LNB/DiSEqC config */
cmd.args[0x00] = CMD_LNBCONFIG;
cmd.args[0x01] = 0x00;
cmd.args[0x02] = 0x10;
cmd.args[0x03] = 0x00;
cmd.args[0x04] = 0x8f;
cmd.args[0x05] = 0x28;
cmd.args[0x06] = (toneburst == CX24116_DISEQC_TONEOFF) ? 0x00 : 0x01;
cmd.args[0x07] = 0x01;
cmd.len = 0x08;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
/* Prepare a DiSEqC command */
state->dsec_cmd.args[0x00] = CMD_LNBSEND;
/* DiSEqC burst */
state->dsec_cmd.args[CX24116_DISEQC_BURST] = CX24116_DISEQC_MINI_A;
/* Unknown */
state->dsec_cmd.args[CX24116_DISEQC_ARG2_2] = 0x02;
state->dsec_cmd.args[CX24116_DISEQC_ARG3_0] = 0x00;
/* Continuation flag? */
state->dsec_cmd.args[CX24116_DISEQC_ARG4_0] = 0x00;
/* DiSEqC message length */
state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = 0x00;
/* Command length */
state->dsec_cmd.len = CX24116_DISEQC_MSGOFS;
return 0;
}
/* Send DiSEqC message with derived burst (hack) || previous burst */
static int cx24116_send_diseqc_msg(struct dvb_frontend *fe,
struct dvb_diseqc_master_cmd *d)
{
struct cx24116_state *state = fe->demodulator_priv;
int i, ret;
/* Dump DiSEqC message */
if (debug) {
printk(KERN_INFO "cx24116: %s(", __func__);
for (i = 0 ; i < d->msg_len ;) {
printk(KERN_INFO "0x%02x", d->msg[i]);
if (++i < d->msg_len)
printk(KERN_INFO ", ");
}
printk(") toneburst=%d\n", toneburst);
}
/* Validate length */
if (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS))
return -EINVAL;
/* DiSEqC message */
for (i = 0; i < d->msg_len; i++)
state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i];
/* DiSEqC message length */
state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len;
/* Command length */
state->dsec_cmd.len = CX24116_DISEQC_MSGOFS +
state->dsec_cmd.args[CX24116_DISEQC_MSGLEN];
/* DiSEqC toneburst */
if (toneburst == CX24116_DISEQC_MESGCACHE)
/* Message is cached */
return 0;
else if (toneburst == CX24116_DISEQC_TONEOFF)
/* Message is sent without burst */
state->dsec_cmd.args[CX24116_DISEQC_BURST] = 0;
else if (toneburst == CX24116_DISEQC_TONECACHE) {
/*
* Message is sent with derived else cached burst
*
* WRITE PORT GROUP COMMAND 38
*
* 0/A/A: E0 10 38 F0..F3
* 1/B/B: E0 10 38 F4..F7
* 2/C/A: E0 10 38 F8..FB
* 3/D/B: E0 10 38 FC..FF
*
* databyte[3]= 8421:8421
* ABCD:WXYZ
* CLR :SET
*
* WX= PORT SELECT 0..3 (X=TONEBURST)
* Y = VOLTAGE (0=13V, 1=18V)
* Z = BAND (0=LOW, 1=HIGH(22K))
*/
if (d->msg_len >= 4 && d->msg[2] == 0x38)
state->dsec_cmd.args[CX24116_DISEQC_BURST] =
((d->msg[3] & 4) >> 2);
if (debug)
dprintk("%s burst=%d\n", __func__,
state->dsec_cmd.args[CX24116_DISEQC_BURST]);
}
/* Wait for LNB ready */
ret = cx24116_wait_for_lnb(fe);
if (ret != 0)
return ret;
/* Wait for voltage/min repeat delay */
msleep(100);
/* Command */
ret = cx24116_cmd_execute(fe, &state->dsec_cmd);
if (ret != 0)
return ret;
/*
* Wait for send
*
* Eutelsat spec:
* >15ms delay + (XXX determine if FW does this, see set_tone)
* 13.5ms per byte +
* >15ms delay +
* 12.5ms burst +
* >15ms delay (XXX determine if FW does this, see set_tone)
*/
msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) +
((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60));
return 0;
}
/* Send DiSEqC burst */
static int cx24116_diseqc_send_burst(struct dvb_frontend *fe,
fe_sec_mini_cmd_t burst)
{
struct cx24116_state *state = fe->demodulator_priv;
int ret;
dprintk("%s(%d) toneburst=%d\n", __func__, burst, toneburst);
/* DiSEqC burst */
if (burst == SEC_MINI_A)
state->dsec_cmd.args[CX24116_DISEQC_BURST] =
CX24116_DISEQC_MINI_A;
else if (burst == SEC_MINI_B)
state->dsec_cmd.args[CX24116_DISEQC_BURST] =
CX24116_DISEQC_MINI_B;
else
return -EINVAL;
/* DiSEqC toneburst */
if (toneburst != CX24116_DISEQC_MESGCACHE)
/* Burst is cached */
return 0;
/* Burst is to be sent with cached message */
/* Wait for LNB ready */
ret = cx24116_wait_for_lnb(fe);
if (ret != 0)
return ret;
/* Wait for voltage/min repeat delay */
msleep(100);
/* Command */
ret = cx24116_cmd_execute(fe, &state->dsec_cmd);
if (ret != 0)
return ret;
/*
* Wait for send
*
* Eutelsat spec:
* >15ms delay + (XXX determine if FW does this, see set_tone)
* 13.5ms per byte +
* >15ms delay +
* 12.5ms burst +
* >15ms delay (XXX determine if FW does this, see set_tone)
*/
msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) + 60);
return 0;
}
static void cx24116_release(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
dprintk("%s\n", __func__);
kfree(state);
}
static struct dvb_frontend_ops cx24116_ops;
struct dvb_frontend *cx24116_attach(const struct cx24116_config *config,
struct i2c_adapter *i2c)
{
struct cx24116_state *state = NULL;
int ret;
dprintk("%s\n", __func__);
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct cx24116_state), GFP_KERNEL);
if (state == NULL)
goto error1;
state->config = config;
state->i2c = i2c;
/* check if the demod is present */
ret = (cx24116_readreg(state, 0xFF) << 8) |
cx24116_readreg(state, 0xFE);
if (ret != 0x0501) {
printk(KERN_INFO "Invalid probe, probably not a CX24116 device\n");
goto error2;
}
/* create dvb_frontend */
memcpy(&state->frontend.ops, &cx24116_ops,
sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
return &state->frontend;
error2: kfree(state);
error1: return NULL;
}
EXPORT_SYMBOL(cx24116_attach);
/*
* Initialise or wake up device
*
* Power config will reset and load initial firmware if required
*/
static int cx24116_initfe(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
struct cx24116_cmd cmd;
int ret;
dprintk("%s()\n", __func__);
/* Power on */
cx24116_writereg(state, 0xe0, 0);
cx24116_writereg(state, 0xe1, 0);
cx24116_writereg(state, 0xea, 0);
/* Firmware CMD 36: Power config */
cmd.args[0x00] = CMD_TUNERSLEEP;
cmd.args[0x01] = 0;
cmd.len = 0x02;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
ret = cx24116_diseqc_init(fe);
if (ret != 0)
return ret;
/* HVR-4000 needs this */
return cx24116_set_voltage(fe, SEC_VOLTAGE_13);
}
/*
* Put device to sleep
*/
static int cx24116_sleep(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
struct cx24116_cmd cmd;
int ret;
dprintk("%s()\n", __func__);
/* Firmware CMD 36: Power config */
cmd.args[0x00] = CMD_TUNERSLEEP;
cmd.args[0x01] = 1;
cmd.len = 0x02;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
/* Power off (Shutdown clocks) */
cx24116_writereg(state, 0xea, 0xff);
cx24116_writereg(state, 0xe1, 1);
cx24116_writereg(state, 0xe0, 1);
return 0;
}
/* dvb-core told us to tune, the tv property cache will be complete,
* it's safe for is to pull values and use them for tuning purposes.
*/
static int cx24116_set_frontend(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
struct cx24116_cmd cmd;
fe_status_t tunerstat;
int i, status, ret, retune = 1;
dprintk("%s()\n", __func__);
switch (c->delivery_system) {
case SYS_DVBS:
dprintk("%s: DVB-S delivery system selected\n", __func__);
/* Only QPSK is supported for DVB-S */
if (c->modulation != QPSK) {
dprintk("%s: unsupported modulation selected (%d)\n",
__func__, c->modulation);
return -EOPNOTSUPP;
}
/* Pilot doesn't exist in DVB-S, turn bit off */
state->dnxt.pilot_val = CX24116_PILOT_OFF;
/* DVB-S only supports 0.35 */
if (c->rolloff != ROLLOFF_35) {
dprintk("%s: unsupported rolloff selected (%d)\n",
__func__, c->rolloff);
return -EOPNOTSUPP;
}
state->dnxt.rolloff_val = CX24116_ROLLOFF_035;
break;
case SYS_DVBS2:
dprintk("%s: DVB-S2 delivery system selected\n", __func__);
/*
* NBC 8PSK/QPSK with DVB-S is supported for DVB-S2,
* but not hardware auto detection
*/
if (c->modulation != PSK_8 && c->modulation != QPSK) {
dprintk("%s: unsupported modulation selected (%d)\n",
__func__, c->modulation);
return -EOPNOTSUPP;
}
switch (c->pilot) {
case PILOT_AUTO: /* Not supported but emulated */
state->dnxt.pilot_val = (c->modulation == QPSK)
? CX24116_PILOT_OFF : CX24116_PILOT_ON;
retune++;
break;
case PILOT_OFF:
state->dnxt.pilot_val = CX24116_PILOT_OFF;
break;
case PILOT_ON:
state->dnxt.pilot_val = CX24116_PILOT_ON;
break;
default:
dprintk("%s: unsupported pilot mode selected (%d)\n",
__func__, c->pilot);
return -EOPNOTSUPP;
}
switch (c->rolloff) {
case ROLLOFF_20:
state->dnxt.rolloff_val = CX24116_ROLLOFF_020;
break;
case ROLLOFF_25:
state->dnxt.rolloff_val = CX24116_ROLLOFF_025;
break;
case ROLLOFF_35:
state->dnxt.rolloff_val = CX24116_ROLLOFF_035;
break;
case ROLLOFF_AUTO: /* Rolloff must be explicit */
default:
dprintk("%s: unsupported rolloff selected (%d)\n",
__func__, c->rolloff);
return -EOPNOTSUPP;
}
break;
default:
dprintk("%s: unsupported delivery system selected (%d)\n",
__func__, c->delivery_system);
return -EOPNOTSUPP;
}
state->dnxt.delsys = c->delivery_system;
state->dnxt.modulation = c->modulation;
state->dnxt.frequency = c->frequency;
state->dnxt.pilot = c->pilot;
state->dnxt.rolloff = c->rolloff;
ret = cx24116_set_inversion(state, c->inversion);
if (ret != 0)
return ret;
/* FEC_NONE/AUTO for DVB-S2 is not supported and detected here */
ret = cx24116_set_fec(state, c->delivery_system, c->modulation, c->fec_inner);
if (ret != 0)
return ret;
ret = cx24116_set_symbolrate(state, c->symbol_rate);
if (ret != 0)
return ret;
/* discard the 'current' tuning parameters and prepare to tune */
cx24116_clone_params(fe);
dprintk("%s: delsys = %d\n", __func__, state->dcur.delsys);
dprintk("%s: modulation = %d\n", __func__, state->dcur.modulation);
dprintk("%s: frequency = %d\n", __func__, state->dcur.frequency);
dprintk("%s: pilot = %d (val = 0x%02x)\n", __func__,
state->dcur.pilot, state->dcur.pilot_val);
dprintk("%s: retune = %d\n", __func__, retune);
dprintk("%s: rolloff = %d (val = 0x%02x)\n", __func__,
state->dcur.rolloff, state->dcur.rolloff_val);
dprintk("%s: symbol_rate = %d\n", __func__, state->dcur.symbol_rate);
dprintk("%s: FEC = %d (mask/val = 0x%02x/0x%02x)\n", __func__,
state->dcur.fec, state->dcur.fec_mask, state->dcur.fec_val);
dprintk("%s: Inversion = %d (val = 0x%02x)\n", __func__,
state->dcur.inversion, state->dcur.inversion_val);
/* This is also done in advise/acquire on HVR4000 but not on LITE */
if (state->config->set_ts_params)
state->config->set_ts_params(fe, 0);
/* Set/Reset B/W */
cmd.args[0x00] = CMD_BANDWIDTH;
cmd.args[0x01] = 0x01;
cmd.len = 0x02;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
/* Prepare a tune request */
cmd.args[0x00] = CMD_TUNEREQUEST;
/* Frequency */
cmd.args[0x01] = (state->dcur.frequency & 0xff0000) >> 16;
cmd.args[0x02] = (state->dcur.frequency & 0x00ff00) >> 8;
cmd.args[0x03] = (state->dcur.frequency & 0x0000ff);
/* Symbol Rate */
cmd.args[0x04] = ((state->dcur.symbol_rate / 1000) & 0xff00) >> 8;
cmd.args[0x05] = ((state->dcur.symbol_rate / 1000) & 0x00ff);
/* Automatic Inversion */
cmd.args[0x06] = state->dcur.inversion_val;
/* Modulation / FEC / Pilot */
cmd.args[0x07] = state->dcur.fec_val | state->dcur.pilot_val;
cmd.args[0x08] = CX24116_SEARCH_RANGE_KHZ >> 8;
cmd.args[0x09] = CX24116_SEARCH_RANGE_KHZ & 0xff;
cmd.args[0x0a] = 0x00;
cmd.args[0x0b] = 0x00;
cmd.args[0x0c] = state->dcur.rolloff_val;
cmd.args[0x0d] = state->dcur.fec_mask;
if (state->dcur.symbol_rate > 30000000) {
cmd.args[0x0e] = 0x04;
cmd.args[0x0f] = 0x00;
cmd.args[0x10] = 0x01;
cmd.args[0x11] = 0x77;
cmd.args[0x12] = 0x36;
cx24116_writereg(state, CX24116_REG_CLKDIV, 0x44);
cx24116_writereg(state, CX24116_REG_RATEDIV, 0x01);
} else {
cmd.args[0x0e] = 0x06;
cmd.args[0x0f] = 0x00;
cmd.args[0x10] = 0x00;
cmd.args[0x11] = 0xFA;
cmd.args[0x12] = 0x24;
cx24116_writereg(state, CX24116_REG_CLKDIV, 0x46);
cx24116_writereg(state, CX24116_REG_RATEDIV, 0x00);
}
cmd.len = 0x13;
/* We need to support pilot and non-pilot tuning in the
* driver automatically. This is a workaround for because
* the demod does not support autodetect.
*/
do {
/* Reset status register */
status = cx24116_readreg(state, CX24116_REG_SSTATUS)
& CX24116_SIGNAL_MASK;
cx24116_writereg(state, CX24116_REG_SSTATUS, status);
/* Tune */
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
break;
/*
* Wait for up to 500 ms before retrying
*
* If we are able to tune then generally it occurs within 100ms.
* If it takes longer, try a different toneburst setting.
*/
for (i = 0; i < 50 ; i++) {
cx24116_read_status(fe, &tunerstat);
status = tunerstat & (FE_HAS_SIGNAL | FE_HAS_SYNC);
if (status == (FE_HAS_SIGNAL | FE_HAS_SYNC)) {
dprintk("%s: Tuned\n", __func__);
goto tuned;
}
msleep(10);
}
dprintk("%s: Not tuned\n", __func__);
/* Toggle pilot bit when in auto-pilot */
if (state->dcur.pilot == PILOT_AUTO)
cmd.args[0x07] ^= CX24116_PILOT_ON;
} while (--retune);
tuned: /* Set/Reset B/W */
cmd.args[0x00] = CMD_BANDWIDTH;
cmd.args[0x01] = 0x00;
cmd.len = 0x02;
return cx24116_cmd_execute(fe, &cmd);
}
static int cx24116_tune(struct dvb_frontend *fe, bool re_tune,
unsigned int mode_flags, unsigned int *delay, fe_status_t *status)
{
/*
* It is safe to discard "params" here, as the DVB core will sync
* fe->dtv_property_cache with fepriv->parameters_in, where the
* DVBv3 params are stored. The only practical usage for it indicate
* that re-tuning is needed, e. g. (fepriv->state & FESTATE_RETUNE) is
* true.
*/
*delay = HZ / 5;
if (re_tune) {
int ret = cx24116_set_frontend(fe);
if (ret)
return ret;
}
return cx24116_read_status(fe, status);
}
static int cx24116_get_algo(struct dvb_frontend *fe)
{
return DVBFE_ALGO_HW;
}
static struct dvb_frontend_ops cx24116_ops = {
.delsys = { SYS_DVBS, SYS_DVBS2 },
.info = {
.name = "Conexant CX24116/CX24118",
.frequency_min = 950000,
.frequency_max = 2150000,
.frequency_stepsize = 1011, /* kHz for QPSK frontends */
.frequency_tolerance = 5000,
.symbol_rate_min = 1000000,
.symbol_rate_max = 45000000,
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_4_5 | FE_CAN_FEC_5_6 | FE_CAN_FEC_6_7 |
FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
FE_CAN_2G_MODULATION |
FE_CAN_QPSK | FE_CAN_RECOVER
},
.release = cx24116_release,
.init = cx24116_initfe,
.sleep = cx24116_sleep,
.read_status = cx24116_read_status,
.read_ber = cx24116_read_ber,
.read_signal_strength = cx24116_read_signal_strength,
.read_snr = cx24116_read_snr,
.read_ucblocks = cx24116_read_ucblocks,
.set_tone = cx24116_set_tone,
.set_voltage = cx24116_set_voltage,
.diseqc_send_master_cmd = cx24116_send_diseqc_msg,
.diseqc_send_burst = cx24116_diseqc_send_burst,
.get_frontend_algo = cx24116_get_algo,
.tune = cx24116_tune,
.set_frontend = cx24116_set_frontend,
};
MODULE_DESCRIPTION("DVB Frontend module for Conexant cx24116/cx24118 hardware");
MODULE_AUTHOR("Steven Toth");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1878_0 |
crossvul-cpp_data_good_2701_1 | /*
* Copyright (C) 2002 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/* \summary: IPv6 mobility printer */
/* RFC 3775 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip6.h"
static const char tstr[] = "[|MOBILITY]";
/* Mobility header */
struct ip6_mobility {
uint8_t ip6m_pproto; /* following payload protocol (for PG) */
uint8_t ip6m_len; /* length in units of 8 octets */
uint8_t ip6m_type; /* message type */
uint8_t reserved; /* reserved */
uint16_t ip6m_cksum; /* sum of IPv6 pseudo-header and MH */
union {
uint16_t ip6m_un_data16[1]; /* type-specific field */
uint8_t ip6m_un_data8[2]; /* type-specific field */
} ip6m_dataun;
};
#define ip6m_data16 ip6m_dataun.ip6m_un_data16
#define ip6m_data8 ip6m_dataun.ip6m_un_data8
#define IP6M_MINLEN 8
/* http://www.iana.org/assignments/mobility-parameters/mobility-parameters.xhtml */
/* message type */
#define IP6M_BINDING_REQUEST 0 /* Binding Refresh Request */
#define IP6M_HOME_TEST_INIT 1 /* Home Test Init */
#define IP6M_CAREOF_TEST_INIT 2 /* Care-of Test Init */
#define IP6M_HOME_TEST 3 /* Home Test */
#define IP6M_CAREOF_TEST 4 /* Care-of Test */
#define IP6M_BINDING_UPDATE 5 /* Binding Update */
#define IP6M_BINDING_ACK 6 /* Binding Acknowledgement */
#define IP6M_BINDING_ERROR 7 /* Binding Error */
#define IP6M_MAX 7
static const struct tok ip6m_str[] = {
{ IP6M_BINDING_REQUEST, "BRR" },
{ IP6M_HOME_TEST_INIT, "HoTI" },
{ IP6M_CAREOF_TEST_INIT, "CoTI" },
{ IP6M_HOME_TEST, "HoT" },
{ IP6M_CAREOF_TEST, "CoT" },
{ IP6M_BINDING_UPDATE, "BU" },
{ IP6M_BINDING_ACK, "BA" },
{ IP6M_BINDING_ERROR, "BE" },
{ 0, NULL }
};
static const unsigned ip6m_hdrlen[IP6M_MAX + 1] = {
IP6M_MINLEN, /* IP6M_BINDING_REQUEST */
IP6M_MINLEN + 8, /* IP6M_HOME_TEST_INIT */
IP6M_MINLEN + 8, /* IP6M_CAREOF_TEST_INIT */
IP6M_MINLEN + 16, /* IP6M_HOME_TEST */
IP6M_MINLEN + 16, /* IP6M_CAREOF_TEST */
IP6M_MINLEN + 4, /* IP6M_BINDING_UPDATE */
IP6M_MINLEN + 4, /* IP6M_BINDING_ACK */
IP6M_MINLEN + 16, /* IP6M_BINDING_ERROR */
};
/* Mobility Header Options */
#define IP6MOPT_MINLEN 2
#define IP6MOPT_PAD1 0x0 /* Pad1 */
#define IP6MOPT_PADN 0x1 /* PadN */
#define IP6MOPT_REFRESH 0x2 /* Binding Refresh Advice */
#define IP6MOPT_REFRESH_MINLEN 4
#define IP6MOPT_ALTCOA 0x3 /* Alternate Care-of Address */
#define IP6MOPT_ALTCOA_MINLEN 18
#define IP6MOPT_NONCEID 0x4 /* Nonce Indices */
#define IP6MOPT_NONCEID_MINLEN 6
#define IP6MOPT_AUTH 0x5 /* Binding Authorization Data */
#define IP6MOPT_AUTH_MINLEN 12
static int
mobility_opt_print(netdissect_options *ndo,
const u_char *bp, const unsigned len)
{
unsigned i, optlen;
for (i = 0; i < len; i += optlen) {
ND_TCHECK(bp[i]);
if (bp[i] == IP6MOPT_PAD1)
optlen = 1;
else {
if (i + 1 < len) {
ND_TCHECK(bp[i + 1]);
optlen = bp[i + 1] + 2;
}
else
goto trunc;
}
if (i + optlen > len)
goto trunc;
ND_TCHECK(bp[i + optlen]);
switch (bp[i]) {
case IP6MOPT_PAD1:
ND_PRINT((ndo, "(pad1)"));
break;
case IP6MOPT_PADN:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(padn: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(padn)"));
break;
case IP6MOPT_REFRESH:
if (len - i < IP6MOPT_REFRESH_MINLEN) {
ND_PRINT((ndo, "(refresh: trunc)"));
goto trunc;
}
/* units of 4 secs */
ND_TCHECK_16BITS(&bp[i+2]);
ND_PRINT((ndo, "(refresh: %u)",
EXTRACT_16BITS(&bp[i+2]) << 2));
break;
case IP6MOPT_ALTCOA:
if (len - i < IP6MOPT_ALTCOA_MINLEN) {
ND_PRINT((ndo, "(altcoa: trunc)"));
goto trunc;
}
ND_TCHECK_128BITS(&bp[i+2]);
ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2])));
break;
case IP6MOPT_NONCEID:
if (len - i < IP6MOPT_NONCEID_MINLEN) {
ND_PRINT((ndo, "(ni: trunc)"));
goto trunc;
}
ND_TCHECK_16BITS(&bp[i+2]);
ND_TCHECK_16BITS(&bp[i+4]);
ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)",
EXTRACT_16BITS(&bp[i+2]),
EXTRACT_16BITS(&bp[i+4])));
break;
case IP6MOPT_AUTH:
if (len - i < IP6MOPT_AUTH_MINLEN) {
ND_PRINT((ndo, "(auth: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(auth)"));
break;
default:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i]));
goto trunc;
}
ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1]));
break;
}
}
return 0;
trunc:
return 1;
}
/*
* Mobility Header
*/
int
mobility_print(netdissect_options *ndo,
const u_char *bp, const u_char *bp2 _U_)
{
const struct ip6_mobility *mh;
const u_char *ep;
unsigned mhlen, hlen;
uint8_t type;
mh = (const struct ip6_mobility *)bp;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if (!ND_TTEST(mh->ip6m_len)) {
/*
* There's not enough captured data to include the
* mobility header length.
*
* Our caller expects us to return the length, however,
* so return a value that will run to the end of the
* captured data.
*
* XXX - "ip6_print()" doesn't do anything with the
* returned length, however, as it breaks out of the
* header-processing loop.
*/
mhlen = ep - bp;
goto trunc;
}
mhlen = (mh->ip6m_len + 1) << 3;
/* XXX ip6m_cksum */
ND_TCHECK(mh->ip6m_type);
type = mh->ip6m_type;
if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) {
ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type));
goto trunc;
}
ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type)));
switch (type) {
case IP6M_BINDING_REQUEST:
hlen = IP6M_MINLEN;
break;
case IP6M_HOME_TEST_INIT:
case IP6M_CAREOF_TEST_INIT:
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_TCHECK_32BITS(&bp[hlen + 4]);
ND_PRINT((ndo, " %s Init Cookie=%08x:%08x",
type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
break;
case IP6M_HOME_TEST:
case IP6M_CAREOF_TEST:
ND_TCHECK(mh->ip6m_data16[0]);
ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0])));
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_TCHECK_32BITS(&bp[hlen + 4]);
ND_PRINT((ndo, " %s Init Cookie=%08x:%08x",
type == IP6M_HOME_TEST ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
if (ndo->ndo_vflag) {
ND_TCHECK_32BITS(&bp[hlen + 4]);
ND_PRINT((ndo, " %s Keygen Token=%08x:%08x",
type == IP6M_HOME_TEST ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
break;
case IP6M_BINDING_UPDATE:
ND_TCHECK(mh->ip6m_data16[0]);
ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0])));
hlen = IP6M_MINLEN;
ND_TCHECK_16BITS(&bp[hlen]);
if (bp[hlen] & 0xf0) {
ND_PRINT((ndo, " "));
if (bp[hlen] & 0x80)
ND_PRINT((ndo, "A"));
if (bp[hlen] & 0x40)
ND_PRINT((ndo, "H"));
if (bp[hlen] & 0x20)
ND_PRINT((ndo, "L"));
if (bp[hlen] & 0x10)
ND_PRINT((ndo, "K"));
}
/* Reserved (4bits) */
hlen += 1;
/* Reserved (8bits) */
hlen += 1;
ND_TCHECK_16BITS(&bp[hlen]);
/* units of 4 secs */
ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2));
hlen += 2;
break;
case IP6M_BINDING_ACK:
ND_TCHECK(mh->ip6m_data8[0]);
ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0]));
ND_TCHECK(mh->ip6m_data8[1]);
if (mh->ip6m_data8[1] & 0x80)
ND_PRINT((ndo, " K"));
/* Reserved (7bits) */
hlen = IP6M_MINLEN;
ND_TCHECK_16BITS(&bp[hlen]);
ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen])));
hlen += 2;
ND_TCHECK_16BITS(&bp[hlen]);
/* units of 4 secs */
ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2));
hlen += 2;
break;
case IP6M_BINDING_ERROR:
ND_TCHECK(mh->ip6m_data8[0]);
ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0]));
/* Reserved */
hlen = IP6M_MINLEN;
ND_TCHECK2(bp[hlen], 16);
ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen])));
hlen += 16;
break;
default:
ND_PRINT((ndo, " len=%u", mh->ip6m_len));
return(mhlen);
break;
}
if (ndo->ndo_vflag)
if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen))
goto trunc;
return(mhlen);
trunc:
ND_PRINT((ndo, "%s", tstr));
return(-1);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2701_1 |
crossvul-cpp_data_good_502_0 | /* radare - LGPL - Copyright 2010-2018 - nibble, pancake */
#include <stdio.h>
#include <r_types.h>
#include <r_util.h>
#include "dyldcache.h"
static int r_bin_dyldcache_init(struct r_bin_dyldcache_obj_t* bin) {
int len = r_buf_fread_at (bin->b, 0, (ut8*)&bin->hdr, "16c4i7l", 1);
if (len == -1) {
perror ("read (cache_header)");
return false;
}
bin->nlibs = bin->hdr.numlibs;
return true;
}
static int r_bin_dyldcache_apply_patch (struct r_buf_t* buf, ut32 data, ut64 offset) {
return r_buf_write_at (buf, offset, (ut8*)&data, sizeof (data));
}
#define NZ_OFFSET(x) if((x) > 0) r_bin_dyldcache_apply_patch (dbuf, (x) - linkedit_offset, (ut64)((size_t)&(x) - (size_t)data))
// make it public in util/buf.c ?
static ut64 r_buf_read64le (RBuffer *buf, ut64 off) {
ut8 data[8] = {0};
r_buf_read_at (buf, off, data, 8);
return r_read_le64 (data);
}
static char *r_buf_read_string (RBuffer *buf, ut64 addr, int len) {
ut8 *data = malloc (len);
if (data) {
r_buf_read_at (buf, addr, data, len);
data[len-1] = 0;
return data;
}
return NULL;
}
/* TODO: Needs more testing and ERROR HANDLING */
struct r_bin_dyldcache_lib_t *r_bin_dyldcache_extract(struct r_bin_dyldcache_obj_t* bin, int idx, int *nlib) {
ut64 liboff, linkedit_offset;
ut64 dyld_vmbase;
ut32 addend = 0;
struct r_bin_dyldcache_lib_t *ret = NULL;
struct dyld_cache_image_info* image_infos = NULL;
struct mach_header *mh;
ut8 *data, *cmdptr;
int cmd, libsz = 0;
RBuffer* dbuf;
char *libname;
if (!bin) {
return NULL;
}
if (bin->size < 1) {
eprintf ("Empty file? (%s)\n", bin->file? bin->file: "(null)");
return NULL;
}
if (bin->nlibs < 0 || idx < 0 || idx >= bin->nlibs) {
return NULL;
}
*nlib = bin->nlibs;
ret = R_NEW0 (struct r_bin_dyldcache_lib_t);
if (!ret) {
return NULL;
}
if (bin->hdr.startaddr > bin->size) {
eprintf ("corrupted dyldcache");
free (ret);
return NULL;
}
if (bin->hdr.startaddr > bin->size || bin->hdr.baseaddroff > bin->size) {
eprintf ("corrupted dyldcache");
free (ret);
return NULL;
}
int sz = bin->nlibs * sizeof (struct dyld_cache_image_info);
image_infos = malloc (sz); //(struct dyld_cache_image_info*) (bin->b->buf + bin->hdr.startaddr);
if (!image_infos) {
free (ret);
return NULL;
}
r_buf_read_at (bin->b, bin->hdr.startaddr, (ut8*)image_infos, sz);
dyld_vmbase = r_buf_read64le (bin->b, bin->hdr.baseaddroff);
liboff = image_infos[idx].address - dyld_vmbase;
if (liboff > bin->size) {
eprintf ("Corrupted file\n");
free (ret);
return NULL;
}
ret->offset = liboff;
int pfo = image_infos[idx].pathFileOffset;
if (pfo < 0 || pfo > bin->size) {
eprintf ("corrupted file: pathFileOffset > bin->size (%d)\n", pfo);
free (ret);
return NULL;
}
libname = r_buf_read_string (bin->b, pfo, 64);
/* Locate lib hdr in cache */
data = bin->b->buf + liboff;
mh = (struct mach_header *)data;
/* Check it is mach-o */
if (mh->magic != MH_MAGIC && mh->magic != MH_MAGIC_64) {
if (mh->magic == 0xbebafeca) { //FAT binary
eprintf ("FAT Binary\n");
}
eprintf ("Not mach-o\n");
free (ret);
return NULL;
}
/* Write mach-o hdr */
if (!(dbuf = r_buf_new ())) {
eprintf ("new (dbuf)\n");
free (ret);
return NULL;
}
addend = mh->magic == MH_MAGIC? sizeof (struct mach_header) : sizeof (struct mach_header_64);
r_buf_set_bytes (dbuf, data, addend);
cmdptr = data + addend;
/* Write load commands */
for (cmd = 0; cmd < mh->ncmds; cmd++) {
struct load_command *lc = (struct load_command *)cmdptr;
r_buf_append_bytes (dbuf, (ut8*)lc, lc->cmdsize);
cmdptr += lc->cmdsize;
}
cmdptr = data + addend;
/* Write segments */
for (cmd = linkedit_offset = 0; cmd < mh->ncmds; cmd++) {
struct load_command *lc = (struct load_command *)cmdptr;
cmdptr += lc->cmdsize;
switch (lc->cmd) {
case LC_SEGMENT:
{
/* Write segment and patch offset */
struct segment_command *seg = (struct segment_command *)lc;
int t = seg->filesize;
if (seg->fileoff + seg->filesize > bin->size || seg->fileoff > bin->size) {
eprintf ("malformed dyldcache\n");
free (ret);
r_buf_free (dbuf);
return NULL;
}
r_buf_append_bytes (dbuf, bin->b->buf+seg->fileoff, t);
r_bin_dyldcache_apply_patch (dbuf, dbuf->length, (ut64)((size_t)&seg->fileoff - (size_t)data));
/* Patch section offsets */
int sect_offset = seg->fileoff - libsz;
libsz = dbuf->length;
if (!strcmp (seg->segname, "__LINKEDIT")) {
linkedit_offset = sect_offset;
}
if (seg->nsects > 0) {
struct section *sects = (struct section *)((ut8 *)seg + sizeof(struct segment_command));
int nsect;
for (nsect = 0; nsect < seg->nsects; nsect++) {
if (sects[nsect].offset > libsz) {
r_bin_dyldcache_apply_patch (dbuf, sects[nsect].offset - sect_offset,
(ut64)((size_t)§s[nsect].offset - (size_t)data));
}
}
}
}
break;
case LC_SYMTAB:
{
struct symtab_command *st = (struct symtab_command *)lc;
NZ_OFFSET (st->symoff);
NZ_OFFSET (st->stroff);
}
break;
case LC_DYSYMTAB:
{
struct dysymtab_command *st = (struct dysymtab_command *)lc;
NZ_OFFSET (st->tocoff);
NZ_OFFSET (st->modtaboff);
NZ_OFFSET (st->extrefsymoff);
NZ_OFFSET (st->indirectsymoff);
NZ_OFFSET (st->extreloff);
NZ_OFFSET (st->locreloff);
}
break;
case LC_DYLD_INFO:
case LC_DYLD_INFO_ONLY:
{
struct dyld_info_command *st = (struct dyld_info_command *)lc;
NZ_OFFSET (st->rebase_off);
NZ_OFFSET (st->bind_off);
NZ_OFFSET (st->weak_bind_off);
NZ_OFFSET (st->lazy_bind_off);
NZ_OFFSET (st->export_off);
}
break;
}
}
/* Fill r_bin_dyldcache_lib_t ret */
ret->b = dbuf;
strncpy (ret->path, libname, sizeof (ret->path) - 1);
ret->size = libsz;
return ret;
}
void* r_bin_dyldcache_free(struct r_bin_dyldcache_obj_t* bin) {
if (!bin) {
return NULL;
}
r_buf_free (bin->b);
free (bin);
return NULL;
}
void r_bin_dydlcache_get_libname(struct r_bin_dyldcache_lib_t *lib, char **libname) {
char *cur = lib->path;
char *res = lib->path;
int path_length = strlen (lib->path);
while (cur < cur + path_length - 1) {
cur = strchr (cur, '/');
if (!cur) {
break;
}
cur++;
res = cur;
}
*libname = res;
}
struct r_bin_dyldcache_obj_t* r_bin_dyldcache_new(const char* file) {
struct r_bin_dyldcache_obj_t *bin;
ut8 *buf;
if (!(bin = R_NEW0 (struct r_bin_dyldcache_obj_t))) {
return NULL;
}
bin->file = file;
if (!(buf = (ut8*)r_file_slurp (file, &bin->size))) {
return r_bin_dyldcache_free (bin);
}
bin->b = r_buf_new ();
if (!r_buf_set_bytes (bin->b, buf, bin->size)) {
free (buf);
return r_bin_dyldcache_free (bin);
}
free (buf);
if (!r_bin_dyldcache_init (bin)) {
return r_bin_dyldcache_free (bin);
}
return bin;
}
struct r_bin_dyldcache_obj_t* r_bin_dyldcache_from_bytes_new(const ut8* buf, ut64 size) {
struct r_bin_dyldcache_obj_t *bin = R_NEW0 (struct r_bin_dyldcache_obj_t);
if (!bin) {
return NULL;
}
if (!buf) {
return r_bin_dyldcache_free (bin);
}
bin->b = r_buf_new ();
if (!bin->b || !r_buf_set_bytes (bin->b, buf, size)) {
return r_bin_dyldcache_free (bin);
}
if (!r_bin_dyldcache_init (bin)) {
return r_bin_dyldcache_free (bin);
}
bin->size = size;
return bin;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_502_0 |
crossvul-cpp_data_bad_486_2 | /* -*- c-basic-offset: 8 -*-
rdesktop: A Remote Desktop Protocol client.
Protocol services - Clipboard functions
Copyright 2003 Erik Forsberg <forsberg@cendio.se> for Cendio AB
Copyright (C) Matthew Chapman <matthewc.unsw.edu.au> 2003-2008
Copyright 2017 Henrik Andersson <hean01@cendio.se> for Cendio AB
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "rdesktop.h"
#define CLIPRDR_CONNECT 1
#define CLIPRDR_FORMAT_ANNOUNCE 2
#define CLIPRDR_FORMAT_ACK 3
#define CLIPRDR_DATA_REQUEST 4
#define CLIPRDR_DATA_RESPONSE 5
#define CLIPRDR_REQUEST 0
#define CLIPRDR_RESPONSE 1
#define CLIPRDR_ERROR 2
static VCHANNEL *cliprdr_channel;
static uint8 *last_formats = NULL;
static uint32 last_formats_length = 0;
static void
cliprdr_send_packet(uint16 type, uint16 status, uint8 * data, uint32 length)
{
STREAM s;
logger(Clipboard, Debug, "cliprdr_send_packet(), type=%d, status=%d, length=%d", type,
status, length);
s = channel_init(cliprdr_channel, length + 12);
out_uint16_le(s, type);
out_uint16_le(s, status);
out_uint32_le(s, length);
out_uint8p(s, data, length);
out_uint32(s, 0); /* pad? */
s_mark_end(s);
channel_send(s, cliprdr_channel);
}
/* Helper which announces our readiness to supply clipboard data
in a single format (such as CF_TEXT) to the RDP side.
To announce more than one format at a time, use
cliprdr_send_native_format_announce.
*/
void
cliprdr_send_simple_native_format_announce(uint32 format)
{
uint8 buffer[36];
logger(Clipboard, Debug, "cliprdr_send_simple_native_format_announce() format 0x%x",
format);
buf_out_uint32(buffer, format);
memset(buffer + 4, 0, sizeof(buffer) - 4); /* description */
cliprdr_send_native_format_announce(buffer, sizeof(buffer));
}
/* Announces our readiness to supply clipboard data in multiple
formats, each denoted by a 36-byte format descriptor of
[ uint32 format + 32-byte description ].
*/
void
cliprdr_send_native_format_announce(uint8 * formats_data, uint32 formats_data_length)
{
logger(Clipboard, Debug, "cliprdr_send_native_format_announce()");
cliprdr_send_packet(CLIPRDR_FORMAT_ANNOUNCE, CLIPRDR_REQUEST, formats_data,
formats_data_length);
if (formats_data != last_formats)
{
if (last_formats)
xfree(last_formats);
last_formats = xmalloc(formats_data_length);
memcpy(last_formats, formats_data, formats_data_length);
last_formats_length = formats_data_length;
}
}
void
cliprdr_send_data_request(uint32 format)
{
uint8 buffer[4];
logger(Clipboard, Debug, "cliprdr_send_data_request(), format 0x%x", format);
buf_out_uint32(buffer, format);
cliprdr_send_packet(CLIPRDR_DATA_REQUEST, CLIPRDR_REQUEST, buffer, sizeof(buffer));
}
void
cliprdr_send_data(uint8 * data, uint32 length)
{
logger(Clipboard, Debug, "cliprdr_send_data(), length %d bytes", length);
cliprdr_send_packet(CLIPRDR_DATA_RESPONSE, CLIPRDR_RESPONSE, data, length);
}
static void
cliprdr_process(STREAM s)
{
uint16 type, status;
uint32 length, format;
uint8 *data;
in_uint16_le(s, type);
in_uint16_le(s, status);
in_uint32_le(s, length);
data = s->p;
logger(Clipboard, Debug, "cliprdr_process(), type=%d, status=%d, length=%d", type, status,
length);
if (status == CLIPRDR_ERROR)
{
switch (type)
{
case CLIPRDR_FORMAT_ACK:
/* FIXME: We seem to get this when we send an announce while the server is
still processing a paste. Try sending another announce. */
cliprdr_send_native_format_announce(last_formats,
last_formats_length);
break;
case CLIPRDR_DATA_RESPONSE:
ui_clip_request_failed();
break;
default:
logger(Clipboard, Warning,
"cliprdr_process(), unhandled error (type=%d)", type);
}
return;
}
switch (type)
{
case CLIPRDR_CONNECT:
ui_clip_sync();
break;
case CLIPRDR_FORMAT_ANNOUNCE:
ui_clip_format_announce(data, length);
cliprdr_send_packet(CLIPRDR_FORMAT_ACK, CLIPRDR_RESPONSE, NULL, 0);
return;
case CLIPRDR_FORMAT_ACK:
break;
case CLIPRDR_DATA_REQUEST:
in_uint32_le(s, format);
ui_clip_request_data(format);
break;
case CLIPRDR_DATA_RESPONSE:
ui_clip_handle_data(data, length);
break;
case 7: /* TODO: W2K3 SP1 sends this on connect with a value of 1 */
break;
default:
logger(Clipboard, Warning, "cliprdr_process(), unhandled packet type %d",
type);
}
}
void
cliprdr_set_mode(const char *optarg)
{
ui_clip_set_mode(optarg);
}
RD_BOOL
cliprdr_init(void)
{
cliprdr_channel =
channel_register("cliprdr",
CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP |
CHANNEL_OPTION_COMPRESS_RDP | CHANNEL_OPTION_SHOW_PROTOCOL,
cliprdr_process);
return (cliprdr_channel != NULL);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_486_2 |
crossvul-cpp_data_good_2646_0 | /*
* Copyright (c) 1992, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: DECnet printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
struct mbuf;
struct rtentry;
#ifdef HAVE_NETDNET_DNETDB_H
#include <netdnet/dnetdb.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "extract.h"
#include "netdissect.h"
#include "addrtoname.h"
static const char tstr[] = "[|decnet]";
#ifndef _WIN32
typedef uint8_t byte[1]; /* single byte field */
#else
/*
* the keyword 'byte' generates conflicts in Windows
*/
typedef unsigned char Byte[1]; /* single byte field */
#define byte Byte
#endif /* _WIN32 */
typedef uint8_t word[2]; /* 2 byte field */
typedef uint8_t longword[4]; /* 4 bytes field */
/*
* Definitions for DECNET Phase IV protocol headers
*/
union etheraddress {
uint8_t dne_addr[6]; /* full ethernet address */
struct {
uint8_t dne_hiord[4]; /* DECnet HIORD prefix */
uint8_t dne_nodeaddr[2]; /* DECnet node address */
} dne_remote;
};
typedef union etheraddress etheraddr; /* Ethernet address */
#define HIORD 0x000400aa /* high 32-bits of address (swapped) */
#define AREAMASK 0176000 /* mask for area field */
#define AREASHIFT 10 /* bit-offset for area field */
#define NODEMASK 01777 /* mask for node address field */
#define DN_MAXADDL 20 /* max size of DECnet address */
struct dn_naddr {
uint16_t a_len; /* length of address */
uint8_t a_addr[DN_MAXADDL]; /* address as bytes */
};
/*
* Define long and short header formats.
*/
struct shorthdr
{
byte sh_flags; /* route flags */
word sh_dst; /* destination node address */
word sh_src; /* source node address */
byte sh_visits; /* visit count */
};
struct longhdr
{
byte lg_flags; /* route flags */
byte lg_darea; /* destination area (reserved) */
byte lg_dsarea; /* destination subarea (reserved) */
etheraddr lg_dst; /* destination id */
byte lg_sarea; /* source area (reserved) */
byte lg_ssarea; /* source subarea (reserved) */
etheraddr lg_src; /* source id */
byte lg_nextl2; /* next level 2 router (reserved) */
byte lg_visits; /* visit count */
byte lg_service; /* service class (reserved) */
byte lg_pt; /* protocol type (reserved) */
};
union routehdr
{
struct shorthdr rh_short; /* short route header */
struct longhdr rh_long; /* long route header */
};
/*
* Define the values of various fields in the protocol messages.
*
* 1. Data packet formats.
*/
#define RMF_MASK 7 /* mask for message type */
#define RMF_SHORT 2 /* short message format */
#define RMF_LONG 6 /* long message format */
#ifndef RMF_RQR
#define RMF_RQR 010 /* request return to sender */
#define RMF_RTS 020 /* returning to sender */
#define RMF_IE 040 /* intra-ethernet packet */
#endif /* RMR_RQR */
#define RMF_FVER 0100 /* future version flag */
#define RMF_PAD 0200 /* pad field */
#define RMF_PADMASK 0177 /* pad field mask */
#define VIS_MASK 077 /* visit field mask */
/*
* 2. Control packet formats.
*/
#define RMF_CTLMASK 017 /* mask for message type */
#define RMF_CTLMSG 01 /* control message indicator */
#define RMF_INIT 01 /* initialization message */
#define RMF_VER 03 /* verification message */
#define RMF_TEST 05 /* hello and test message */
#define RMF_L1ROUT 07 /* level 1 routing message */
#define RMF_L2ROUT 011 /* level 2 routing message */
#define RMF_RHELLO 013 /* router hello message */
#define RMF_EHELLO 015 /* endnode hello message */
#define TI_L2ROUT 01 /* level 2 router */
#define TI_L1ROUT 02 /* level 1 router */
#define TI_ENDNODE 03 /* endnode */
#define TI_VERIF 04 /* verification required */
#define TI_BLOCK 010 /* blocking requested */
#define VE_VERS 2 /* version number (2) */
#define VE_ECO 0 /* ECO number */
#define VE_UECO 0 /* user ECO number (0) */
#define P3_VERS 1 /* phase III version number (1) */
#define P3_ECO 3 /* ECO number (3) */
#define P3_UECO 0 /* user ECO number (0) */
#define II_L2ROUT 01 /* level 2 router */
#define II_L1ROUT 02 /* level 1 router */
#define II_ENDNODE 03 /* endnode */
#define II_VERIF 04 /* verification required */
#define II_NOMCAST 040 /* no multicast traffic accepted */
#define II_BLOCK 0100 /* blocking requested */
#define II_TYPEMASK 03 /* mask for node type */
#define TESTDATA 0252 /* test data bytes */
#define TESTLEN 1 /* length of transmitted test data */
/*
* Define control message formats.
*/
struct initmsgIII /* phase III initialization message */
{
byte inIII_flags; /* route flags */
word inIII_src; /* source node address */
byte inIII_info; /* routing layer information */
word inIII_blksize; /* maximum data link block size */
byte inIII_vers; /* version number */
byte inIII_eco; /* ECO number */
byte inIII_ueco; /* user ECO number */
byte inIII_rsvd; /* reserved image field */
};
struct initmsg /* initialization message */
{
byte in_flags; /* route flags */
word in_src; /* source node address */
byte in_info; /* routing layer information */
word in_blksize; /* maximum data link block size */
byte in_vers; /* version number */
byte in_eco; /* ECO number */
byte in_ueco; /* user ECO number */
word in_hello; /* hello timer */
byte in_rsvd; /* reserved image field */
};
struct verifmsg /* verification message */
{
byte ve_flags; /* route flags */
word ve_src; /* source node address */
byte ve_fcnval; /* function value image field */
};
struct testmsg /* hello and test message */
{
byte te_flags; /* route flags */
word te_src; /* source node address */
byte te_data; /* test data image field */
};
struct l1rout /* level 1 routing message */
{
byte r1_flags; /* route flags */
word r1_src; /* source node address */
byte r1_rsvd; /* reserved field */
};
struct l2rout /* level 2 routing message */
{
byte r2_flags; /* route flags */
word r2_src; /* source node address */
byte r2_rsvd; /* reserved field */
};
struct rhellomsg /* router hello message */
{
byte rh_flags; /* route flags */
byte rh_vers; /* version number */
byte rh_eco; /* ECO number */
byte rh_ueco; /* user ECO number */
etheraddr rh_src; /* source id */
byte rh_info; /* routing layer information */
word rh_blksize; /* maximum data link block size */
byte rh_priority; /* router's priority */
byte rh_area; /* reserved */
word rh_hello; /* hello timer */
byte rh_mpd; /* reserved */
};
struct ehellomsg /* endnode hello message */
{
byte eh_flags; /* route flags */
byte eh_vers; /* version number */
byte eh_eco; /* ECO number */
byte eh_ueco; /* user ECO number */
etheraddr eh_src; /* source id */
byte eh_info; /* routing layer information */
word eh_blksize; /* maximum data link block size */
byte eh_area; /* area (reserved) */
byte eh_seed[8]; /* verification seed */
etheraddr eh_router; /* designated router */
word eh_hello; /* hello timer */
byte eh_mpd; /* (reserved) */
byte eh_data; /* test data image field */
};
union controlmsg
{
struct initmsg cm_init; /* initialization message */
struct verifmsg cm_ver; /* verification message */
struct testmsg cm_test; /* hello and test message */
struct l1rout cm_l1rou; /* level 1 routing message */
struct l2rout cm_l2rout; /* level 2 routing message */
struct rhellomsg cm_rhello; /* router hello message */
struct ehellomsg cm_ehello; /* endnode hello message */
};
/* Macros for decoding routing-info fields */
#define RI_COST(x) ((x)&0777)
#define RI_HOPS(x) (((x)>>10)&037)
/*
* NSP protocol fields and values.
*/
#define NSP_TYPEMASK 014 /* mask to isolate type code */
#define NSP_SUBMASK 0160 /* mask to isolate subtype code */
#define NSP_SUBSHFT 4 /* shift to move subtype code */
#define MFT_DATA 0 /* data message */
#define MFT_ACK 04 /* acknowledgement message */
#define MFT_CTL 010 /* control message */
#define MFS_ILS 020 /* data or I/LS indicator */
#define MFS_BOM 040 /* beginning of message (data) */
#define MFS_MOM 0 /* middle of message (data) */
#define MFS_EOM 0100 /* end of message (data) */
#define MFS_INT 040 /* interrupt message */
#define MFS_DACK 0 /* data acknowledgement */
#define MFS_IACK 020 /* I/LS acknowledgement */
#define MFS_CACK 040 /* connect acknowledgement */
#define MFS_NOP 0 /* no operation */
#define MFS_CI 020 /* connect initiate */
#define MFS_CC 040 /* connect confirm */
#define MFS_DI 060 /* disconnect initiate */
#define MFS_DC 0100 /* disconnect confirm */
#define MFS_RCI 0140 /* retransmitted connect initiate */
#define SGQ_ACK 0100000 /* ack */
#define SGQ_NAK 0110000 /* negative ack */
#define SGQ_OACK 0120000 /* other channel ack */
#define SGQ_ONAK 0130000 /* other channel negative ack */
#define SGQ_MASK 07777 /* mask to isolate seq # */
#define SGQ_OTHER 020000 /* other channel qualifier */
#define SGQ_DELAY 010000 /* ack delay flag */
#define SGQ_EOM 0100000 /* pseudo flag for end-of-message */
#define LSM_MASK 03 /* mask for modifier field */
#define LSM_NOCHANGE 0 /* no change */
#define LSM_DONOTSEND 1 /* do not send data */
#define LSM_SEND 2 /* send data */
#define LSI_MASK 014 /* mask for interpretation field */
#define LSI_DATA 0 /* data segment or message count */
#define LSI_INTR 4 /* interrupt request count */
#define LSI_INTM 0377 /* funny marker for int. message */
#define COS_MASK 014 /* mask for flow control field */
#define COS_NONE 0 /* no flow control */
#define COS_SEGMENT 04 /* segment flow control */
#define COS_MESSAGE 010 /* message flow control */
#define COS_DEFAULT 1 /* default value for field */
#define COI_MASK 3 /* mask for version field */
#define COI_32 0 /* version 3.2 */
#define COI_31 1 /* version 3.1 */
#define COI_40 2 /* version 4.0 */
#define COI_41 3 /* version 4.1 */
#define MNU_MASK 140 /* mask for session control version */
#define MNU_10 000 /* session V1.0 */
#define MNU_20 040 /* session V2.0 */
#define MNU_ACCESS 1 /* access control present */
#define MNU_USRDATA 2 /* user data field present */
#define MNU_INVKPROXY 4 /* invoke proxy field present */
#define MNU_UICPROXY 8 /* use uic-based proxy */
#define DC_NORESOURCES 1 /* no resource reason code */
#define DC_NOLINK 41 /* no link terminate reason code */
#define DC_COMPLETE 42 /* disconnect complete reason code */
#define DI_NOERROR 0 /* user disconnect */
#define DI_SHUT 3 /* node is shutting down */
#define DI_NOUSER 4 /* destination end user does not exist */
#define DI_INVDEST 5 /* invalid end user destination */
#define DI_REMRESRC 6 /* insufficient remote resources */
#define DI_TPA 8 /* third party abort */
#define DI_PROTOCOL 7 /* protocol error discovered */
#define DI_ABORT 9 /* user abort */
#define DI_LOCALRESRC 32 /* insufficient local resources */
#define DI_REMUSERRESRC 33 /* insufficient remote user resources */
#define DI_BADACCESS 34 /* bad access control information */
#define DI_BADACCNT 36 /* bad ACCOUNT information */
#define DI_CONNECTABORT 38 /* connect request cancelled */
#define DI_TIMEDOUT 38 /* remote node or user crashed */
#define DI_UNREACHABLE 39 /* local timers expired due to ... */
#define DI_BADIMAGE 43 /* bad image data in connect */
#define DI_SERVMISMATCH 54 /* cryptographic service mismatch */
#define UC_OBJREJECT 0 /* object rejected connect */
#define UC_USERDISCONNECT 0 /* user disconnect */
#define UC_RESOURCES 1 /* insufficient resources (local or remote) */
#define UC_NOSUCHNODE 2 /* unrecognized node name */
#define UC_REMOTESHUT 3 /* remote node shutting down */
#define UC_NOSUCHOBJ 4 /* unrecognized object */
#define UC_INVOBJFORMAT 5 /* invalid object name format */
#define UC_OBJTOOBUSY 6 /* object too busy */
#define UC_NETWORKABORT 8 /* network abort */
#define UC_USERABORT 9 /* user abort */
#define UC_INVNODEFORMAT 10 /* invalid node name format */
#define UC_LOCALSHUT 11 /* local node shutting down */
#define UC_ACCESSREJECT 34 /* invalid access control information */
#define UC_NORESPONSE 38 /* no response from object */
#define UC_UNREACHABLE 39 /* node unreachable */
/*
* NSP message formats.
*/
struct nsphdr /* general nsp header */
{
byte nh_flags; /* message flags */
word nh_dst; /* destination link address */
word nh_src; /* source link address */
};
struct seghdr /* data segment header */
{
byte sh_flags; /* message flags */
word sh_dst; /* destination link address */
word sh_src; /* source link address */
word sh_seq[3]; /* sequence numbers */
};
struct minseghdr /* minimum data segment header */
{
byte ms_flags; /* message flags */
word ms_dst; /* destination link address */
word ms_src; /* source link address */
word ms_seq; /* sequence number */
};
struct lsmsg /* link service message (after hdr) */
{
byte ls_lsflags; /* link service flags */
byte ls_fcval; /* flow control value */
};
struct ackmsg /* acknowledgement message */
{
byte ak_flags; /* message flags */
word ak_dst; /* destination link address */
word ak_src; /* source link address */
word ak_acknum[2]; /* acknowledgement numbers */
};
struct minackmsg /* minimum acknowledgement message */
{
byte mk_flags; /* message flags */
word mk_dst; /* destination link address */
word mk_src; /* source link address */
word mk_acknum; /* acknowledgement number */
};
struct ciackmsg /* connect acknowledgement message */
{
byte ck_flags; /* message flags */
word ck_dst; /* destination link address */
};
struct cimsg /* connect initiate message */
{
byte ci_flags; /* message flags */
word ci_dst; /* destination link address (0) */
word ci_src; /* source link address */
byte ci_services; /* requested services */
byte ci_info; /* information */
word ci_segsize; /* maximum segment size */
};
struct ccmsg /* connect confirm message */
{
byte cc_flags; /* message flags */
word cc_dst; /* destination link address */
word cc_src; /* source link address */
byte cc_services; /* requested services */
byte cc_info; /* information */
word cc_segsize; /* maximum segment size */
byte cc_optlen; /* optional data length */
};
struct cnmsg /* generic connect message */
{
byte cn_flags; /* message flags */
word cn_dst; /* destination link address */
word cn_src; /* source link address */
byte cn_services; /* requested services */
byte cn_info; /* information */
word cn_segsize; /* maximum segment size */
};
struct dimsg /* disconnect initiate message */
{
byte di_flags; /* message flags */
word di_dst; /* destination link address */
word di_src; /* source link address */
word di_reason; /* reason code */
byte di_optlen; /* optional data length */
};
struct dcmsg /* disconnect confirm message */
{
byte dc_flags; /* message flags */
word dc_dst; /* destination link address */
word dc_src; /* source link address */
word dc_reason; /* reason code */
};
/* Forwards */
static int print_decnet_ctlmsg(netdissect_options *, const union routehdr *, u_int, u_int);
static void print_t_info(netdissect_options *, int);
static int print_l1_routes(netdissect_options *, const char *, u_int);
static int print_l2_routes(netdissect_options *, const char *, u_int);
static void print_i_info(netdissect_options *, int);
static int print_elist(const char *, u_int);
static int print_nsp(netdissect_options *, const u_char *, u_int);
static void print_reason(netdissect_options *, int);
#ifndef HAVE_NETDNET_DNETDB_H_DNET_HTOA
extern char *dnet_htoa(struct dn_naddr *);
#endif
void
decnet_print(netdissect_options *ndo,
register const u_char *ap, register u_int length,
register u_int caplen)
{
register const union routehdr *rhp;
register int mflags;
int dst, src, hops;
u_int nsplen, pktlen;
const u_char *nspp;
if (length < sizeof(struct shorthdr)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
ND_TCHECK2(*ap, sizeof(short));
pktlen = EXTRACT_LE_16BITS(ap);
if (pktlen < sizeof(struct shorthdr)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
if (pktlen > length) {
ND_PRINT((ndo, "%s", tstr));
return;
}
length = pktlen;
rhp = (const union routehdr *)&(ap[sizeof(short)]);
ND_TCHECK(rhp->rh_short.sh_flags);
mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
if (mflags & RMF_PAD) {
/* pad bytes of some sort in front of message */
u_int padlen = mflags & RMF_PADMASK;
if (ndo->ndo_vflag)
ND_PRINT((ndo, "[pad:%d] ", padlen));
if (length < padlen + 2) {
ND_PRINT((ndo, "%s", tstr));
return;
}
ND_TCHECK2(ap[sizeof(short)], padlen);
ap += padlen;
length -= padlen;
caplen -= padlen;
rhp = (const union routehdr *)&(ap[sizeof(short)]);
ND_TCHECK(rhp->rh_short.sh_flags);
mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
}
if (mflags & RMF_FVER) {
ND_PRINT((ndo, "future-version-decnet"));
ND_DEFAULTPRINT(ap, min(length, caplen));
return;
}
/* is it a control message? */
if (mflags & RMF_CTLMSG) {
if (!print_decnet_ctlmsg(ndo, rhp, length, caplen))
goto trunc;
return;
}
switch (mflags & RMF_MASK) {
case RMF_LONG:
if (length < sizeof(struct longhdr)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
ND_TCHECK(rhp->rh_long);
dst =
EXTRACT_LE_16BITS(rhp->rh_long.lg_dst.dne_remote.dne_nodeaddr);
src =
EXTRACT_LE_16BITS(rhp->rh_long.lg_src.dne_remote.dne_nodeaddr);
hops = EXTRACT_LE_8BITS(rhp->rh_long.lg_visits);
nspp = &(ap[sizeof(short) + sizeof(struct longhdr)]);
nsplen = length - sizeof(struct longhdr);
break;
case RMF_SHORT:
ND_TCHECK(rhp->rh_short);
dst = EXTRACT_LE_16BITS(rhp->rh_short.sh_dst);
src = EXTRACT_LE_16BITS(rhp->rh_short.sh_src);
hops = (EXTRACT_LE_8BITS(rhp->rh_short.sh_visits) & VIS_MASK)+1;
nspp = &(ap[sizeof(short) + sizeof(struct shorthdr)]);
nsplen = length - sizeof(struct shorthdr);
break;
default:
ND_PRINT((ndo, "unknown message flags under mask"));
ND_DEFAULTPRINT((const u_char *)ap, min(length, caplen));
return;
}
ND_PRINT((ndo, "%s > %s %d ",
dnaddr_string(ndo, src), dnaddr_string(ndo, dst), pktlen));
if (ndo->ndo_vflag) {
if (mflags & RMF_RQR)
ND_PRINT((ndo, "RQR "));
if (mflags & RMF_RTS)
ND_PRINT((ndo, "RTS "));
if (mflags & RMF_IE)
ND_PRINT((ndo, "IE "));
ND_PRINT((ndo, "%d hops ", hops));
}
if (!print_nsp(ndo, nspp, nsplen))
goto trunc;
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
return;
}
static int
print_decnet_ctlmsg(netdissect_options *ndo,
register const union routehdr *rhp, u_int length,
u_int caplen)
{
/* Our caller has already checked for mflags */
int mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
register const union controlmsg *cmp = (const union controlmsg *)rhp;
int src, dst, info, blksize, eco, ueco, hello, other, vers;
etheraddr srcea, rtea;
int priority;
const char *rhpx = (const char *)rhp;
int ret;
switch (mflags & RMF_CTLMASK) {
case RMF_INIT:
ND_PRINT((ndo, "init "));
if (length < sizeof(struct initmsg))
goto trunc;
ND_TCHECK(cmp->cm_init);
src = EXTRACT_LE_16BITS(cmp->cm_init.in_src);
info = EXTRACT_LE_8BITS(cmp->cm_init.in_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_init.in_blksize);
vers = EXTRACT_LE_8BITS(cmp->cm_init.in_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_init.in_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_init.in_ueco);
hello = EXTRACT_LE_16BITS(cmp->cm_init.in_hello);
print_t_info(ndo, info);
ND_PRINT((ndo,
"src %sblksize %d vers %d eco %d ueco %d hello %d",
dnaddr_string(ndo, src), blksize, vers, eco, ueco,
hello));
ret = 1;
break;
case RMF_VER:
ND_PRINT((ndo, "verification "));
if (length < sizeof(struct verifmsg))
goto trunc;
ND_TCHECK(cmp->cm_ver);
src = EXTRACT_LE_16BITS(cmp->cm_ver.ve_src);
other = EXTRACT_LE_8BITS(cmp->cm_ver.ve_fcnval);
ND_PRINT((ndo, "src %s fcnval %o", dnaddr_string(ndo, src), other));
ret = 1;
break;
case RMF_TEST:
ND_PRINT((ndo, "test "));
if (length < sizeof(struct testmsg))
goto trunc;
ND_TCHECK(cmp->cm_test);
src = EXTRACT_LE_16BITS(cmp->cm_test.te_src);
other = EXTRACT_LE_8BITS(cmp->cm_test.te_data);
ND_PRINT((ndo, "src %s data %o", dnaddr_string(ndo, src), other));
ret = 1;
break;
case RMF_L1ROUT:
ND_PRINT((ndo, "lev-1-routing "));
if (length < sizeof(struct l1rout))
goto trunc;
ND_TCHECK(cmp->cm_l1rou);
src = EXTRACT_LE_16BITS(cmp->cm_l1rou.r1_src);
ND_PRINT((ndo, "src %s ", dnaddr_string(ndo, src)));
ret = print_l1_routes(ndo, &(rhpx[sizeof(struct l1rout)]),
length - sizeof(struct l1rout));
break;
case RMF_L2ROUT:
ND_PRINT((ndo, "lev-2-routing "));
if (length < sizeof(struct l2rout))
goto trunc;
ND_TCHECK(cmp->cm_l2rout);
src = EXTRACT_LE_16BITS(cmp->cm_l2rout.r2_src);
ND_PRINT((ndo, "src %s ", dnaddr_string(ndo, src)));
ret = print_l2_routes(ndo, &(rhpx[sizeof(struct l2rout)]),
length - sizeof(struct l2rout));
break;
case RMF_RHELLO:
ND_PRINT((ndo, "router-hello "));
if (length < sizeof(struct rhellomsg))
goto trunc;
ND_TCHECK(cmp->cm_rhello);
vers = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_ueco);
memcpy((char *)&srcea, (const char *)&(cmp->cm_rhello.rh_src),
sizeof(srcea));
src = EXTRACT_LE_16BITS(srcea.dne_remote.dne_nodeaddr);
info = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_rhello.rh_blksize);
priority = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_priority);
hello = EXTRACT_LE_16BITS(cmp->cm_rhello.rh_hello);
print_i_info(ndo, info);
ND_PRINT((ndo,
"vers %d eco %d ueco %d src %s blksize %d pri %d hello %d",
vers, eco, ueco, dnaddr_string(ndo, src),
blksize, priority, hello));
ret = print_elist(&(rhpx[sizeof(struct rhellomsg)]),
length - sizeof(struct rhellomsg));
break;
case RMF_EHELLO:
ND_PRINT((ndo, "endnode-hello "));
if (length < sizeof(struct ehellomsg))
goto trunc;
ND_TCHECK(cmp->cm_ehello);
vers = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_ueco);
memcpy((char *)&srcea, (const char *)&(cmp->cm_ehello.eh_src),
sizeof(srcea));
src = EXTRACT_LE_16BITS(srcea.dne_remote.dne_nodeaddr);
info = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_ehello.eh_blksize);
/*seed*/
memcpy((char *)&rtea, (const char *)&(cmp->cm_ehello.eh_router),
sizeof(rtea));
dst = EXTRACT_LE_16BITS(rtea.dne_remote.dne_nodeaddr);
hello = EXTRACT_LE_16BITS(cmp->cm_ehello.eh_hello);
other = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_data);
print_i_info(ndo, info);
ND_PRINT((ndo,
"vers %d eco %d ueco %d src %s blksize %d rtr %s hello %d data %o",
vers, eco, ueco, dnaddr_string(ndo, src),
blksize, dnaddr_string(ndo, dst), hello, other));
ret = 1;
break;
default:
ND_PRINT((ndo, "unknown control message"));
ND_DEFAULTPRINT((const u_char *)rhp, min(length, caplen));
ret = 1;
break;
}
return (ret);
trunc:
return (0);
}
static void
print_t_info(netdissect_options *ndo,
int info)
{
int ntype = info & 3;
switch (ntype) {
case 0: ND_PRINT((ndo, "reserved-ntype? ")); break;
case TI_L2ROUT: ND_PRINT((ndo, "l2rout ")); break;
case TI_L1ROUT: ND_PRINT((ndo, "l1rout ")); break;
case TI_ENDNODE: ND_PRINT((ndo, "endnode ")); break;
}
if (info & TI_VERIF)
ND_PRINT((ndo, "verif "));
if (info & TI_BLOCK)
ND_PRINT((ndo, "blo "));
}
static int
print_l1_routes(netdissect_options *ndo,
const char *rp, u_int len)
{
int count;
int id;
int info;
/* The last short is a checksum */
while (len > (3 * sizeof(short))) {
ND_TCHECK2(*rp, 3 * sizeof(short));
count = EXTRACT_LE_16BITS(rp);
if (count > 1024)
return (1); /* seems to be bogus from here on */
rp += sizeof(short);
len -= sizeof(short);
id = EXTRACT_LE_16BITS(rp);
rp += sizeof(short);
len -= sizeof(short);
info = EXTRACT_LE_16BITS(rp);
rp += sizeof(short);
len -= sizeof(short);
ND_PRINT((ndo, "{ids %d-%d cost %d hops %d} ", id, id + count,
RI_COST(info), RI_HOPS(info)));
}
return (1);
trunc:
return (0);
}
static int
print_l2_routes(netdissect_options *ndo,
const char *rp, u_int len)
{
int count;
int area;
int info;
/* The last short is a checksum */
while (len > (3 * sizeof(short))) {
ND_TCHECK2(*rp, 3 * sizeof(short));
count = EXTRACT_LE_16BITS(rp);
if (count > 1024)
return (1); /* seems to be bogus from here on */
rp += sizeof(short);
len -= sizeof(short);
area = EXTRACT_LE_16BITS(rp);
rp += sizeof(short);
len -= sizeof(short);
info = EXTRACT_LE_16BITS(rp);
rp += sizeof(short);
len -= sizeof(short);
ND_PRINT((ndo, "{areas %d-%d cost %d hops %d} ", area, area + count,
RI_COST(info), RI_HOPS(info)));
}
return (1);
trunc:
return (0);
}
static void
print_i_info(netdissect_options *ndo,
int info)
{
int ntype = info & II_TYPEMASK;
switch (ntype) {
case 0: ND_PRINT((ndo, "reserved-ntype? ")); break;
case II_L2ROUT: ND_PRINT((ndo, "l2rout ")); break;
case II_L1ROUT: ND_PRINT((ndo, "l1rout ")); break;
case II_ENDNODE: ND_PRINT((ndo, "endnode ")); break;
}
if (info & II_VERIF)
ND_PRINT((ndo, "verif "));
if (info & II_NOMCAST)
ND_PRINT((ndo, "nomcast "));
if (info & II_BLOCK)
ND_PRINT((ndo, "blo "));
}
static int
print_elist(const char *elp _U_, u_int len _U_)
{
/* Not enough examples available for me to debug this */
return (1);
}
static int
print_nsp(netdissect_options *ndo,
const u_char *nspp, u_int nsplen)
{
const struct nsphdr *nsphp = (const struct nsphdr *)nspp;
int dst, src, flags;
if (nsplen < sizeof(struct nsphdr))
goto trunc;
ND_TCHECK(*nsphp);
flags = EXTRACT_LE_8BITS(nsphp->nh_flags);
dst = EXTRACT_LE_16BITS(nsphp->nh_dst);
src = EXTRACT_LE_16BITS(nsphp->nh_src);
switch (flags & NSP_TYPEMASK) {
case MFT_DATA:
switch (flags & NSP_SUBMASK) {
case MFS_BOM:
case MFS_MOM:
case MFS_EOM:
case MFS_BOM+MFS_EOM:
ND_PRINT((ndo, "data %d>%d ", src, dst));
{
const struct seghdr *shp = (const struct seghdr *)nspp;
int ack;
u_int data_off = sizeof(struct minseghdr);
if (nsplen < data_off)
goto trunc;
ND_TCHECK(shp->sh_seq[0]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[0]);
if (ack & SGQ_ACK) { /* acknum field */
if ((ack & SGQ_NAK) == SGQ_NAK)
ND_PRINT((ndo, "nak %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ack %d ", ack & SGQ_MASK));
data_off += sizeof(short);
if (nsplen < data_off)
goto trunc;
ND_TCHECK(shp->sh_seq[1]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[1]);
if (ack & SGQ_OACK) { /* ackoth field */
if ((ack & SGQ_ONAK) == SGQ_ONAK)
ND_PRINT((ndo, "onak %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "oack %d ", ack & SGQ_MASK));
data_off += sizeof(short);
if (nsplen < data_off)
goto trunc;
ND_TCHECK(shp->sh_seq[2]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[2]);
}
}
ND_PRINT((ndo, "seg %d ", ack & SGQ_MASK));
}
break;
case MFS_ILS+MFS_INT:
ND_PRINT((ndo, "intr "));
{
const struct seghdr *shp = (const struct seghdr *)nspp;
int ack;
u_int data_off = sizeof(struct minseghdr);
if (nsplen < data_off)
goto trunc;
ND_TCHECK(shp->sh_seq[0]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[0]);
if (ack & SGQ_ACK) { /* acknum field */
if ((ack & SGQ_NAK) == SGQ_NAK)
ND_PRINT((ndo, "nak %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ack %d ", ack & SGQ_MASK));
data_off += sizeof(short);
if (nsplen < data_off)
goto trunc;
ND_TCHECK(shp->sh_seq[1]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[1]);
if (ack & SGQ_OACK) { /* ackdat field */
if ((ack & SGQ_ONAK) == SGQ_ONAK)
ND_PRINT((ndo, "nakdat %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ackdat %d ", ack & SGQ_MASK));
data_off += sizeof(short);
if (nsplen < data_off)
goto trunc;
ND_TCHECK(shp->sh_seq[2]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[2]);
}
}
ND_PRINT((ndo, "seg %d ", ack & SGQ_MASK));
}
break;
case MFS_ILS:
ND_PRINT((ndo, "link-service %d>%d ", src, dst));
{
const struct seghdr *shp = (const struct seghdr *)nspp;
const struct lsmsg *lsmp =
(const struct lsmsg *)&(nspp[sizeof(struct seghdr)]);
int ack;
int lsflags, fcval;
if (nsplen < sizeof(struct seghdr) + sizeof(struct lsmsg))
goto trunc;
ND_TCHECK(shp->sh_seq[0]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[0]);
if (ack & SGQ_ACK) { /* acknum field */
if ((ack & SGQ_NAK) == SGQ_NAK)
ND_PRINT((ndo, "nak %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ack %d ", ack & SGQ_MASK));
ND_TCHECK(shp->sh_seq[1]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[1]);
if (ack & SGQ_OACK) { /* ackdat field */
if ((ack & SGQ_ONAK) == SGQ_ONAK)
ND_PRINT((ndo, "nakdat %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ackdat %d ", ack & SGQ_MASK));
ND_TCHECK(shp->sh_seq[2]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[2]);
}
}
ND_PRINT((ndo, "seg %d ", ack & SGQ_MASK));
ND_TCHECK(*lsmp);
lsflags = EXTRACT_LE_8BITS(lsmp->ls_lsflags);
fcval = EXTRACT_LE_8BITS(lsmp->ls_fcval);
switch (lsflags & LSI_MASK) {
case LSI_DATA:
ND_PRINT((ndo, "dat seg count %d ", fcval));
switch (lsflags & LSM_MASK) {
case LSM_NOCHANGE:
break;
case LSM_DONOTSEND:
ND_PRINT((ndo, "donotsend-data "));
break;
case LSM_SEND:
ND_PRINT((ndo, "send-data "));
break;
default:
ND_PRINT((ndo, "reserved-fcmod? %x", lsflags));
break;
}
break;
case LSI_INTR:
ND_PRINT((ndo, "intr req count %d ", fcval));
break;
default:
ND_PRINT((ndo, "reserved-fcval-int? %x", lsflags));
break;
}
}
break;
default:
ND_PRINT((ndo, "reserved-subtype? %x %d > %d", flags, src, dst));
break;
}
break;
case MFT_ACK:
switch (flags & NSP_SUBMASK) {
case MFS_DACK:
ND_PRINT((ndo, "data-ack %d>%d ", src, dst));
{
const struct ackmsg *amp = (const struct ackmsg *)nspp;
int ack;
if (nsplen < sizeof(struct ackmsg))
goto trunc;
ND_TCHECK(*amp);
ack = EXTRACT_LE_16BITS(amp->ak_acknum[0]);
if (ack & SGQ_ACK) { /* acknum field */
if ((ack & SGQ_NAK) == SGQ_NAK)
ND_PRINT((ndo, "nak %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ack %d ", ack & SGQ_MASK));
ack = EXTRACT_LE_16BITS(amp->ak_acknum[1]);
if (ack & SGQ_OACK) { /* ackoth field */
if ((ack & SGQ_ONAK) == SGQ_ONAK)
ND_PRINT((ndo, "onak %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "oack %d ", ack & SGQ_MASK));
}
}
}
break;
case MFS_IACK:
ND_PRINT((ndo, "ils-ack %d>%d ", src, dst));
{
const struct ackmsg *amp = (const struct ackmsg *)nspp;
int ack;
if (nsplen < sizeof(struct ackmsg))
goto trunc;
ND_TCHECK(*amp);
ack = EXTRACT_LE_16BITS(amp->ak_acknum[0]);
if (ack & SGQ_ACK) { /* acknum field */
if ((ack & SGQ_NAK) == SGQ_NAK)
ND_PRINT((ndo, "nak %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ack %d ", ack & SGQ_MASK));
ND_TCHECK(amp->ak_acknum[1]);
ack = EXTRACT_LE_16BITS(amp->ak_acknum[1]);
if (ack & SGQ_OACK) { /* ackdat field */
if ((ack & SGQ_ONAK) == SGQ_ONAK)
ND_PRINT((ndo, "nakdat %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ackdat %d ", ack & SGQ_MASK));
}
}
}
break;
case MFS_CACK:
ND_PRINT((ndo, "conn-ack %d", dst));
break;
default:
ND_PRINT((ndo, "reserved-acktype? %x %d > %d", flags, src, dst));
break;
}
break;
case MFT_CTL:
switch (flags & NSP_SUBMASK) {
case MFS_CI:
case MFS_RCI:
if ((flags & NSP_SUBMASK) == MFS_CI)
ND_PRINT((ndo, "conn-initiate "));
else
ND_PRINT((ndo, "retrans-conn-initiate "));
ND_PRINT((ndo, "%d>%d ", src, dst));
{
const struct cimsg *cimp = (const struct cimsg *)nspp;
int services, info, segsize;
if (nsplen < sizeof(struct cimsg))
goto trunc;
ND_TCHECK(*cimp);
services = EXTRACT_LE_8BITS(cimp->ci_services);
info = EXTRACT_LE_8BITS(cimp->ci_info);
segsize = EXTRACT_LE_16BITS(cimp->ci_segsize);
switch (services & COS_MASK) {
case COS_NONE:
break;
case COS_SEGMENT:
ND_PRINT((ndo, "seg "));
break;
case COS_MESSAGE:
ND_PRINT((ndo, "msg "));
break;
}
switch (info & COI_MASK) {
case COI_32:
ND_PRINT((ndo, "ver 3.2 "));
break;
case COI_31:
ND_PRINT((ndo, "ver 3.1 "));
break;
case COI_40:
ND_PRINT((ndo, "ver 4.0 "));
break;
case COI_41:
ND_PRINT((ndo, "ver 4.1 "));
break;
}
ND_PRINT((ndo, "segsize %d ", segsize));
}
break;
case MFS_CC:
ND_PRINT((ndo, "conn-confirm %d>%d ", src, dst));
{
const struct ccmsg *ccmp = (const struct ccmsg *)nspp;
int services, info;
u_int segsize, optlen;
if (nsplen < sizeof(struct ccmsg))
goto trunc;
ND_TCHECK(*ccmp);
services = EXTRACT_LE_8BITS(ccmp->cc_services);
info = EXTRACT_LE_8BITS(ccmp->cc_info);
segsize = EXTRACT_LE_16BITS(ccmp->cc_segsize);
optlen = EXTRACT_LE_8BITS(ccmp->cc_optlen);
switch (services & COS_MASK) {
case COS_NONE:
break;
case COS_SEGMENT:
ND_PRINT((ndo, "seg "));
break;
case COS_MESSAGE:
ND_PRINT((ndo, "msg "));
break;
}
switch (info & COI_MASK) {
case COI_32:
ND_PRINT((ndo, "ver 3.2 "));
break;
case COI_31:
ND_PRINT((ndo, "ver 3.1 "));
break;
case COI_40:
ND_PRINT((ndo, "ver 4.0 "));
break;
case COI_41:
ND_PRINT((ndo, "ver 4.1 "));
break;
}
ND_PRINT((ndo, "segsize %d ", segsize));
if (optlen) {
ND_PRINT((ndo, "optlen %d ", optlen));
}
}
break;
case MFS_DI:
ND_PRINT((ndo, "disconn-initiate %d>%d ", src, dst));
{
const struct dimsg *dimp = (const struct dimsg *)nspp;
int reason;
u_int optlen;
if (nsplen < sizeof(struct dimsg))
goto trunc;
ND_TCHECK(*dimp);
reason = EXTRACT_LE_16BITS(dimp->di_reason);
optlen = EXTRACT_LE_8BITS(dimp->di_optlen);
print_reason(ndo, reason);
if (optlen) {
ND_PRINT((ndo, "optlen %d ", optlen));
}
}
break;
case MFS_DC:
ND_PRINT((ndo, "disconn-confirm %d>%d ", src, dst));
{
const struct dcmsg *dcmp = (const struct dcmsg *)nspp;
int reason;
ND_TCHECK(*dcmp);
reason = EXTRACT_LE_16BITS(dcmp->dc_reason);
print_reason(ndo, reason);
}
break;
default:
ND_PRINT((ndo, "reserved-ctltype? %x %d > %d", flags, src, dst));
break;
}
break;
default:
ND_PRINT((ndo, "reserved-type? %x %d > %d", flags, src, dst));
break;
}
return (1);
trunc:
return (0);
}
static const struct tok reason2str[] = {
{ UC_OBJREJECT, "object rejected connect" },
{ UC_RESOURCES, "insufficient resources" },
{ UC_NOSUCHNODE, "unrecognized node name" },
{ DI_SHUT, "node is shutting down" },
{ UC_NOSUCHOBJ, "unrecognized object" },
{ UC_INVOBJFORMAT, "invalid object name format" },
{ UC_OBJTOOBUSY, "object too busy" },
{ DI_PROTOCOL, "protocol error discovered" },
{ DI_TPA, "third party abort" },
{ UC_USERABORT, "user abort" },
{ UC_INVNODEFORMAT, "invalid node name format" },
{ UC_LOCALSHUT, "local node shutting down" },
{ DI_LOCALRESRC, "insufficient local resources" },
{ DI_REMUSERRESRC, "insufficient remote user resources" },
{ UC_ACCESSREJECT, "invalid access control information" },
{ DI_BADACCNT, "bad ACCOUNT information" },
{ UC_NORESPONSE, "no response from object" },
{ UC_UNREACHABLE, "node unreachable" },
{ DC_NOLINK, "no link terminate" },
{ DC_COMPLETE, "disconnect complete" },
{ DI_BADIMAGE, "bad image data in connect" },
{ DI_SERVMISMATCH, "cryptographic service mismatch" },
{ 0, NULL }
};
static void
print_reason(netdissect_options *ndo,
register int reason)
{
ND_PRINT((ndo, "%s ", tok2str(reason2str, "reason-%d", reason)));
}
const char *
dnnum_string(netdissect_options *ndo, u_short dnaddr)
{
char *str;
size_t siz;
int area = (u_short)(dnaddr & AREAMASK) >> AREASHIFT;
int node = dnaddr & NODEMASK;
str = (char *)malloc(siz = sizeof("00.0000"));
if (str == NULL)
(*ndo->ndo_error)(ndo, "dnnum_string: malloc");
snprintf(str, siz, "%d.%d", area, node);
return(str);
}
const char *
dnname_string(netdissect_options *ndo, u_short dnaddr)
{
#ifdef HAVE_DNET_HTOA
struct dn_naddr dna;
char *dnname;
dna.a_len = sizeof(short);
memcpy((char *)dna.a_addr, (char *)&dnaddr, sizeof(short));
dnname = dnet_htoa(&dna);
if(dnname != NULL)
return (strdup(dnname));
else
return(dnnum_string(ndo, dnaddr));
#else
return(dnnum_string(ndo, dnaddr)); /* punt */
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2646_0 |
crossvul-cpp_data_bad_702_0 | /*
* SSLv3/TLSv1 client-side functions
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_SSL_CLI_C)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#include "mbedtls/debug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/ssl_internal.h"
#include <string.h>
#include <stdint.h>
#if defined(MBEDTLS_HAVE_TIME)
#include "mbedtls/platform_time.h"
#endif
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = v; while( n-- ) *p++ = 0;
}
#endif
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
static void ssl_write_hostname_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t hostname_len;
*olen = 0;
if( ssl->hostname == NULL )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding server name extension: %s",
ssl->hostname ) );
hostname_len = strlen( ssl->hostname );
if( end < p || (size_t)( end - p ) < hostname_len + 9 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Sect. 3, RFC 6066 (TLS Extensions Definitions)
*
* In order to provide any of the server names, clients MAY include an
* extension of type "server_name" in the (extended) client hello. The
* "extension_data" field of this extension SHALL contain
* "ServerNameList" where:
*
* struct {
* NameType name_type;
* select (name_type) {
* case host_name: HostName;
* } name;
* } ServerName;
*
* enum {
* host_name(0), (255)
* } NameType;
*
* opaque HostName<1..2^16-1>;
*
* struct {
* ServerName server_name_list<1..2^16-1>
* } ServerNameList;
*
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 5) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 5) ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 3) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 3) ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) & 0xFF );
*p++ = (unsigned char)( ( hostname_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( hostname_len ) & 0xFF );
memcpy( p, ssl->hostname, hostname_len );
*olen = hostname_len + 9;
}
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
#if defined(MBEDTLS_SSL_RENEGOTIATION)
static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
/* We're always including an TLS_EMPTY_RENEGOTIATION_INFO_SCSV in the
* initial ClientHello, in which case also adding the renegotiation
* info extension is NOT RECOMMENDED as per RFC 5746 Section 3.4. */
if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding renegotiation extension" ) );
if( end < p || (size_t)( end - p ) < 5 + ssl->verify_data_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Secure renegotiation
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO ) & 0xFF );
*p++ = 0x00;
*p++ = ( ssl->verify_data_len + 1 ) & 0xFF;
*p++ = ssl->verify_data_len & 0xFF;
memcpy( p, ssl->own_verify_data, ssl->verify_data_len );
*olen = 5 + ssl->verify_data_len;
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
/*
* Only if we handle at least one key exchange that needs signatures.
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
static void ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t sig_alg_len = 0;
const int *md;
#if defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C)
unsigned char *sig_alg_list = buf + 6;
#endif
*olen = 0;
if( ssl->conf->max_minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding signature_algorithms extension" ) );
for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
{
#if defined(MBEDTLS_ECDSA_C)
sig_alg_len += 2;
#endif
#if defined(MBEDTLS_RSA_C)
sig_alg_len += 2;
#endif
}
if( end < p || (size_t)( end - p ) < sig_alg_len + 6 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Prepare signature_algorithms extension (TLS 1.2)
*/
sig_alg_len = 0;
for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
{
#if defined(MBEDTLS_ECDSA_C)
sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_ECDSA;
#endif
#if defined(MBEDTLS_RSA_C)
sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_RSA;
#endif
}
/*
* enum {
* none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),
* sha512(6), (255)
* } HashAlgorithm;
*
* enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
* SignatureAlgorithm;
*
* struct {
* HashAlgorithm hash;
* SignatureAlgorithm signature;
* } SignatureAndHashAlgorithm;
*
* SignatureAndHashAlgorithm
* supported_signature_algorithms<2..2^16-2>;
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG ) & 0xFF );
*p++ = (unsigned char)( ( ( sig_alg_len + 2 ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( sig_alg_len + 2 ) ) & 0xFF );
*p++ = (unsigned char)( ( sig_alg_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( sig_alg_len ) & 0xFF );
*olen = 6 + sig_alg_len;
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static void ssl_write_supported_elliptic_curves_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
unsigned char *elliptic_curve_list = p + 6;
size_t elliptic_curve_len = 0;
const mbedtls_ecp_curve_info *info;
#if defined(MBEDTLS_ECP_C)
const mbedtls_ecp_group_id *grp_id;
#else
((void) ssl);
#endif
*olen = 0;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_elliptic_curves extension" ) );
#if defined(MBEDTLS_ECP_C)
for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )
#else
for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ )
#endif
{
#if defined(MBEDTLS_ECP_C)
info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
#endif
if( info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid curve in ssl configuration" ) );
return;
}
elliptic_curve_len += 2;
}
if( end < p || (size_t)( end - p ) < 6 + elliptic_curve_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
elliptic_curve_len = 0;
#if defined(MBEDTLS_ECP_C)
for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )
#else
for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ )
#endif
{
#if defined(MBEDTLS_ECP_C)
info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
#endif
elliptic_curve_list[elliptic_curve_len++] = info->tls_id >> 8;
elliptic_curve_list[elliptic_curve_len++] = info->tls_id & 0xFF;
}
if( elliptic_curve_len == 0 )
return;
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len ) ) & 0xFF );
*olen = 6 + elliptic_curve_len;
}
static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_point_formats extension" ) );
if( end < p || (size_t)( end - p ) < 6 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS ) & 0xFF );
*p++ = 0x00;
*p++ = 2;
*p++ = 1;
*p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
*olen = 6;
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
int ret;
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t kkpp_len;
*olen = 0;
/* Skip costly extension if we can't use EC J-PAKE anyway */
if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding ecjpake_kkpp extension" ) );
if( end - p < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP ) & 0xFF );
/*
* We may need to send ClientHello multiple times for Hello verification.
* We don't want to compute fresh values every time (both for performance
* and consistency reasons), so cache the extension content.
*/
if( ssl->handshake->ecjpake_cache == NULL ||
ssl->handshake->ecjpake_cache_len == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "generating new ecjpake parameters" ) );
ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,
p + 2, end - p - 2, &kkpp_len,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret );
return;
}
ssl->handshake->ecjpake_cache = mbedtls_calloc( 1, kkpp_len );
if( ssl->handshake->ecjpake_cache == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "allocation failed" ) );
return;
}
memcpy( ssl->handshake->ecjpake_cache, p + 2, kkpp_len );
ssl->handshake->ecjpake_cache_len = kkpp_len;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "re-using cached ecjpake parameters" ) );
kkpp_len = ssl->handshake->ecjpake_cache_len;
if( (size_t)( end - p - 2 ) < kkpp_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
memcpy( p + 2, ssl->handshake->ecjpake_cache, kkpp_len );
}
*p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( kkpp_len ) & 0xFF );
*olen = kkpp_len + 4;
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) {
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding max_fragment_length extension" ) );
if( end < p || (size_t)( end - p ) < 5 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH ) & 0xFF );
*p++ = 0x00;
*p++ = 1;
*p++ = ssl->conf->mfl_code;
*olen = 5;
}
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding truncated_hmac extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding encrypt_then_mac "
"extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding extended_master_secret "
"extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t tlen = ssl->session_negotiate->ticket_len;
*olen = 0;
if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding session ticket extension" ) );
if( end < p || (size_t)( end - p ) < 4 + tlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET ) & 0xFF );
*p++ = (unsigned char)( ( tlen >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( tlen ) & 0xFF );
*olen = 4;
if( ssl->session_negotiate->ticket == NULL || tlen == 0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "sending session ticket of length %d", tlen ) );
memcpy( p, ssl->session_negotiate->ticket, tlen );
*olen += tlen;
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_SSL_ALPN)
static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t alpnlen = 0;
const char **cur;
*olen = 0;
if( ssl->conf->alpn_list == NULL )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding alpn extension" ) );
for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
alpnlen += (unsigned char)( strlen( *cur ) & 0xFF ) + 1;
if( end < p || (size_t)( end - p ) < 6 + alpnlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN ) & 0xFF );
/*
* opaque ProtocolName<1..2^8-1>;
*
* struct {
* ProtocolName protocol_name_list<2..2^16-1>
* } ProtocolNameList;
*/
/* Skip writing extension and list length for now */
p += 4;
for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
{
*p = (unsigned char)( strlen( *cur ) & 0xFF );
memcpy( p + 1, *cur, *p );
p += 1 + *p;
}
*olen = p - buf;
/* List length = olen - 2 (ext_type) - 2 (ext_len) - 2 (list_len) */
buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF );
buf[5] = (unsigned char)( ( ( *olen - 6 ) ) & 0xFF );
/* Extension length = olen - 2 (ext_type) - 2 (ext_len) */
buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF );
buf[3] = (unsigned char)( ( ( *olen - 4 ) ) & 0xFF );
}
#endif /* MBEDTLS_SSL_ALPN */
/*
* Generate random bytes for ClientHello
*/
static int ssl_generate_random( mbedtls_ssl_context *ssl )
{
int ret;
unsigned char *p = ssl->handshake->randbytes;
#if defined(MBEDTLS_HAVE_TIME)
mbedtls_time_t t;
#endif
/*
* When responding to a verify request, MUST reuse random (RFC 6347 4.2.1)
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
ssl->handshake->verify_cookie != NULL )
{
return( 0 );
}
#endif
#if defined(MBEDTLS_HAVE_TIME)
t = mbedtls_time( NULL );
*p++ = (unsigned char)( t >> 24 );
*p++ = (unsigned char)( t >> 16 );
*p++ = (unsigned char)( t >> 8 );
*p++ = (unsigned char)( t );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, current time: %lu", t ) );
#else
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 )
return( ret );
p += 4;
#endif /* MBEDTLS_HAVE_TIME */
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 )
return( ret );
return( 0 );
}
static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
{
int ret;
size_t i, n, olen, ext_len = 0;
unsigned char *buf;
unsigned char *p, *q;
unsigned char offer_compress;
const int *ciphersuites;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client hello" ) );
if( ssl->conf->f_rng == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") );
return( MBEDTLS_ERR_SSL_NO_RNG );
}
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
ssl->major_ver = ssl->conf->min_major_ver;
ssl->minor_ver = ssl->conf->min_minor_ver;
}
if( ssl->conf->max_major_ver == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "configured max major version is invalid, "
"consider using mbedtls_ssl_config_defaults()" ) );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
/*
* 0 . 0 handshake type
* 1 . 3 handshake length
* 4 . 5 highest version supported
* 6 . 9 current UNIX time
* 10 . 37 random bytes
*/
buf = ssl->out_msg;
p = buf + 4;
mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
ssl->conf->transport, p );
p += 2;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, max version: [%d:%d]",
buf[4], buf[5] ) );
if( ( ret = ssl_generate_random( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_generate_random", ret );
return( ret );
}
memcpy( p, ssl->handshake->randbytes, 32 );
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", p, 32 );
p += 32;
/*
* 38 . 38 session id length
* 39 . 39+n session id
* 39+n . 39+n DTLS only: cookie length (1 byte)
* 40+n . .. DTSL only: cookie
* .. . .. ciphersuitelist length (2 bytes)
* .. . .. ciphersuitelist
* .. . .. compression methods length (1 byte)
* .. . .. compression methods
* .. . .. extensions length (2 bytes)
* .. . .. extensions
*/
n = ssl->session_negotiate->id_len;
if( n < 16 || n > 32 ||
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
#endif
ssl->handshake->resume == 0 )
{
n = 0;
}
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
/*
* RFC 5077 section 3.4: "When presenting a ticket, the client MAY
* generate and include a Session ID in the TLS ClientHello."
*/
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
if( ssl->session_negotiate->ticket != NULL &&
ssl->session_negotiate->ticket_len != 0 )
{
ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id, 32 );
if( ret != 0 )
return( ret );
ssl->session_negotiate->id_len = n = 32;
}
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
*p++ = (unsigned char) n;
for( i = 0; i < n; i++ )
*p++ = ssl->session_negotiate->id[i];
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, session id len.: %d", n ) );
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 39, n );
/*
* DTLS cookie
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
{
if( ssl->handshake->verify_cookie == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "no verify cookie to send" ) );
*p++ = 0;
}
else
{
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie",
ssl->handshake->verify_cookie,
ssl->handshake->verify_cookie_len );
*p++ = ssl->handshake->verify_cookie_len;
memcpy( p, ssl->handshake->verify_cookie,
ssl->handshake->verify_cookie_len );
p += ssl->handshake->verify_cookie_len;
}
}
#endif
/*
* Ciphersuite list
*/
ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
/* Skip writing ciphersuite length for now */
n = 0;
q = p;
p += 2;
for( i = 0; ciphersuites[i] != 0; i++ )
{
ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuites[i] );
if( ciphersuite_info == NULL )
continue;
if( ciphersuite_info->min_minor_ver > ssl->conf->max_minor_ver ||
ciphersuite_info->max_minor_ver < ssl->conf->min_minor_ver )
continue;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
( ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )
continue;
#endif
#if defined(MBEDTLS_ARC4_C)
if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
ciphersuite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
continue;
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
continue;
#endif
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, add ciphersuite: %04x",
ciphersuites[i] ) );
n++;
*p++ = (unsigned char)( ciphersuites[i] >> 8 );
*p++ = (unsigned char)( ciphersuites[i] );
}
/*
* Add TLS_EMPTY_RENEGOTIATION_INFO_SCSV
*/
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
*p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO >> 8 );
*p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO );
n++;
}
/* Some versions of OpenSSL don't handle it correctly if not at end */
#if defined(MBEDTLS_SSL_FALLBACK_SCSV)
if( ssl->conf->fallback == MBEDTLS_SSL_IS_FALLBACK )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding FALLBACK_SCSV" ) );
*p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 );
*p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE );
n++;
}
#endif
*q++ = (unsigned char)( n >> 7 );
*q++ = (unsigned char)( n << 1 );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, got %d ciphersuites", n ) );
#if defined(MBEDTLS_ZLIB_SUPPORT)
offer_compress = 1;
#else
offer_compress = 0;
#endif
/*
* We don't support compression with DTLS right now: is many records come
* in the same datagram, uncompressing one could overwrite the next one.
* We don't want to add complexity for handling that case unless there is
* an actual need for it.
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
offer_compress = 0;
#endif
if( offer_compress )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 2 ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d %d",
MBEDTLS_SSL_COMPRESS_DEFLATE, MBEDTLS_SSL_COMPRESS_NULL ) );
*p++ = 2;
*p++ = MBEDTLS_SSL_COMPRESS_DEFLATE;
*p++ = MBEDTLS_SSL_COMPRESS_NULL;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 1 ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d",
MBEDTLS_SSL_COMPRESS_NULL ) );
*p++ = 1;
*p++ = MBEDTLS_SSL_COMPRESS_NULL;
}
// First write extensions, then the total length
//
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
ssl_write_hostname_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
/* Note that TLS_EMPTY_RENEGOTIATION_INFO_SCSV is always added
* even if MBEDTLS_SSL_RENEGOTIATION is not defined. */
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
ssl_write_signature_algorithms_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_ALPN)
ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
/* olen unused if all extensions are disabled */
((void) olen);
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, total extension length: %d",
ext_len ) );
if( ext_len > 0 )
{
*p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ext_len ) & 0xFF );
p += ext_len;
}
ssl->out_msglen = p - buf;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CLIENT_HELLO;
ssl->state++;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
mbedtls_ssl_send_flight_completed( ssl );
#endif
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client hello" ) );
return( 0 );
}
static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
{
/* Check verify-data in constant-time. The length OTOH is no secret */
if( len != 1 + ssl->verify_data_len * 2 ||
buf[0] != ssl->verify_data_len * 2 ||
mbedtls_ssl_safer_memcmp( buf + 1,
ssl->own_verify_data, ssl->verify_data_len ) != 0 ||
mbedtls_ssl_safer_memcmp( buf + 1 + ssl->verify_data_len,
ssl->peer_verify_data, ssl->verify_data_len ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
else
#endif /* MBEDTLS_SSL_RENEGOTIATION */
{
if( len != 1 || buf[0] != 0x00 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
}
return( 0 );
}
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
/*
* server should use the extension only if we did,
* and if so the server's value should match ours (and len is always 1)
*/
if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ||
len != 1 ||
buf[0] != ssl->conf->mfl_code )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching max fragment length extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
return( 0 );
}
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching truncated HMAC extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching encrypt-then-MAC extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching extended master secret extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching session ticket extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->handshake->new_session_ticket = 1;
return( 0 );
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
size_t list_size;
const unsigned char *p;
list_size = buf[0];
if( list_size + 1 != len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
p = buf + 1;
while( list_size > 0 )
{
if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
p[0] == MBEDTLS_ECP_PF_COMPRESSED )
{
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
ssl->handshake->ecdh_ctx.point_format = p[0];
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl->handshake->ecjpake_ctx.point_format = p[0];
#endif
MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
return( 0 );
}
list_size--;
p++;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "no point format in common" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
int ret;
if( ssl->transform_negotiate->ciphersuite_info->key_exchange !=
MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) );
return( 0 );
}
/* If we got here, we no longer need our cached extension */
mbedtls_free( ssl->handshake->ecjpake_cache );
ssl->handshake->ecjpake_cache = NULL;
ssl->handshake->ecjpake_cache_len = 0;
if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,
buf, len ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_ALPN)
static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf, size_t len )
{
size_t list_len, name_len;
const char **p;
/* If we didn't send it, the server shouldn't send it */
if( ssl->conf->alpn_list == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching ALPN extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/*
* opaque ProtocolName<1..2^8-1>;
*
* struct {
* ProtocolName protocol_name_list<2..2^16-1>
* } ProtocolNameList;
*
* the "ProtocolNameList" MUST contain exactly one "ProtocolName"
*/
/* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
if( len < 4 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
list_len = ( buf[0] << 8 ) | buf[1];
if( list_len != len - 2 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
name_len = buf[2];
if( name_len != list_len - 1 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/* Check that the server chosen protocol was in our list and save it */
for( p = ssl->conf->alpn_list; *p != NULL; p++ )
{
if( name_len == strlen( *p ) &&
memcmp( buf + 3, *p, name_len ) == 0 )
{
ssl->alpn_chosen = *p;
return( 0 );
}
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ALPN extension: no matching protocol" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
#endif /* MBEDTLS_SSL_ALPN */
/*
* Parse HelloVerifyRequest. Only called after verifying the HS type.
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
static int ssl_parse_hello_verify_request( mbedtls_ssl_context *ssl )
{
const unsigned char *p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
int major_ver, minor_ver;
unsigned char cookie_len;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse hello verify request" ) );
/*
* struct {
* ProtocolVersion server_version;
* opaque cookie<0..2^8-1>;
* } HelloVerifyRequest;
*/
MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 );
mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, p );
p += 2;
/*
* Since the RFC is not clear on this point, accept DTLS 1.0 (TLS 1.1)
* even is lower than our min version.
*/
if( major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 ||
minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ||
major_ver > ssl->conf->max_major_ver ||
minor_ver > ssl->conf->max_minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server version" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
}
cookie_len = *p++;
MBEDTLS_SSL_DEBUG_BUF( 3, "cookie", p, cookie_len );
if( ( ssl->in_msg + ssl->in_msglen ) - p < cookie_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1,
( "cookie length does not match incoming message size" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
mbedtls_free( ssl->handshake->verify_cookie );
ssl->handshake->verify_cookie = mbedtls_calloc( 1, cookie_len );
if( ssl->handshake->verify_cookie == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", cookie_len ) );
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
}
memcpy( ssl->handshake->verify_cookie, p, cookie_len );
ssl->handshake->verify_cookie_len = cookie_len;
/* Start over at ClientHello */
ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
mbedtls_ssl_reset_checksum( ssl );
mbedtls_ssl_recv_flight_completed( ssl );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse hello verify request" ) );
return( 0 );
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
{
int ret, i;
size_t n;
size_t ext_len;
unsigned char *buf, *ext;
unsigned char comp;
#if defined(MBEDTLS_ZLIB_SUPPORT)
int accept_comp;
#endif
#if defined(MBEDTLS_SSL_RENEGOTIATION)
int renegotiation_info_seen = 0;
#endif
int handshake_failure = 0;
const mbedtls_ssl_ciphersuite_t *suite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello" ) );
buf = ssl->in_msg;
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
/* No alert on a read error. */
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
{
ssl->renego_records_seen++;
if( ssl->conf->renego_max_records >= 0 &&
ssl->renego_records_seen > ssl->conf->renego_max_records )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
"but not honored by server" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-handshake message during renego" ) );
ssl->keep_current_message = 1;
return( MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO );
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
{
if( buf[0] == MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "received hello verify request" ) );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
return( ssl_parse_hello_verify_request( ssl ) );
}
else
{
/* We made it through the verification process */
mbedtls_free( ssl->handshake->verify_cookie );
ssl->handshake->verify_cookie = NULL;
ssl->handshake->verify_cookie_len = 0;
}
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
if( ssl->in_hslen < 38 + mbedtls_ssl_hs_hdr_len( ssl ) ||
buf[0] != MBEDTLS_SSL_HS_SERVER_HELLO )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/*
* 0 . 1 server_version
* 2 . 33 random (maybe including 4 bytes of Unix time)
* 34 . 34 session_id length = n
* 35 . 34+n session_id
* 35+n . 36+n cipher_suite
* 37+n . 37+n compression_method
*
* 38+n . 39+n extensions length (optional)
* 40+n . .. extensions
*/
buf += mbedtls_ssl_hs_hdr_len( ssl );
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, version", buf + 0, 2 );
mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver,
ssl->conf->transport, buf + 0 );
if( ssl->major_ver < ssl->conf->min_major_ver ||
ssl->minor_ver < ssl->conf->min_minor_ver ||
ssl->major_ver > ssl->conf->max_major_ver ||
ssl->minor_ver > ssl->conf->max_minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server version out of bounds - "
" min: [%d:%d], server: [%d:%d], max: [%d:%d]",
ssl->conf->min_major_ver, ssl->conf->min_minor_ver,
ssl->major_ver, ssl->minor_ver,
ssl->conf->max_major_ver, ssl->conf->max_minor_ver ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu",
( (uint32_t) buf[2] << 24 ) |
( (uint32_t) buf[3] << 16 ) |
( (uint32_t) buf[4] << 8 ) |
( (uint32_t) buf[5] ) ) );
memcpy( ssl->handshake->randbytes + 32, buf + 2, 32 );
n = buf[34];
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf + 2, 32 );
if( n > 32 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
if( ssl->in_hslen > mbedtls_ssl_hs_hdr_len( ssl ) + 39 + n )
{
ext_len = ( ( buf[38 + n] << 8 )
| ( buf[39 + n] ) );
if( ( ext_len > 0 && ext_len < 4 ) ||
ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 40 + n + ext_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
else if( ssl->in_hslen == mbedtls_ssl_hs_hdr_len( ssl ) + 38 + n )
{
ext_len = 0;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/* ciphersuite (used later) */
i = ( buf[35 + n] << 8 ) | buf[36 + n];
/*
* Read and check compression
*/
comp = buf[37 + n];
#if defined(MBEDTLS_ZLIB_SUPPORT)
/* See comments in ssl_write_client_hello() */
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
accept_comp = 0;
else
#endif
accept_comp = 1;
if( comp != MBEDTLS_SSL_COMPRESS_NULL &&
( comp != MBEDTLS_SSL_COMPRESS_DEFLATE || accept_comp == 0 ) )
#else /* MBEDTLS_ZLIB_SUPPORT */
if( comp != MBEDTLS_SSL_COMPRESS_NULL )
#endif/* MBEDTLS_ZLIB_SUPPORT */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server hello, bad compression: %d", comp ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
}
/*
* Initialize update checksum functions
*/
ssl->transform_negotiate->ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( i );
if( ssl->transform_negotiate->ciphersuite_info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %04x not found", i ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
mbedtls_ssl_optimize_checksum( ssl, ssl->transform_negotiate->ciphersuite_info );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %d", n ) );
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, session id", buf + 35, n );
/*
* Check if the session can be resumed
*/
if( ssl->handshake->resume == 0 || n == 0 ||
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
#endif
ssl->session_negotiate->ciphersuite != i ||
ssl->session_negotiate->compression != comp ||
ssl->session_negotiate->id_len != n ||
memcmp( ssl->session_negotiate->id, buf + 35, n ) != 0 )
{
ssl->state++;
ssl->handshake->resume = 0;
#if defined(MBEDTLS_HAVE_TIME)
ssl->session_negotiate->start = mbedtls_time( NULL );
#endif
ssl->session_negotiate->ciphersuite = i;
ssl->session_negotiate->compression = comp;
ssl->session_negotiate->id_len = n;
memcpy( ssl->session_negotiate->id, buf + 35, n );
}
else
{
ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( ret );
}
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed",
ssl->handshake->resume ? "a" : "no" ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %04x", i ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d", buf[37 + n] ) );
suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite );
if( suite_info == NULL
#if defined(MBEDTLS_ARC4_C)
|| ( ssl->conf->arc4_disabled &&
suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
#endif
)
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) );
i = 0;
while( 1 )
{
if( ssl->conf->ciphersuite_list[ssl->minor_ver][i] == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
if( ssl->conf->ciphersuite_list[ssl->minor_ver][i++] ==
ssl->session_negotiate->ciphersuite )
{
break;
}
}
if( comp != MBEDTLS_SSL_COMPRESS_NULL
#if defined(MBEDTLS_ZLIB_SUPPORT)
&& comp != MBEDTLS_SSL_COMPRESS_DEFLATE
#endif
)
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
ssl->session_negotiate->compression = comp;
ext = buf + 40 + n;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "server hello, total extension length: %d", ext_len ) );
while( ext_len )
{
unsigned int ext_id = ( ( ext[0] << 8 )
| ( ext[1] ) );
unsigned int ext_size = ( ( ext[2] << 8 )
| ( ext[3] ) );
if( ext_size + 4 > ext_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
switch( ext_id )
{
case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) );
#if defined(MBEDTLS_SSL_RENEGOTIATION)
renegotiation_info_seen = 1;
#endif
if( ( ret = ssl_parse_renegotiation_info( ssl, ext + 4,
ext_size ) ) != 0 )
return( ret );
break;
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max_fragment_length extension" ) );
if( ( ret = ssl_parse_max_fragment_length_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated_hmac extension" ) );
if( ( ret = ssl_parse_truncated_hmac_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt_then_mac extension" ) );
if( ( ret = ssl_parse_encrypt_then_mac_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended_master_secret extension" ) );
if( ( ret = ssl_parse_extended_ms_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
case MBEDTLS_TLS_EXT_SESSION_TICKET:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session_ticket extension" ) );
if( ( ret = ssl_parse_session_ticket_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported_point_formats extension" ) );
if( ( ret = ssl_parse_supported_point_formats_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake_kkpp extension" ) );
if( ( ret = ssl_parse_ecjpake_kkpp( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_ALPN)
case MBEDTLS_TLS_EXT_ALPN:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) );
if( ( ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ) ) != 0 )
return( ret );
break;
#endif /* MBEDTLS_SSL_ALPN */
default:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d (ignoring)",
ext_id ) );
}
ext_len -= 4 + ext_size;
ext += 4 + ext_size;
if( ext_len > 0 && ext_len < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
/*
* Renegotiation security checks
*/
if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
handshake_failure = 1;
}
#if defined(MBEDTLS_SSL_RENEGOTIATION)
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
renegotiation_info_seen == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) );
handshake_failure = 1;
}
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) );
handshake_failure = 1;
}
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
renegotiation_info_seen == 1 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) );
handshake_failure = 1;
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
if( handshake_failure == 1 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
return( 0 );
}
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
static int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl, unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
/*
* Ephemeral DH parameters:
*
* struct {
* opaque dh_p<1..2^16-1>;
* opaque dh_g<1..2^16-1>;
* opaque dh_Ys<1..2^16-1>;
* } ServerDHParams;
*/
if( ( ret = mbedtls_dhm_read_params( &ssl->handshake->dhm_ctx, p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 2, ( "mbedtls_dhm_read_params" ), ret );
return( ret );
}
if( ssl->handshake->dhm_ctx.len * 8 < ssl->conf->dhm_min_bitlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "DHM prime too short: %d < %d",
ssl->handshake->dhm_ctx.len * 8,
ssl->conf->dhm_min_bitlen ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY );
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
static int ssl_check_server_ecdh_params( const mbedtls_ssl_context *ssl )
{
const mbedtls_ecp_curve_info *curve_info;
curve_info = mbedtls_ecp_curve_info_from_grp_id( ssl->handshake->ecdh_ctx.grp.id );
if( curve_info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDH curve: %s", curve_info->name ) );
#if defined(MBEDTLS_ECP_C)
if( mbedtls_ssl_check_curve( ssl, ssl->handshake->ecdh_ctx.grp.id ) != 0 )
#else
if( ssl->handshake->ecdh_ctx.grp.nbits < 163 ||
ssl->handshake->ecdh_ctx.grp.nbits > 521 )
#endif
return( -1 );
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Qp", &ssl->handshake->ecdh_ctx.Qp );
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
static int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
/*
* Ephemeral ECDH parameters:
*
* struct {
* ECParameters curve_params;
* ECPoint public;
* } ServerECDHParams;
*/
if( ( ret = mbedtls_ecdh_read_params( &ssl->handshake->ecdh_ctx,
(const unsigned char **) p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_read_params" ), ret );
return( ret );
}
if( ssl_check_server_ecdh_params( ssl ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (ECDHE curve)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
/*
* Generate a pre-master secret and encrypt it with the server's RSA key
*/
static int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl,
size_t offset, size_t *olen,
size_t pms_offset )
{
int ret;
size_t len_bytes = ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2;
unsigned char *p = ssl->handshake->premaster + pms_offset;
if( offset + len_bytes > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small for encrypted pms" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
/*
* Generate (part of) the pre-master as
* struct {
* ProtocolVersion client_version;
* opaque random[46];
* } PreMasterSecret;
*/
mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
ssl->conf->transport, p );
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p + 2, 46 ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "f_rng", ret );
return( ret );
}
ssl->handshake->pmslen = 48;
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Now write it out, encrypted
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
MBEDTLS_PK_RSA ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate key type mismatch" ) );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_encrypt( &ssl->session_negotiate->peer_cert->pk,
p, ssl->handshake->pmslen,
ssl->out_msg + offset + len_bytes, olen,
MBEDTLS_SSL_MAX_CONTENT_LEN - offset - len_bytes,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_rsa_pkcs1_encrypt", ret );
return( ret );
}
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( len_bytes == 2 )
{
ssl->out_msg[offset+0] = (unsigned char)( *olen >> 8 );
ssl->out_msg[offset+1] = (unsigned char)( *olen );
*olen += 2;
}
#endif
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
static int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end,
mbedtls_md_type_t *md_alg,
mbedtls_pk_type_t *pk_alg )
{
((void) ssl);
*md_alg = MBEDTLS_MD_NONE;
*pk_alg = MBEDTLS_PK_NONE;
/* Only in TLS 1.2 */
if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
{
return( 0 );
}
if( (*p) + 2 > end )
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
/*
* Get hash algorithm
*/
if( ( *md_alg = mbedtls_ssl_md_alg_from_hash( (*p)[0] ) ) == MBEDTLS_MD_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "Server used unsupported "
"HashAlgorithm %d", *(p)[0] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Get signature algorithm
*/
if( ( *pk_alg = mbedtls_ssl_pk_alg_from_sig( (*p)[1] ) ) == MBEDTLS_PK_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used unsupported "
"SignatureAlgorithm %d", (*p)[1] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Check if the hash is acceptable
*/
if( mbedtls_ssl_check_sig_hash( ssl, *md_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used HashAlgorithm %d that was not offered",
*(p)[0] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used SignatureAlgorithm %d", (*p)[1] ) );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used HashAlgorithm %d", (*p)[0] ) );
*p += 2;
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ecp_keypair *peer_key;
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
MBEDTLS_PK_ECKEY ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
peer_key = mbedtls_pk_ec( ssl->session_negotiate->peer_cert->pk );
if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, peer_key,
MBEDTLS_ECDH_THEIRS ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret );
return( ret );
}
if( ssl_check_server_ecdh_params( ssl ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server certificate (ECDH curve)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
}
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
unsigned char *p = NULL, *end = NULL;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
* doesn't use a psk_identity_hint
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
{
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
/* Current message is probably either
* CertificateRequest or ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must "
"not be skipped" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
end = ssl->in_msg + ssl->in_hslen;
MBEDTLS_SSL_DEBUG_BUF( 3, "server key exchange", p, end - p );
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
} /* FALLTROUGH */
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
; /* nothing more to do */
else
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
{
if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
p, end - p );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
{
size_t sig_len, hashlen;
unsigned char hash[64];
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
size_t params_len = p - params;
/*
* Handle the digitally-signed structure
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
if( ssl_parse_signature_algorithm( ssl, &p, end,
&md_alg, &pk_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
{
pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
/* Default hash for ECDSA is SHA-1 */
if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )
md_alg = MBEDTLS_MD_SHA1;
}
else
#endif
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
/*
* Read signature
*/
sig_len = ( p[0] << 8 ) | p[1];
p += 2;
if( end != p + sig_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
/*
* Compute the hash that has been signed
*/
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( md_alg == MBEDTLS_MD_NONE )
{
hashlen = 36;
ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params,
params_len );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( md_alg != MBEDTLS_MD_NONE )
{
/* Info from md_alg will be used instead */
hashlen = 0;
ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params,
params_len, md_alg );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen :
(unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Verify signature
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
md_alg, hash, hashlen, p, sig_len ) ) != 0 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
return( ret );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
exit:
ssl->state++;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
return( 0 );
}
#if ! defined(MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED)
static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
{
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
ssl->state++;
return( 0 );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#else /* MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED */
static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
{
int ret;
unsigned char *buf;
size_t n = 0;
size_t cert_type_len = 0, dn_len = 0;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
ssl->state++;
return( 0 );
}
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
ssl->state++;
ssl->client_auth = ( ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "got %s certificate request",
ssl->client_auth ? "a" : "no" ) );
if( ssl->client_auth == 0 )
{
/* Current message is probably the ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
/*
* struct {
* ClientCertificateType certificate_types<1..2^8-1>;
* SignatureAndHashAlgorithm
* supported_signature_algorithms<2^16-1>; -- TLS 1.2 only
* DistinguishedName certificate_authorities<0..2^16-1>;
* } CertificateRequest;
*
* Since we only support a single certificate on clients, let's just
* ignore all the information that's supposed to help us pick a
* certificate.
*
* We could check that our certificate matches the request, and bail out
* if it doesn't, but it's simpler to just send the certificate anyway,
* and give the server the opportunity to decide if it should terminate
* the connection when it doesn't like our certificate.
*
* Same goes for the hash in TLS 1.2's signature_algorithms: at this
* point we only have one hash available (see comments in
* write_certificate_verify), so let's just use what we have.
*
* However, we still minimally parse the message to check it is at least
* superficially sane.
*/
buf = ssl->in_msg;
/* certificate_types */
cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )];
n = cert_type_len;
if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
/* supported_signature_algorithms */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
size_t sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 )
| ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) );
#if defined(MBEDTLS_DEBUG_C)
unsigned char* sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n;
size_t i;
for( i = 0; i < sig_alg_len; i += 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "Supported Signature Algorithm found: %d"
",%d", sig_alg[i], sig_alg[i + 1] ) );
}
#endif
n += 2 + sig_alg_len;
if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
/* certificate_authorities */
dn_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 )
| ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) );
n += dn_len;
if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
exit:
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate request" ) );
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED */
static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl )
{
int ret;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello done" ) );
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ||
ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_HELLO_DONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE );
}
ssl->state++;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
mbedtls_ssl_recv_flight_completed( ssl );
#endif
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello done" ) );
return( 0 );
}
static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
size_t i, n;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )
{
/*
* DHM key exchange -- send G^X mod P
*/
n = ssl->handshake->dhm_ctx.len;
ssl->out_msg[4] = (unsigned char)( n >> 8 );
ssl->out_msg[5] = (unsigned char)( n );
i = 6;
ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
(int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
&ssl->out_msg[i], n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX );
if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
ssl->handshake->premaster,
MBEDTLS_PREMASTER_SIZE,
&ssl->handshake->pmslen,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
/*
* ECDH key exchange -- send client public value
*/
i = 4;
ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx,
&n,
&ssl->out_msg[i], 1000,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,
&ssl->handshake->pmslen,
ssl->handshake->premaster,
MBEDTLS_MPI_MAX_SIZE,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( mbedtls_ssl_ciphersuite_uses_psk( ciphersuite_info ) )
{
/*
* opaque psk_identity<0..2^16-1>;
*/
if( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for PSK" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
i = 4;
n = ssl->conf->psk_identity_len;
if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity too long or "
"SSL buffer too short" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
ssl->out_msg[i++] = (unsigned char)( n >> 8 );
ssl->out_msg[i++] = (unsigned char)( n );
memcpy( ssl->out_msg + i, ssl->conf->psk_identity, ssl->conf->psk_identity_len );
i += ssl->conf->psk_identity_len;
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )
{
n = 0;
}
else
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 2 ) ) != 0 )
return( ret );
}
else
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
/*
* ClientDiffieHellmanPublic public (DHM send G^X mod P)
*/
n = ssl->handshake->dhm_ctx.len;
if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity or DHM size too long"
" or SSL buffer too short" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
ssl->out_msg[i++] = (unsigned char)( n >> 8 );
ssl->out_msg[i++] = (unsigned char)( n );
ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
(int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
&ssl->out_msg[i], n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
/*
* ClientECDiffieHellmanPublic public;
*/
ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx, &n,
&ssl->out_msg[i], MBEDTLS_SSL_MAX_CONTENT_LEN - i,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
ciphersuite_info->key_exchange ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
i = 4;
if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 0 ) ) != 0 )
return( ret );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
i = 4;
ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx,
ssl->out_msg + i, MBEDTLS_SSL_MAX_CONTENT_LEN - i, &n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret );
return( ret );
}
ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,
ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
{
((void) ciphersuite_info);
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
ssl->out_msglen = i + n;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE;
ssl->state++;
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client key exchange" ) );
return( 0 );
}
#if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \
!defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
{
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
int ret;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
return( ret );
}
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#else
static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
size_t n = 0, offset = 0;
unsigned char hash[48];
unsigned char *hash_start = hash;
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
unsigned int hashlen;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
return( ret );
}
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
if( ssl->client_auth == 0 || mbedtls_ssl_own_cert( ssl ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
if( mbedtls_ssl_own_key( ssl ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for certificate" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
/*
* Make an RSA signature of the handshake digests
*/
ssl->handshake->calc_verify( ssl, hash );
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
{
/*
* digitally-signed struct {
* opaque md5_hash[16];
* opaque sha_hash[20];
* };
*
* md5_hash
* MD5(handshake_messages);
*
* sha_hash
* SHA(handshake_messages);
*/
hashlen = 36;
md_alg = MBEDTLS_MD_NONE;
/*
* For ECDSA, default hash is SHA-1 only
*/
if( mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECDSA ) )
{
hash_start += 16;
hashlen -= 16;
md_alg = MBEDTLS_MD_SHA1;
}
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
/*
* digitally-signed struct {
* opaque handshake_messages[handshake_messages_length];
* };
*
* Taking shortcut here. We assume that the server always allows the
* PRF Hash function and has sent it in the allowed signature
* algorithms list received in the Certificate Request message.
*
* Until we encounter a server that does not, we will take this
* shortcut.
*
* Reason: Otherwise we should have running hashes for SHA512 and SHA224
* in order to satisfy 'weird' needs from the server side.
*/
if( ssl->transform_negotiate->ciphersuite_info->mac ==
MBEDTLS_MD_SHA384 )
{
md_alg = MBEDTLS_MD_SHA384;
ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA384;
}
else
{
md_alg = MBEDTLS_MD_SHA256;
ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA256;
}
ssl->out_msg[5] = mbedtls_ssl_sig_from_pk( mbedtls_ssl_own_key( ssl ) );
/* Info from md_alg will be used instead */
hashlen = 0;
offset = 2;
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ), md_alg, hash_start, hashlen,
ssl->out_msg + 6 + offset, &n,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret );
return( ret );
}
ssl->out_msg[4 + offset] = (unsigned char)( n >> 8 );
ssl->out_msg[5 + offset] = (unsigned char)( n );
ssl->out_msglen = 6 + n + offset;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE_VERIFY;
ssl->state++;
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate verify" ) );
return( ret );
}
#endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl )
{
int ret;
uint32_t lifetime;
size_t ticket_len;
unsigned char *ticket;
const unsigned char *msg;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse new session ticket" ) );
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* struct {
* uint32 ticket_lifetime_hint;
* opaque ticket<0..2^16-1>;
* } NewSessionTicket;
*
* 0 . 3 ticket_lifetime_hint
* 4 . 5 ticket_len (n)
* 6 . 5+n ticket content
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET ||
ssl->in_hslen < 6 + mbedtls_ssl_hs_hdr_len( ssl ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
}
msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
lifetime = ( msg[0] << 24 ) | ( msg[1] << 16 ) |
( msg[2] << 8 ) | ( msg[3] );
ticket_len = ( msg[4] << 8 ) | ( msg[5] );
if( ticket_len + 6 + mbedtls_ssl_hs_hdr_len( ssl ) != ssl->in_hslen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", ticket_len ) );
/* We're not waiting for a NewSessionTicket message any more */
ssl->handshake->new_session_ticket = 0;
ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
/*
* Zero-length ticket means the server changed his mind and doesn't want
* to send a ticket after all, so just forget it
*/
if( ticket_len == 0 )
return( 0 );
mbedtls_zeroize( ssl->session_negotiate->ticket,
ssl->session_negotiate->ticket_len );
mbedtls_free( ssl->session_negotiate->ticket );
ssl->session_negotiate->ticket = NULL;
ssl->session_negotiate->ticket_len = 0;
if( ( ticket = mbedtls_calloc( 1, ticket_len ) ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ticket alloc failed" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
}
memcpy( ticket, msg + 6, ticket_len );
ssl->session_negotiate->ticket = ticket;
ssl->session_negotiate->ticket_len = ticket_len;
ssl->session_negotiate->ticket_lifetime = lifetime;
/*
* RFC 5077 section 3.4:
* "If the client receives a session ticket from the server, then it
* discards any Session ID that was sent in the ServerHello."
*/
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket in use, discarding session id" ) );
ssl->session_negotiate->id_len = 0;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse new session ticket" ) );
return( 0 );
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
/*
* SSL handshake -- client side -- single step
*/
int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl )
{
int ret = 0;
if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "client state: %d", ssl->state ) );
if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
return( ret );
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
{
if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
return( ret );
}
#endif
/* Change state now, so that it is right in mbedtls_ssl_read_record(), used
* by DTLS for dropping out-of-sequence ChangeCipherSpec records */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
if( ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC &&
ssl->handshake->new_session_ticket != 0 )
{
ssl->state = MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET;
}
#endif
switch( ssl->state )
{
case MBEDTLS_SSL_HELLO_REQUEST:
ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
break;
/*
* ==> ClientHello
*/
case MBEDTLS_SSL_CLIENT_HELLO:
ret = ssl_write_client_hello( ssl );
break;
/*
* <== ServerHello
* Certificate
* ( ServerKeyExchange )
* ( CertificateRequest )
* ServerHelloDone
*/
case MBEDTLS_SSL_SERVER_HELLO:
ret = ssl_parse_server_hello( ssl );
break;
case MBEDTLS_SSL_SERVER_CERTIFICATE:
ret = mbedtls_ssl_parse_certificate( ssl );
break;
case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
ret = ssl_parse_server_key_exchange( ssl );
break;
case MBEDTLS_SSL_CERTIFICATE_REQUEST:
ret = ssl_parse_certificate_request( ssl );
break;
case MBEDTLS_SSL_SERVER_HELLO_DONE:
ret = ssl_parse_server_hello_done( ssl );
break;
/*
* ==> ( Certificate/Alert )
* ClientKeyExchange
* ( CertificateVerify )
* ChangeCipherSpec
* Finished
*/
case MBEDTLS_SSL_CLIENT_CERTIFICATE:
ret = mbedtls_ssl_write_certificate( ssl );
break;
case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
ret = ssl_write_client_key_exchange( ssl );
break;
case MBEDTLS_SSL_CERTIFICATE_VERIFY:
ret = ssl_write_certificate_verify( ssl );
break;
case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
ret = mbedtls_ssl_write_change_cipher_spec( ssl );
break;
case MBEDTLS_SSL_CLIENT_FINISHED:
ret = mbedtls_ssl_write_finished( ssl );
break;
/*
* <== ( NewSessionTicket )
* ChangeCipherSpec
* Finished
*/
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET:
ret = ssl_parse_new_session_ticket( ssl );
break;
#endif
case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
ret = mbedtls_ssl_parse_change_cipher_spec( ssl );
break;
case MBEDTLS_SSL_SERVER_FINISHED:
ret = mbedtls_ssl_parse_finished( ssl );
break;
case MBEDTLS_SSL_FLUSH_BUFFERS:
MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) );
ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
break;
case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
mbedtls_ssl_handshake_wrapup( ssl );
break;
default:
MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
return( ret );
}
#endif /* MBEDTLS_SSL_CLI_C */
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_702_0 |
crossvul-cpp_data_bad_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);
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);
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/bad_4840_0 |
crossvul-cpp_data_bad_2718_0 | /*
* Copyright (c) 2016 Antonin Décimo, Jean-Raphaël Gaglione
*
* 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: Home Networking Control Protocol (HNCP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdlib.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static void
hncp_print_rec(netdissect_options *ndo,
const u_char *cp, u_int length, int indent);
void
hncp_print(netdissect_options *ndo,
const u_char *cp, u_int length)
{
ND_PRINT((ndo, "hncp (%d)", length));
hncp_print_rec(ndo, cp, length, 1);
}
/* RFC7787 */
#define DNCP_REQUEST_NETWORK_STATE 1
#define DNCP_REQUEST_NODE_STATE 2
#define DNCP_NODE_ENDPOINT 3
#define DNCP_NETWORK_STATE 4
#define DNCP_NODE_STATE 5
#define DNCP_PEER 8
#define DNCP_KEEP_ALIVE_INTERVAL 9
#define DNCP_TRUST_VERDICT 10
/* RFC7788 */
#define HNCP_HNCP_VERSION 32
#define HNCP_EXTERNAL_CONNECTION 33
#define HNCP_DELEGATED_PREFIX 34
#define HNCP_PREFIX_POLICY 43
#define HNCP_DHCPV4_DATA 37
#define HNCP_DHCPV6_DATA 38
#define HNCP_ASSIGNED_PREFIX 35
#define HNCP_NODE_ADDRESS 36
#define HNCP_DNS_DELEGATED_ZONE 39
#define HNCP_DOMAIN_NAME 40
#define HNCP_NODE_NAME 41
#define HNCP_MANAGED_PSK 42
/* See type_mask in hncp_print_rec below */
#define RANGE_DNCP_RESERVED 0x10000
#define RANGE_HNCP_UNASSIGNED 0x10001
#define RANGE_DNCP_PRIVATE_USE 0x10002
#define RANGE_DNCP_FUTURE_USE 0x10003
static const struct tok type_values[] = {
{ DNCP_REQUEST_NETWORK_STATE, "Request network state" },
{ DNCP_REQUEST_NODE_STATE, "Request node state" },
{ DNCP_NODE_ENDPOINT, "Node endpoint" },
{ DNCP_NETWORK_STATE, "Network state" },
{ DNCP_NODE_STATE, "Node state" },
{ DNCP_PEER, "Peer" },
{ DNCP_KEEP_ALIVE_INTERVAL, "Keep-alive interval" },
{ DNCP_TRUST_VERDICT, "Trust-Verdict" },
{ HNCP_HNCP_VERSION, "HNCP-Version" },
{ HNCP_EXTERNAL_CONNECTION, "External-Connection" },
{ HNCP_DELEGATED_PREFIX, "Delegated-Prefix" },
{ HNCP_PREFIX_POLICY, "Prefix-Policy" },
{ HNCP_DHCPV4_DATA, "DHCPv4-Data" },
{ HNCP_DHCPV6_DATA, "DHCPv6-Data" },
{ HNCP_ASSIGNED_PREFIX, "Assigned-Prefix" },
{ HNCP_NODE_ADDRESS, "Node-Address" },
{ HNCP_DNS_DELEGATED_ZONE, "DNS-Delegated-Zone" },
{ HNCP_DOMAIN_NAME, "Domain-Name" },
{ HNCP_NODE_NAME, "Node-Name" },
{ HNCP_MANAGED_PSK, "Managed-PSK" },
{ RANGE_DNCP_RESERVED, "Reserved" },
{ RANGE_HNCP_UNASSIGNED, "Unassigned" },
{ RANGE_DNCP_PRIVATE_USE, "Private use" },
{ RANGE_DNCP_FUTURE_USE, "Future use" },
{ 0, NULL}
};
#define DH4OPT_DNS_SERVERS 6 /* RFC2132 */
#define DH4OPT_NTP_SERVERS 42 /* RFC2132 */
#define DH4OPT_DOMAIN_SEARCH 119 /* RFC3397 */
static const struct tok dh4opt_str[] = {
{ DH4OPT_DNS_SERVERS, "DNS-server" },
{ DH4OPT_NTP_SERVERS, "NTP-server"},
{ DH4OPT_DOMAIN_SEARCH, "DNS-search" },
{ 0, NULL }
};
#define DH6OPT_DNS_SERVERS 23 /* RFC3646 */
#define DH6OPT_DOMAIN_LIST 24 /* RFC3646 */
#define DH6OPT_SNTP_SERVERS 31 /* RFC4075 */
static const struct tok dh6opt_str[] = {
{ DH6OPT_DNS_SERVERS, "DNS-server" },
{ DH6OPT_DOMAIN_LIST, "DNS-search-list" },
{ DH6OPT_SNTP_SERVERS, "SNTP-servers" },
{ 0, NULL }
};
/*
* For IPv4-mapped IPv6 addresses, length of the prefix that precedes
* the 4 bytes of IPv4 address at the end of the IPv6 address.
*/
#define IPV4_MAPPED_HEADING_LEN 12
/*
* Is an IPv6 address an IPv4-mapped address?
*/
static inline int
is_ipv4_mapped_address(const u_char *addr)
{
/* The value of the prefix */
static const u_char ipv4_mapped_heading[IPV4_MAPPED_HEADING_LEN] =
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF };
return memcmp(addr, ipv4_mapped_heading, IPV4_MAPPED_HEADING_LEN) == 0;
}
static const char *
format_nid(const u_char *data)
{
static char buf[4][sizeof("01:01:01:01")];
static int i = 0;
i = (i + 1) % 4;
snprintf(buf[i], sizeof(buf[i]), "%02x:%02x:%02x:%02x",
data[0], data[1], data[2], data[3]);
return buf[i];
}
static const char *
format_256(const u_char *data)
{
static char buf[4][sizeof("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")];
static int i = 0;
i = (i + 1) % 4;
snprintf(buf[i], sizeof(buf[i]), "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "%016" PRIx64,
EXTRACT_64BITS(data),
EXTRACT_64BITS(data + 8),
EXTRACT_64BITS(data + 16),
EXTRACT_64BITS(data + 24)
);
return buf[i];
}
static const char *
format_interval(const uint32_t n)
{
static char buf[4][sizeof("0000000.000s")];
static int i = 0;
i = (i + 1) % 4;
snprintf(buf[i], sizeof(buf[i]), "%u.%03us", n / 1000, n % 1000);
return buf[i];
}
static const char *
format_ip6addr(netdissect_options *ndo, const u_char *cp)
{
if (is_ipv4_mapped_address(cp))
return ipaddr_string(ndo, cp + IPV4_MAPPED_HEADING_LEN);
else
return ip6addr_string(ndo, cp);
}
static int
print_prefix(netdissect_options *ndo, const u_char *prefix, u_int max_length)
{
int plenbytes;
char buf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::/128")];
if (prefix[0] >= 96 && max_length >= IPV4_MAPPED_HEADING_LEN + 1 &&
is_ipv4_mapped_address(&prefix[1])) {
struct in_addr addr;
u_int plen;
plen = prefix[0]-96;
if (32 < plen)
return -1;
max_length -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
if (max_length < (u_int)plenbytes + IPV4_MAPPED_HEADING_LEN)
return -3;
memcpy(&addr, &prefix[1 + IPV4_MAPPED_HEADING_LEN], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, sizeof(buf), "%s/%d", ipaddr_string(ndo, &addr), plen);
plenbytes += 1 + IPV4_MAPPED_HEADING_LEN;
} else {
plenbytes = decode_prefix6(ndo, prefix, max_length, buf, sizeof(buf));
}
ND_PRINT((ndo, "%s", buf));
return plenbytes;
}
static int
print_dns_label(netdissect_options *ndo,
const u_char *cp, u_int max_length, int print)
{
u_int length = 0;
while (length < max_length) {
u_int lab_length = cp[length++];
if (lab_length == 0)
return (int)length;
if (length > 1 && print)
safeputchar(ndo, '.');
if (length+lab_length > max_length) {
if (print)
safeputs(ndo, cp+length, max_length-length);
break;
}
if (print)
safeputs(ndo, cp+length, lab_length);
length += lab_length;
}
if (print)
ND_PRINT((ndo, "[|DNS]"));
return -1;
}
static int
dhcpv4_print(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
u_int i, t;
const u_char *tlv, *value;
uint8_t type, optlen;
i = 0;
while (i < length) {
tlv = cp + i;
type = (uint8_t)tlv[0];
optlen = (uint8_t)tlv[1];
value = tlv + 2;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
ND_PRINT((ndo, "%s", tok2str(dh4opt_str, "Unknown", type)));
ND_PRINT((ndo," (%u)", optlen + 2 ));
switch (type) {
case DH4OPT_DNS_SERVERS:
case DH4OPT_NTP_SERVERS: {
if (optlen < 4 || optlen % 4 != 0) {
return -1;
}
for (t = 0; t < optlen; t += 4)
ND_PRINT((ndo, " %s", ipaddr_string(ndo, value + t)));
}
break;
case DH4OPT_DOMAIN_SEARCH: {
const u_char *tp = value;
while (tp < value + optlen) {
ND_PRINT((ndo, " "));
if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL)
return -1;
}
}
break;
}
i += 2 + optlen;
}
return 0;
}
static int
dhcpv6_print(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
u_int i, t;
const u_char *tlv, *value;
uint16_t type, optlen;
i = 0;
while (i < length) {
tlv = cp + i;
type = EXTRACT_16BITS(tlv);
optlen = EXTRACT_16BITS(tlv + 2);
value = tlv + 4;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
ND_PRINT((ndo, "%s", tok2str(dh6opt_str, "Unknown", type)));
ND_PRINT((ndo," (%u)", optlen + 4 ));
switch (type) {
case DH6OPT_DNS_SERVERS:
case DH6OPT_SNTP_SERVERS: {
if (optlen % 16 != 0) {
ND_PRINT((ndo, " %s", istr));
return -1;
}
for (t = 0; t < optlen; t += 16)
ND_PRINT((ndo, " %s", ip6addr_string(ndo, value + t)));
}
break;
case DH6OPT_DOMAIN_LIST: {
const u_char *tp = value;
while (tp < value + optlen) {
ND_PRINT((ndo, " "));
if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL)
return -1;
}
}
break;
}
i += 4 + optlen;
}
return 0;
}
/* Determine in-line mode */
static int
is_in_line(netdissect_options *ndo, int indent)
{
return indent - 1 >= ndo->ndo_vflag && ndo->ndo_vflag < 3;
}
static void
print_type_in_line(netdissect_options *ndo,
uint32_t type, int count, int indent, int *first_one)
{
if (count > 0) {
if (*first_one) {
*first_one = 0;
if (indent > 1) {
u_int t;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
} else {
ND_PRINT((ndo, " "));
}
} else {
ND_PRINT((ndo, ", "));
}
ND_PRINT((ndo, "%s", tok2str(type_values, "Easter Egg", type)));
if (count > 1)
ND_PRINT((ndo, " (x%d)", count));
}
}
void
hncp_print_rec(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
const int in_line = is_in_line(ndo, indent);
int first_one = 1;
u_int i, t;
uint32_t last_type_mask = 0xffffffffU;
int last_type_count = -1;
const u_char *tlv, *value;
uint16_t type, bodylen;
uint32_t type_mask;
i = 0;
while (i < length) {
tlv = cp + i;
if (!in_line) {
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
}
ND_TCHECK2(*tlv, 4);
if (i + 4 > length)
goto invalid;
type = EXTRACT_16BITS(tlv);
bodylen = EXTRACT_16BITS(tlv + 2);
value = tlv + 4;
ND_TCHECK2(*value, bodylen);
if (i + bodylen + 4 > length)
goto invalid;
type_mask =
(type == 0) ? RANGE_DNCP_RESERVED:
(44 <= type && type <= 511) ? RANGE_HNCP_UNASSIGNED:
(768 <= type && type <= 1023) ? RANGE_DNCP_PRIVATE_USE:
RANGE_DNCP_FUTURE_USE;
if (type == 6 || type == 7)
type_mask = RANGE_DNCP_FUTURE_USE;
/* defined types */
{
t = 0;
while (1) {
u_int key = type_values[t++].v;
if (key > 0xffff)
break;
if (key == type) {
type_mask = type;
break;
}
}
}
if (in_line) {
if (last_type_mask == type_mask) {
last_type_count++;
} else {
print_type_in_line(ndo, last_type_mask, last_type_count, indent, &first_one);
last_type_mask = type_mask;
last_type_count = 1;
}
goto skip_multiline;
}
ND_PRINT((ndo,"%s", tok2str(type_values, "Easter Egg (42)", type_mask) ));
if (type_mask > 0xffff)
ND_PRINT((ndo,": type=%u", type ));
ND_PRINT((ndo," (%u)", bodylen + 4 ));
switch (type_mask) {
case DNCP_REQUEST_NETWORK_STATE: {
if (bodylen != 0)
ND_PRINT((ndo, " %s", istr));
}
break;
case DNCP_REQUEST_NODE_STATE: {
const char *node_identifier;
if (bodylen != 4) {
ND_PRINT((ndo, " %s", istr));
break;
}
node_identifier = format_nid(value);
ND_PRINT((ndo, " NID: %s", node_identifier));
}
break;
case DNCP_NODE_ENDPOINT: {
const char *node_identifier;
uint32_t endpoint_identifier;
if (bodylen != 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
node_identifier = format_nid(value);
endpoint_identifier = EXTRACT_32BITS(value + 4);
ND_PRINT((ndo, " NID: %s EPID: %08x",
node_identifier,
endpoint_identifier
));
}
break;
case DNCP_NETWORK_STATE: {
uint64_t hash;
if (bodylen != 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
hash = EXTRACT_64BITS(value);
ND_PRINT((ndo, " hash: %016" PRIx64, hash));
}
break;
case DNCP_NODE_STATE: {
const char *node_identifier, *interval;
uint32_t sequence_number;
uint64_t hash;
if (bodylen < 20) {
ND_PRINT((ndo, " %s", istr));
break;
}
node_identifier = format_nid(value);
sequence_number = EXTRACT_32BITS(value + 4);
interval = format_interval(EXTRACT_32BITS(value + 8));
hash = EXTRACT_64BITS(value + 12);
ND_PRINT((ndo, " NID: %s seqno: %u %s hash: %016" PRIx64,
node_identifier,
sequence_number,
interval,
hash
));
hncp_print_rec(ndo, value+20, bodylen-20, indent+1);
}
break;
case DNCP_PEER: {
const char *peer_node_identifier;
uint32_t peer_endpoint_identifier, endpoint_identifier;
if (bodylen != 12) {
ND_PRINT((ndo, " %s", istr));
break;
}
peer_node_identifier = format_nid(value);
peer_endpoint_identifier = EXTRACT_32BITS(value + 4);
endpoint_identifier = EXTRACT_32BITS(value + 8);
ND_PRINT((ndo, " Peer-NID: %s Peer-EPID: %08x Local-EPID: %08x",
peer_node_identifier,
peer_endpoint_identifier,
endpoint_identifier
));
}
break;
case DNCP_KEEP_ALIVE_INTERVAL: {
uint32_t endpoint_identifier;
const char *interval;
if (bodylen < 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
endpoint_identifier = EXTRACT_32BITS(value);
interval = format_interval(EXTRACT_32BITS(value + 4));
ND_PRINT((ndo, " EPID: %08x Interval: %s",
endpoint_identifier,
interval
));
}
break;
case DNCP_TRUST_VERDICT: {
if (bodylen <= 36) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " Verdict: %u Fingerprint: %s Common Name: ",
*value,
format_256(value + 4)));
safeputs(ndo, value + 36, bodylen - 36);
}
break;
case HNCP_HNCP_VERSION: {
uint16_t capabilities;
uint8_t M, P, H, L;
if (bodylen < 5) {
ND_PRINT((ndo, " %s", istr));
break;
}
capabilities = EXTRACT_16BITS(value + 2);
M = (uint8_t)((capabilities >> 12) & 0xf);
P = (uint8_t)((capabilities >> 8) & 0xf);
H = (uint8_t)((capabilities >> 4) & 0xf);
L = (uint8_t)(capabilities & 0xf);
ND_PRINT((ndo, " M: %u P: %u H: %u L: %u User-agent: ",
M, P, H, L
));
safeputs(ndo, value + 4, bodylen - 4);
}
break;
case HNCP_EXTERNAL_CONNECTION: {
/* Container TLV */
hncp_print_rec(ndo, value, bodylen, indent+1);
}
break;
case HNCP_DELEGATED_PREFIX: {
int l;
if (bodylen < 9 || bodylen < 9 + (value[8] + 7) / 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " VLSO: %s PLSO: %s Prefix: ",
format_interval(EXTRACT_32BITS(value)),
format_interval(EXTRACT_32BITS(value + 4))
));
l = print_prefix(ndo, value + 8, bodylen - 8);
if (l == -1) {
ND_PRINT((ndo, "(length is invalid)"));
break;
}
if (l < 0) {
/*
* We've already checked that we've captured the
* entire TLV, based on its length, so this will
* either be -1, meaning "the prefix length is
* greater than the longest possible address of
* that type" (i.e., > 32 for IPv4 or > 128 for
* IPv6", or -3, meaning "the prefix runs past
* the end of the TLV".
*/
ND_PRINT((ndo, " %s", istr));
break;
}
l += 8 + (-l & 3);
if (bodylen >= l)
hncp_print_rec(ndo, value + l, bodylen - l, indent+1);
}
break;
case HNCP_PREFIX_POLICY: {
uint8_t policy;
int l;
if (bodylen < 1) {
ND_PRINT((ndo, " %s", istr));
break;
}
policy = value[0];
ND_PRINT((ndo, " type: "));
if (policy == 0) {
if (bodylen != 1) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, "Internet connectivity"));
} else if (policy >= 1 && policy <= 128) {
ND_PRINT((ndo, "Dest-Prefix: "));
l = print_prefix(ndo, value, bodylen);
if (l == -1) {
ND_PRINT((ndo, "(length is invalid)"));
break;
}
if (l < 0) {
/*
* We've already checked that we've captured the
* entire TLV, based on its length, so this will
* either be -1, meaning "the prefix length is
* greater than the longest possible address of
* that type" (i.e., > 32 for IPv4 or > 128 for
* IPv6", or -3, meaning "the prefix runs past
* the end of the TLV".
*/
ND_PRINT((ndo, " %s", istr));
break;
}
} else if (policy == 129) {
ND_PRINT((ndo, "DNS domain: "));
print_dns_label(ndo, value+1, bodylen-1, 1);
} else if (policy == 130) {
ND_PRINT((ndo, "Opaque UTF-8: "));
safeputs(ndo, value + 1, bodylen - 1);
} else if (policy == 131) {
if (bodylen != 1) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, "Restrictive assignment"));
} else if (policy >= 132) {
ND_PRINT((ndo, "Unknown (%u)", policy)); /* Reserved for future additions */
}
}
break;
case HNCP_DHCPV4_DATA: {
if (bodylen == 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
if (dhcpv4_print(ndo, value, bodylen, indent+1) != 0)
goto invalid;
}
break;
case HNCP_DHCPV6_DATA: {
if (bodylen == 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
if (dhcpv6_print(ndo, value, bodylen, indent+1) != 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
}
break;
case HNCP_ASSIGNED_PREFIX: {
uint8_t prty;
int l;
if (bodylen < 6 || bodylen < 6 + (value[5] + 7) / 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
prty = (uint8_t)(value[4] & 0xf);
ND_PRINT((ndo, " EPID: %08x Prty: %u",
EXTRACT_32BITS(value),
prty
));
ND_PRINT((ndo, " Prefix: "));
if ((l = print_prefix(ndo, value + 5, bodylen - 5)) < 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
l += 5;
l += -l & 3;
if (bodylen >= l)
hncp_print_rec(ndo, value + l, bodylen - l, indent+1);
}
break;
case HNCP_NODE_ADDRESS: {
uint32_t endpoint_identifier;
const char *ip_address;
if (bodylen < 20) {
ND_PRINT((ndo, " %s", istr));
break;
}
endpoint_identifier = EXTRACT_32BITS(value);
ip_address = format_ip6addr(ndo, value + 4);
ND_PRINT((ndo, " EPID: %08x IP Address: %s",
endpoint_identifier,
ip_address
));
hncp_print_rec(ndo, value + 20, bodylen - 20, indent+1);
}
break;
case HNCP_DNS_DELEGATED_ZONE: {
const char *ip_address;
int len;
if (bodylen < 17) {
ND_PRINT((ndo, " %s", istr));
break;
}
ip_address = format_ip6addr(ndo, value);
ND_PRINT((ndo, " IP-Address: %s %c%c%c ",
ip_address,
(value[16] & 4) ? 'l' : '-',
(value[16] & 2) ? 'b' : '-',
(value[16] & 1) ? 's' : '-'
));
len = print_dns_label(ndo, value+17, bodylen-17, 1);
if (len < 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
len += 17;
len += -len & 3;
if (bodylen >= len)
hncp_print_rec(ndo, value+len, bodylen-len, indent+1);
}
break;
case HNCP_DOMAIN_NAME: {
if (bodylen == 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " Domain: "));
print_dns_label(ndo, value, bodylen, 1);
}
break;
case HNCP_NODE_NAME: {
u_int l;
if (bodylen < 17) {
ND_PRINT((ndo, " %s", istr));
break;
}
l = value[16];
if (bodylen < 17 + l) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " IP-Address: %s Name: ",
format_ip6addr(ndo, value)
));
if (l < 64) {
safeputchar(ndo, '"');
safeputs(ndo, value + 17, l);
safeputchar(ndo, '"');
} else {
ND_PRINT((ndo, "%s", istr));
}
l += 17;
l += -l & 3;
if (bodylen >= l)
hncp_print_rec(ndo, value + l, bodylen - l, indent+1);
}
break;
case HNCP_MANAGED_PSK: {
if (bodylen < 32) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " PSK: %s", format_256(value)));
hncp_print_rec(ndo, value + 32, bodylen - 32, indent+1);
}
break;
case RANGE_DNCP_RESERVED:
case RANGE_HNCP_UNASSIGNED:
case RANGE_DNCP_PRIVATE_USE:
case RANGE_DNCP_FUTURE_USE:
break;
}
skip_multiline:
i += 4 + bodylen + (-bodylen & 3);
}
print_type_in_line(ndo, last_type_mask, last_type_count, indent, &first_one);
return;
trunc:
ND_PRINT((ndo, "%s", "[|hncp]"));
return;
invalid:
ND_PRINT((ndo, "%s", istr));
return;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2718_0 |
crossvul-cpp_data_bad_2703_0 | /*
* Copyright (c) 1998-2007 The TCPDUMP project
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Original code by Hannes Gredler (hannes@gredler.at)
* IEEE and TIA extensions by Carles Kishimoto <carles.kishimoto@gmail.com>
* DCBX extensions by Kaladhar Musunuru <kaladharm@sourceforge.net>
*/
/* \summary: IEEE 802.1ab Link Layer Discovery Protocol (LLDP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "af.h"
#include "oui.h"
#define LLDP_EXTRACT_TYPE(x) (((x)&0xfe00)>>9)
#define LLDP_EXTRACT_LEN(x) ((x)&0x01ff)
/*
* TLV type codes
*/
#define LLDP_END_TLV 0
#define LLDP_CHASSIS_ID_TLV 1
#define LLDP_PORT_ID_TLV 2
#define LLDP_TTL_TLV 3
#define LLDP_PORT_DESCR_TLV 4
#define LLDP_SYSTEM_NAME_TLV 5
#define LLDP_SYSTEM_DESCR_TLV 6
#define LLDP_SYSTEM_CAP_TLV 7
#define LLDP_MGMT_ADDR_TLV 8
#define LLDP_PRIVATE_TLV 127
static const struct tok lldp_tlv_values[] = {
{ LLDP_END_TLV, "End" },
{ LLDP_CHASSIS_ID_TLV, "Chassis ID" },
{ LLDP_PORT_ID_TLV, "Port ID" },
{ LLDP_TTL_TLV, "Time to Live" },
{ LLDP_PORT_DESCR_TLV, "Port Description" },
{ LLDP_SYSTEM_NAME_TLV, "System Name" },
{ LLDP_SYSTEM_DESCR_TLV, "System Description" },
{ LLDP_SYSTEM_CAP_TLV, "System Capabilities" },
{ LLDP_MGMT_ADDR_TLV, "Management Address" },
{ LLDP_PRIVATE_TLV, "Organization specific" },
{ 0, NULL}
};
/*
* Chassis ID subtypes
*/
#define LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE 1
#define LLDP_CHASSIS_INTF_ALIAS_SUBTYPE 2
#define LLDP_CHASSIS_PORT_COMP_SUBTYPE 3
#define LLDP_CHASSIS_MAC_ADDR_SUBTYPE 4
#define LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE 5
#define LLDP_CHASSIS_INTF_NAME_SUBTYPE 6
#define LLDP_CHASSIS_LOCAL_SUBTYPE 7
static const struct tok lldp_chassis_subtype_values[] = {
{ LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE, "Chassis component"},
{ LLDP_CHASSIS_INTF_ALIAS_SUBTYPE, "Interface alias"},
{ LLDP_CHASSIS_PORT_COMP_SUBTYPE, "Port component"},
{ LLDP_CHASSIS_MAC_ADDR_SUBTYPE, "MAC address"},
{ LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE, "Network address"},
{ LLDP_CHASSIS_INTF_NAME_SUBTYPE, "Interface name"},
{ LLDP_CHASSIS_LOCAL_SUBTYPE, "Local"},
{ 0, NULL}
};
/*
* Port ID subtypes
*/
#define LLDP_PORT_INTF_ALIAS_SUBTYPE 1
#define LLDP_PORT_PORT_COMP_SUBTYPE 2
#define LLDP_PORT_MAC_ADDR_SUBTYPE 3
#define LLDP_PORT_NETWORK_ADDR_SUBTYPE 4
#define LLDP_PORT_INTF_NAME_SUBTYPE 5
#define LLDP_PORT_AGENT_CIRC_ID_SUBTYPE 6
#define LLDP_PORT_LOCAL_SUBTYPE 7
static const struct tok lldp_port_subtype_values[] = {
{ LLDP_PORT_INTF_ALIAS_SUBTYPE, "Interface alias"},
{ LLDP_PORT_PORT_COMP_SUBTYPE, "Port component"},
{ LLDP_PORT_MAC_ADDR_SUBTYPE, "MAC address"},
{ LLDP_PORT_NETWORK_ADDR_SUBTYPE, "Network Address"},
{ LLDP_PORT_INTF_NAME_SUBTYPE, "Interface Name"},
{ LLDP_PORT_AGENT_CIRC_ID_SUBTYPE, "Agent circuit ID"},
{ LLDP_PORT_LOCAL_SUBTYPE, "Local"},
{ 0, NULL}
};
/*
* System Capabilities
*/
#define LLDP_CAP_OTHER (1 << 0)
#define LLDP_CAP_REPEATER (1 << 1)
#define LLDP_CAP_BRIDGE (1 << 2)
#define LLDP_CAP_WLAN_AP (1 << 3)
#define LLDP_CAP_ROUTER (1 << 4)
#define LLDP_CAP_PHONE (1 << 5)
#define LLDP_CAP_DOCSIS (1 << 6)
#define LLDP_CAP_STATION_ONLY (1 << 7)
static const struct tok lldp_cap_values[] = {
{ LLDP_CAP_OTHER, "Other"},
{ LLDP_CAP_REPEATER, "Repeater"},
{ LLDP_CAP_BRIDGE, "Bridge"},
{ LLDP_CAP_WLAN_AP, "WLAN AP"},
{ LLDP_CAP_ROUTER, "Router"},
{ LLDP_CAP_PHONE, "Telephone"},
{ LLDP_CAP_DOCSIS, "Docsis"},
{ LLDP_CAP_STATION_ONLY, "Station Only"},
{ 0, NULL}
};
#define LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID 1
#define LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID 2
#define LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME 3
#define LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY 4
#define LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION 8
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION 9
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION 10
#define LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION 11
#define LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY 12
#define LLDP_PRIVATE_8021_SUBTYPE_EVB 13
#define LLDP_PRIVATE_8021_SUBTYPE_CDCP 14
static const struct tok lldp_8021_subtype_values[] = {
{ LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID, "Port VLAN Id"},
{ LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID, "Port and Protocol VLAN ID"},
{ LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME, "VLAN name"},
{ LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY, "Protocol Identity"},
{ LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION, "Congestion Notification"},
{ LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION, "ETS Configuration"},
{ LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION, "ETS Recommendation"},
{ LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION, "Priority Flow Control Configuration"},
{ LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY, "Application Priority"},
{ LLDP_PRIVATE_8021_SUBTYPE_EVB, "EVB"},
{ LLDP_PRIVATE_8021_SUBTYPE_CDCP,"CDCP"},
{ 0, NULL}
};
#define LLDP_8021_PORT_PROTOCOL_VLAN_SUPPORT (1 << 1)
#define LLDP_8021_PORT_PROTOCOL_VLAN_STATUS (1 << 2)
static const struct tok lldp_8021_port_protocol_id_values[] = {
{ LLDP_8021_PORT_PROTOCOL_VLAN_SUPPORT, "supported"},
{ LLDP_8021_PORT_PROTOCOL_VLAN_STATUS, "enabled"},
{ 0, NULL}
};
#define LLDP_PRIVATE_8023_SUBTYPE_MACPHY 1
#define LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER 2
#define LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR 3
#define LLDP_PRIVATE_8023_SUBTYPE_MTU 4
static const struct tok lldp_8023_subtype_values[] = {
{ LLDP_PRIVATE_8023_SUBTYPE_MACPHY, "MAC/PHY configuration/status"},
{ LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER, "Power via MDI"},
{ LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR, "Link aggregation"},
{ LLDP_PRIVATE_8023_SUBTYPE_MTU, "Max frame size"},
{ 0, NULL}
};
#define LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES 1
#define LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY 2
#define LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID 3
#define LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI 4
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV 5
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV 6
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV 7
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER 8
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME 9
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME 10
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID 11
static const struct tok lldp_tia_subtype_values[] = {
{ LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES, "LLDP-MED Capabilities" },
{ LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY, "Network policy" },
{ LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID, "Location identification" },
{ LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI, "Extended power-via-MDI" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV, "Inventory - hardware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV, "Inventory - firmware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV, "Inventory - software revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER, "Inventory - serial number" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME, "Inventory - manufacturer name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME, "Inventory - model name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID, "Inventory - asset ID" },
{ 0, NULL}
};
#define LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_METERS 1
#define LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_FLOORS 2
static const struct tok lldp_tia_location_altitude_type_values[] = {
{ LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_METERS, "meters"},
{ LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_FLOORS, "floors"},
{ 0, NULL}
};
/* ANSI/TIA-1057 - Annex B */
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A1 1
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A2 2
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A3 3
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A4 4
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A5 5
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A6 6
static const struct tok lldp_tia_location_lci_catype_values[] = {
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A1, "national subdivisions (state,canton,region,province,prefecture)"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A2, "county, parish, gun, district"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A3, "city, township, shi"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A4, "city division, borough, city district, ward chou"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A5, "neighborhood, block"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A6, "street"},
{ 0, NULL}
};
static const struct tok lldp_tia_location_lci_what_values[] = {
{ 0, "location of DHCP server"},
{ 1, "location of the network element believed to be closest to the client"},
{ 2, "location of the client"},
{ 0, NULL}
};
/*
* From RFC 3636 - dot3MauType
*/
#define LLDP_MAU_TYPE_UNKNOWN 0
#define LLDP_MAU_TYPE_AUI 1
#define LLDP_MAU_TYPE_10BASE_5 2
#define LLDP_MAU_TYPE_FOIRL 3
#define LLDP_MAU_TYPE_10BASE_2 4
#define LLDP_MAU_TYPE_10BASE_T 5
#define LLDP_MAU_TYPE_10BASE_FP 6
#define LLDP_MAU_TYPE_10BASE_FB 7
#define LLDP_MAU_TYPE_10BASE_FL 8
#define LLDP_MAU_TYPE_10BROAD36 9
#define LLDP_MAU_TYPE_10BASE_T_HD 10
#define LLDP_MAU_TYPE_10BASE_T_FD 11
#define LLDP_MAU_TYPE_10BASE_FL_HD 12
#define LLDP_MAU_TYPE_10BASE_FL_FD 13
#define LLDP_MAU_TYPE_100BASE_T4 14
#define LLDP_MAU_TYPE_100BASE_TX_HD 15
#define LLDP_MAU_TYPE_100BASE_TX_FD 16
#define LLDP_MAU_TYPE_100BASE_FX_HD 17
#define LLDP_MAU_TYPE_100BASE_FX_FD 18
#define LLDP_MAU_TYPE_100BASE_T2_HD 19
#define LLDP_MAU_TYPE_100BASE_T2_FD 20
#define LLDP_MAU_TYPE_1000BASE_X_HD 21
#define LLDP_MAU_TYPE_1000BASE_X_FD 22
#define LLDP_MAU_TYPE_1000BASE_LX_HD 23
#define LLDP_MAU_TYPE_1000BASE_LX_FD 24
#define LLDP_MAU_TYPE_1000BASE_SX_HD 25
#define LLDP_MAU_TYPE_1000BASE_SX_FD 26
#define LLDP_MAU_TYPE_1000BASE_CX_HD 27
#define LLDP_MAU_TYPE_1000BASE_CX_FD 28
#define LLDP_MAU_TYPE_1000BASE_T_HD 29
#define LLDP_MAU_TYPE_1000BASE_T_FD 30
#define LLDP_MAU_TYPE_10GBASE_X 31
#define LLDP_MAU_TYPE_10GBASE_LX4 32
#define LLDP_MAU_TYPE_10GBASE_R 33
#define LLDP_MAU_TYPE_10GBASE_ER 34
#define LLDP_MAU_TYPE_10GBASE_LR 35
#define LLDP_MAU_TYPE_10GBASE_SR 36
#define LLDP_MAU_TYPE_10GBASE_W 37
#define LLDP_MAU_TYPE_10GBASE_EW 38
#define LLDP_MAU_TYPE_10GBASE_LW 39
#define LLDP_MAU_TYPE_10GBASE_SW 40
static const struct tok lldp_mau_types_values[] = {
{ LLDP_MAU_TYPE_UNKNOWN, "Unknown"},
{ LLDP_MAU_TYPE_AUI, "AUI"},
{ LLDP_MAU_TYPE_10BASE_5, "10BASE_5"},
{ LLDP_MAU_TYPE_FOIRL, "FOIRL"},
{ LLDP_MAU_TYPE_10BASE_2, "10BASE2"},
{ LLDP_MAU_TYPE_10BASE_T, "10BASET duplex mode unknown"},
{ LLDP_MAU_TYPE_10BASE_FP, "10BASEFP"},
{ LLDP_MAU_TYPE_10BASE_FB, "10BASEFB"},
{ LLDP_MAU_TYPE_10BASE_FL, "10BASEFL duplex mode unknown"},
{ LLDP_MAU_TYPE_10BROAD36, "10BROAD36"},
{ LLDP_MAU_TYPE_10BASE_T_HD, "10BASET hdx"},
{ LLDP_MAU_TYPE_10BASE_T_FD, "10BASET fdx"},
{ LLDP_MAU_TYPE_10BASE_FL_HD, "10BASEFL hdx"},
{ LLDP_MAU_TYPE_10BASE_FL_FD, "10BASEFL fdx"},
{ LLDP_MAU_TYPE_100BASE_T4, "100BASET4"},
{ LLDP_MAU_TYPE_100BASE_TX_HD, "100BASETX hdx"},
{ LLDP_MAU_TYPE_100BASE_TX_FD, "100BASETX fdx"},
{ LLDP_MAU_TYPE_100BASE_FX_HD, "100BASEFX hdx"},
{ LLDP_MAU_TYPE_100BASE_FX_FD, "100BASEFX fdx"},
{ LLDP_MAU_TYPE_100BASE_T2_HD, "100BASET2 hdx"},
{ LLDP_MAU_TYPE_100BASE_T2_FD, "100BASET2 fdx"},
{ LLDP_MAU_TYPE_1000BASE_X_HD, "1000BASEX hdx"},
{ LLDP_MAU_TYPE_1000BASE_X_FD, "1000BASEX fdx"},
{ LLDP_MAU_TYPE_1000BASE_LX_HD, "1000BASELX hdx"},
{ LLDP_MAU_TYPE_1000BASE_LX_FD, "1000BASELX fdx"},
{ LLDP_MAU_TYPE_1000BASE_SX_HD, "1000BASESX hdx"},
{ LLDP_MAU_TYPE_1000BASE_SX_FD, "1000BASESX fdx"},
{ LLDP_MAU_TYPE_1000BASE_CX_HD, "1000BASECX hdx"},
{ LLDP_MAU_TYPE_1000BASE_CX_FD, "1000BASECX fdx"},
{ LLDP_MAU_TYPE_1000BASE_T_HD, "1000BASET hdx"},
{ LLDP_MAU_TYPE_1000BASE_T_FD, "1000BASET fdx"},
{ LLDP_MAU_TYPE_10GBASE_X, "10GBASEX"},
{ LLDP_MAU_TYPE_10GBASE_LX4, "10GBASELX4"},
{ LLDP_MAU_TYPE_10GBASE_R, "10GBASER"},
{ LLDP_MAU_TYPE_10GBASE_ER, "10GBASEER"},
{ LLDP_MAU_TYPE_10GBASE_LR, "10GBASELR"},
{ LLDP_MAU_TYPE_10GBASE_SR, "10GBASESR"},
{ LLDP_MAU_TYPE_10GBASE_W, "10GBASEW"},
{ LLDP_MAU_TYPE_10GBASE_EW, "10GBASEEW"},
{ LLDP_MAU_TYPE_10GBASE_LW, "10GBASELW"},
{ LLDP_MAU_TYPE_10GBASE_SW, "10GBASESW"},
{ 0, NULL}
};
#define LLDP_8023_AUTONEGOTIATION_SUPPORT (1 << 0)
#define LLDP_8023_AUTONEGOTIATION_STATUS (1 << 1)
static const struct tok lldp_8023_autonegotiation_values[] = {
{ LLDP_8023_AUTONEGOTIATION_SUPPORT, "supported"},
{ LLDP_8023_AUTONEGOTIATION_STATUS, "enabled"},
{ 0, NULL}
};
#define LLDP_TIA_CAPABILITY_MED (1 << 0)
#define LLDP_TIA_CAPABILITY_NETWORK_POLICY (1 << 1)
#define LLDP_TIA_CAPABILITY_LOCATION_IDENTIFICATION (1 << 2)
#define LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PSE (1 << 3)
#define LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PD (1 << 4)
#define LLDP_TIA_CAPABILITY_INVENTORY (1 << 5)
static const struct tok lldp_tia_capabilities_values[] = {
{ LLDP_TIA_CAPABILITY_MED, "LLDP-MED capabilities"},
{ LLDP_TIA_CAPABILITY_NETWORK_POLICY, "network policy"},
{ LLDP_TIA_CAPABILITY_LOCATION_IDENTIFICATION, "location identification"},
{ LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PSE, "extended power via MDI-PSE"},
{ LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PD, "extended power via MDI-PD"},
{ LLDP_TIA_CAPABILITY_INVENTORY, "Inventory"},
{ 0, NULL}
};
#define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_1 1
#define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_2 2
#define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_3 3
#define LLDP_TIA_DEVICE_TYPE_NETWORK_CONNECTIVITY 4
static const struct tok lldp_tia_device_type_values[] = {
{ LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_1, "endpoint class 1"},
{ LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_2, "endpoint class 2"},
{ LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_3, "endpoint class 3"},
{ LLDP_TIA_DEVICE_TYPE_NETWORK_CONNECTIVITY, "network connectivity"},
{ 0, NULL}
};
#define LLDP_TIA_APPLICATION_TYPE_VOICE 1
#define LLDP_TIA_APPLICATION_TYPE_VOICE_SIGNALING 2
#define LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE 3
#define LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE_SIGNALING 4
#define LLDP_TIA_APPLICATION_TYPE_SOFTPHONE_VOICE 5
#define LLDP_TIA_APPLICATION_TYPE_VIDEO_CONFERENCING 6
#define LLDP_TIA_APPLICATION_TYPE_STREAMING_VIDEO 7
#define LLDP_TIA_APPLICATION_TYPE_VIDEO_SIGNALING 8
static const struct tok lldp_tia_application_type_values[] = {
{ LLDP_TIA_APPLICATION_TYPE_VOICE, "voice"},
{ LLDP_TIA_APPLICATION_TYPE_VOICE_SIGNALING, "voice signaling"},
{ LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE, "guest voice"},
{ LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE_SIGNALING, "guest voice signaling"},
{ LLDP_TIA_APPLICATION_TYPE_SOFTPHONE_VOICE, "softphone voice"},
{ LLDP_TIA_APPLICATION_TYPE_VIDEO_CONFERENCING, "video conferencing"},
{ LLDP_TIA_APPLICATION_TYPE_STREAMING_VIDEO, "streaming video"},
{ LLDP_TIA_APPLICATION_TYPE_VIDEO_SIGNALING, "video signaling"},
{ 0, NULL}
};
#define LLDP_TIA_NETWORK_POLICY_X_BIT (1 << 5)
#define LLDP_TIA_NETWORK_POLICY_T_BIT (1 << 6)
#define LLDP_TIA_NETWORK_POLICY_U_BIT (1 << 7)
static const struct tok lldp_tia_network_policy_bits_values[] = {
{ LLDP_TIA_NETWORK_POLICY_U_BIT, "Unknown"},
{ LLDP_TIA_NETWORK_POLICY_T_BIT, "Tagged"},
{ LLDP_TIA_NETWORK_POLICY_X_BIT, "reserved"},
{ 0, NULL}
};
#define LLDP_EXTRACT_NETWORK_POLICY_VLAN(x) (((x)&0x1ffe)>>1)
#define LLDP_EXTRACT_NETWORK_POLICY_L2_PRIORITY(x) (((x)&0x01ff)>>6)
#define LLDP_EXTRACT_NETWORK_POLICY_DSCP(x) ((x)&0x003f)
#define LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED 1
#define LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS 2
#define LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN 3
static const struct tok lldp_tia_location_data_format_values[] = {
{ LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED, "coordinate-based LCI"},
{ LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS, "civic address LCI"},
{ LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN, "ECS ELIN"},
{ 0, NULL}
};
#define LLDP_TIA_LOCATION_DATUM_WGS_84 1
#define LLDP_TIA_LOCATION_DATUM_NAD_83_NAVD_88 2
#define LLDP_TIA_LOCATION_DATUM_NAD_83_MLLW 3
static const struct tok lldp_tia_location_datum_type_values[] = {
{ LLDP_TIA_LOCATION_DATUM_WGS_84, "World Geodesic System 1984"},
{ LLDP_TIA_LOCATION_DATUM_NAD_83_NAVD_88, "North American Datum 1983 (NAVD88)"},
{ LLDP_TIA_LOCATION_DATUM_NAD_83_MLLW, "North American Datum 1983 (MLLW)"},
{ 0, NULL}
};
#define LLDP_TIA_POWER_SOURCE_PSE 1
#define LLDP_TIA_POWER_SOURCE_LOCAL 2
#define LLDP_TIA_POWER_SOURCE_PSE_AND_LOCAL 3
static const struct tok lldp_tia_power_source_values[] = {
{ LLDP_TIA_POWER_SOURCE_PSE, "PSE - primary power source"},
{ LLDP_TIA_POWER_SOURCE_LOCAL, "local - backup power source"},
{ LLDP_TIA_POWER_SOURCE_PSE_AND_LOCAL, "PSE+local - reserved"},
{ 0, NULL}
};
#define LLDP_TIA_POWER_PRIORITY_CRITICAL 1
#define LLDP_TIA_POWER_PRIORITY_HIGH 2
#define LLDP_TIA_POWER_PRIORITY_LOW 3
static const struct tok lldp_tia_power_priority_values[] = {
{ LLDP_TIA_POWER_PRIORITY_CRITICAL, "critical"},
{ LLDP_TIA_POWER_PRIORITY_HIGH, "high"},
{ LLDP_TIA_POWER_PRIORITY_LOW, "low"},
{ 0, NULL}
};
#define LLDP_TIA_POWER_VAL_MAX 1024
static const struct tok lldp_tia_inventory_values[] = {
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV, "Hardware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV, "Firmware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV, "Software revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER, "Serial number" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME, "Manufacturer name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME, "Model name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID, "Asset ID" },
{ 0, NULL}
};
/*
* From RFC 3636 - ifMauAutoNegCapAdvertisedBits
*/
#define LLDP_MAU_PMD_OTHER (1 << 15)
#define LLDP_MAU_PMD_10BASE_T (1 << 14)
#define LLDP_MAU_PMD_10BASE_T_FD (1 << 13)
#define LLDP_MAU_PMD_100BASE_T4 (1 << 12)
#define LLDP_MAU_PMD_100BASE_TX (1 << 11)
#define LLDP_MAU_PMD_100BASE_TX_FD (1 << 10)
#define LLDP_MAU_PMD_100BASE_T2 (1 << 9)
#define LLDP_MAU_PMD_100BASE_T2_FD (1 << 8)
#define LLDP_MAU_PMD_FDXPAUSE (1 << 7)
#define LLDP_MAU_PMD_FDXAPAUSE (1 << 6)
#define LLDP_MAU_PMD_FDXSPAUSE (1 << 5)
#define LLDP_MAU_PMD_FDXBPAUSE (1 << 4)
#define LLDP_MAU_PMD_1000BASE_X (1 << 3)
#define LLDP_MAU_PMD_1000BASE_X_FD (1 << 2)
#define LLDP_MAU_PMD_1000BASE_T (1 << 1)
#define LLDP_MAU_PMD_1000BASE_T_FD (1 << 0)
static const struct tok lldp_pmd_capability_values[] = {
{ LLDP_MAU_PMD_10BASE_T, "10BASE-T hdx"},
{ LLDP_MAU_PMD_10BASE_T_FD, "10BASE-T fdx"},
{ LLDP_MAU_PMD_100BASE_T4, "100BASE-T4"},
{ LLDP_MAU_PMD_100BASE_TX, "100BASE-TX hdx"},
{ LLDP_MAU_PMD_100BASE_TX_FD, "100BASE-TX fdx"},
{ LLDP_MAU_PMD_100BASE_T2, "100BASE-T2 hdx"},
{ LLDP_MAU_PMD_100BASE_T2_FD, "100BASE-T2 fdx"},
{ LLDP_MAU_PMD_FDXPAUSE, "Pause for fdx links"},
{ LLDP_MAU_PMD_FDXAPAUSE, "Asym PAUSE for fdx"},
{ LLDP_MAU_PMD_FDXSPAUSE, "Sym PAUSE for fdx"},
{ LLDP_MAU_PMD_FDXBPAUSE, "Asym and Sym PAUSE for fdx"},
{ LLDP_MAU_PMD_1000BASE_X, "1000BASE-{X LX SX CX} hdx"},
{ LLDP_MAU_PMD_1000BASE_X_FD, "1000BASE-{X LX SX CX} fdx"},
{ LLDP_MAU_PMD_1000BASE_T, "1000BASE-T hdx"},
{ LLDP_MAU_PMD_1000BASE_T_FD, "1000BASE-T fdx"},
{ 0, NULL}
};
#define LLDP_MDI_PORT_CLASS (1 << 0)
#define LLDP_MDI_POWER_SUPPORT (1 << 1)
#define LLDP_MDI_POWER_STATE (1 << 2)
#define LLDP_MDI_PAIR_CONTROL_ABILITY (1 << 3)
static const struct tok lldp_mdi_values[] = {
{ LLDP_MDI_PORT_CLASS, "PSE"},
{ LLDP_MDI_POWER_SUPPORT, "supported"},
{ LLDP_MDI_POWER_STATE, "enabled"},
{ LLDP_MDI_PAIR_CONTROL_ABILITY, "can be controlled"},
{ 0, NULL}
};
#define LLDP_MDI_PSE_PORT_POWER_PAIRS_SIGNAL 1
#define LLDP_MDI_PSE_PORT_POWER_PAIRS_SPARE 2
static const struct tok lldp_mdi_power_pairs_values[] = {
{ LLDP_MDI_PSE_PORT_POWER_PAIRS_SIGNAL, "signal"},
{ LLDP_MDI_PSE_PORT_POWER_PAIRS_SPARE, "spare"},
{ 0, NULL}
};
#define LLDP_MDI_POWER_CLASS0 1
#define LLDP_MDI_POWER_CLASS1 2
#define LLDP_MDI_POWER_CLASS2 3
#define LLDP_MDI_POWER_CLASS3 4
#define LLDP_MDI_POWER_CLASS4 5
static const struct tok lldp_mdi_power_class_values[] = {
{ LLDP_MDI_POWER_CLASS0, "class0"},
{ LLDP_MDI_POWER_CLASS1, "class1"},
{ LLDP_MDI_POWER_CLASS2, "class2"},
{ LLDP_MDI_POWER_CLASS3, "class3"},
{ LLDP_MDI_POWER_CLASS4, "class4"},
{ 0, NULL}
};
#define LLDP_AGGREGATION_CAPABILTIY (1 << 0)
#define LLDP_AGGREGATION_STATUS (1 << 1)
static const struct tok lldp_aggregation_values[] = {
{ LLDP_AGGREGATION_CAPABILTIY, "supported"},
{ LLDP_AGGREGATION_STATUS, "enabled"},
{ 0, NULL}
};
/*
* DCBX protocol subtypes.
*/
#define LLDP_DCBX_SUBTYPE_1 1
#define LLDP_DCBX_SUBTYPE_2 2
static const struct tok lldp_dcbx_subtype_values[] = {
{ LLDP_DCBX_SUBTYPE_1, "DCB Capability Exchange Protocol Rev 1" },
{ LLDP_DCBX_SUBTYPE_2, "DCB Capability Exchange Protocol Rev 1.01" },
{ 0, NULL}
};
#define LLDP_DCBX_CONTROL_TLV 1
#define LLDP_DCBX_PRIORITY_GROUPS_TLV 2
#define LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV 3
#define LLDP_DCBX_APPLICATION_TLV 4
/*
* Interface numbering subtypes.
*/
#define LLDP_INTF_NUMB_IFX_SUBTYPE 2
#define LLDP_INTF_NUMB_SYSPORT_SUBTYPE 3
static const struct tok lldp_intf_numb_subtype_values[] = {
{ LLDP_INTF_NUMB_IFX_SUBTYPE, "Interface Index" },
{ LLDP_INTF_NUMB_SYSPORT_SUBTYPE, "System Port Number" },
{ 0, NULL}
};
#define LLDP_INTF_NUM_LEN 5
#define LLDP_EVB_MODE_NOT_SUPPORTED 0
#define LLDP_EVB_MODE_EVB_BRIDGE 1
#define LLDP_EVB_MODE_EVB_STATION 2
#define LLDP_EVB_MODE_RESERVED 3
static const struct tok lldp_evb_mode_values[]={
{ LLDP_EVB_MODE_NOT_SUPPORTED, "Not Supported"},
{ LLDP_EVB_MODE_EVB_BRIDGE, "EVB Bridge"},
{ LLDP_EVB_MODE_EVB_STATION, "EVB Staion"},
{ LLDP_EVB_MODE_RESERVED, "Reserved for future Standardization"},
{ 0, NULL},
};
#define NO_OF_BITS 8
#define LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH 6
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH 25
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH 25
#define LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH 6
#define LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH 5
#define LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH 9
#define LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH 8
#define LLDP_IANA_SUBTYPE_MUDURL 1
static const struct tok lldp_iana_subtype_values[] = {
{ LLDP_IANA_SUBTYPE_MUDURL, "MUD-URL" },
{ 0, NULL }
};
static void
print_ets_priority_assignment_table(netdissect_options *ndo,
const u_char *ptr)
{
ND_PRINT((ndo, "\n\t Priority Assignment Table"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d",
ptr[0]>>4,ptr[0]&0x0f,ptr[1]>>4,ptr[1]&0x0f,ptr[2]>>4,
ptr[2] & 0x0f, ptr[3] >> 4, ptr[3] & 0x0f));
}
static void
print_tc_bandwidth_table(netdissect_options *ndo,
const u_char *ptr)
{
ND_PRINT((ndo, "\n\t TC Bandwidth Table"));
ND_PRINT((ndo, "\n\t TC%% : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7]));
}
static void
print_tsa_assignment_table(netdissect_options *ndo,
const u_char *ptr)
{
ND_PRINT((ndo, "\n\t TSA Assignment Table"));
ND_PRINT((ndo, "\n\t Traffic Class: 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7]));
}
/*
* Print IEEE 802.1 private extensions. (802.1AB annex E)
*/
static int
lldp_private_8021_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
u_int sublen;
u_int tval;
u_int i;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8021_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port vlan id (PVID): %u",
EXTRACT_16BITS(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)",
EXTRACT_16BITS(tptr+5),
bittok2str(lldp_8021_port_protocol_id_values, "none", *(tptr+4)),
*(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan id (VID): %u", EXTRACT_16BITS(tptr + 4)));
if (tlv_len < 7) {
return hexdump;
}
sublen = *(tptr+6);
if (tlv_len < 7+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan name: "));
safeputs(ndo, tptr + 7, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY:
if (tlv_len < 5) {
return hexdump;
}
sublen = *(tptr+4);
if (tlv_len < 5+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t protocol identity: "));
safeputs(ndo, tptr + 5, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Pre-Priority CNPV Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Pre-Priority Ready Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing:%d, CBS:%d, RES:%d, Max TCs:%d",
tval >> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07));
/*Print Priority Assignment Table*/
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table*/
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
/*Print Priority Assignment Table */
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table */
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing: %d, MBC: %d, RES: %d, PFC cap:%d ",
tval >> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f)));
ND_PRINT((ndo, "\n\t PFC Enable"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
if(tlv_len<=LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH){
return hexdump;
}
/* Length of Application Priority Table */
sublen=tlv_len-5;
if(sublen%3!=0){
return hexdump;
}
i=0;
ND_PRINT((ndo, "\n\t Application Priority Table"));
while(i<sublen) {
tval=*(tptr+i+5);
ND_PRINT((ndo, "\n\t Priority: %u, RES: %u, Sel: %u, Protocol ID: %u",
tval >> 5, (tval >> 3) & 0x03, (tval & 0x07),
EXTRACT_16BITS(tptr + i + 5)));
i=i+3;
}
break;
case LLDP_PRIVATE_8021_SUBTYPE_EVB:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH){
return hexdump;
}
ND_PRINT((ndo, "\n\t EVB Bridge Status"));
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t RES: %d, BGID: %d, RRCAP: %d, RRCTR: %d",
tval >> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01));
ND_PRINT((ndo, "\n\t EVB Station Status"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d",
tval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03));
tval=*(tptr+6);
ND_PRINT((ndo, "\n\t R: %d, RTE: %d, ",tval >> 5, tval & 0x1f));
tval=*(tptr+7);
ND_PRINT((ndo, "EVB Mode: %s [%d]",
tok2str(lldp_evb_mode_values, "unknown", tval >> 6), tval >> 6));
ND_PRINT((ndo, "\n\t ROL: %d, RWD: %d, ", (tval >> 5) & 0x01, tval & 0x1f));
tval=*(tptr+8);
ND_PRINT((ndo, "RES: %d, ROL: %d, RKA: %d", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f));
break;
case LLDP_PRIVATE_8021_SUBTYPE_CDCP:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Role: %d, RES: %d, Scomp: %d ",
tval >> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01));
ND_PRINT((ndo, "ChnCap: %d", EXTRACT_16BITS(tptr + 6) & 0x0fff));
sublen=tlv_len-8;
if(sublen%3!=0) {
return hexdump;
}
i=0;
while(i<sublen) {
tval=EXTRACT_24BITS(tptr+i+8);
ND_PRINT((ndo, "\n\t SCID: %d, SVID: %d",
tval >> 12, tval & 0x000fff));
i=i+3;
}
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
/*
* Print IEEE 802.3 private extensions. (802.3bc)
*/
static int
lldp_private_8023_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8023_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8023_SUBTYPE_MACPHY:
if (tlv_len < 9) {
return hexdump;
}
ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)",
bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)),
*(tptr + 4)));
ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)",
bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)),
EXTRACT_16BITS(tptr + 5)));
ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)",
tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)),
EXTRACT_16BITS(tptr + 7)));
break;
case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s",
bittok2str(lldp_mdi_values, "none", *(tptr+4)),
tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)),
tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6))));
break;
case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR:
if (tlv_len < 9) {
return hexdump;
}
ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u",
bittok2str(lldp_aggregation_values, "none", *(tptr+4)),
EXTRACT_32BITS(tptr + 5)));
break;
case LLDP_PRIVATE_8023_SUBTYPE_MTU:
ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4)));
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
/*
* Extract 34bits of latitude/longitude coordinates.
*/
static uint64_t
lldp_extract_latlon(const u_char *tptr)
{
uint64_t latlon;
latlon = *tptr & 0x3;
latlon = (latlon << 32) | EXTRACT_32BITS(tptr+1);
return latlon;
}
/* objects defined in IANA subtype 00 00 5e
* (right now there is only one)
*/
static int
lldp_private_iana_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
if (tlv_len < 8) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_iana_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_IANA_SUBTYPE_MUDURL:
ND_PRINT((ndo, "\n\t MUD-URL="));
(void)fn_printn(ndo, tptr+4, tlv_len-4, NULL);
break;
default:
hexdump=TRUE;
}
return hexdump;
}
/*
* Print private TIA extensions.
*/
static int
lldp_private_tia_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
uint8_t location_format;
uint16_t power_val;
u_int lci_len;
uint8_t ca_type, ca_len;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_tia_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Media capabilities [%s] (0x%04x)",
bittok2str(lldp_tia_capabilities_values, "none",
EXTRACT_16BITS(tptr + 4)), EXTRACT_16BITS(tptr + 4)));
ND_PRINT((ndo, "\n\t Device type [%s] (0x%02x)",
tok2str(lldp_tia_device_type_values, "unknown", *(tptr+6)),
*(tptr + 6)));
break;
case LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY:
if (tlv_len < 8) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Application type [%s] (0x%02x)",
tok2str(lldp_tia_application_type_values, "none", *(tptr+4)),
*(tptr + 4)));
ND_PRINT((ndo, ", Flags [%s]", bittok2str(
lldp_tia_network_policy_bits_values, "none", *(tptr + 5))));
ND_PRINT((ndo, "\n\t Vlan id %u",
LLDP_EXTRACT_NETWORK_POLICY_VLAN(EXTRACT_16BITS(tptr + 5))));
ND_PRINT((ndo, ", L2 priority %u",
LLDP_EXTRACT_NETWORK_POLICY_L2_PRIORITY(EXTRACT_16BITS(tptr + 6))));
ND_PRINT((ndo, ", DSCP value %u",
LLDP_EXTRACT_NETWORK_POLICY_DSCP(EXTRACT_16BITS(tptr + 6))));
break;
case LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID:
if (tlv_len < 5) {
return hexdump;
}
location_format = *(tptr+4);
ND_PRINT((ndo, "\n\t Location data format %s (0x%02x)",
tok2str(lldp_tia_location_data_format_values, "unknown", location_format),
location_format));
switch (location_format) {
case LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED:
if (tlv_len < 21) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Latitude resolution %u, latitude value %" PRIu64,
(*(tptr + 5) >> 2), lldp_extract_latlon(tptr + 5)));
ND_PRINT((ndo, "\n\t Longitude resolution %u, longitude value %" PRIu64,
(*(tptr + 10) >> 2), lldp_extract_latlon(tptr + 10)));
ND_PRINT((ndo, "\n\t Altitude type %s (%u)",
tok2str(lldp_tia_location_altitude_type_values, "unknown",(*(tptr+15)>>4)),
(*(tptr + 15) >> 4)));
ND_PRINT((ndo, "\n\t Altitude resolution %u, altitude value 0x%x",
(EXTRACT_16BITS(tptr+15)>>6)&0x3f,
((EXTRACT_32BITS(tptr + 16) & 0x3fffffff))));
ND_PRINT((ndo, "\n\t Datum %s (0x%02x)",
tok2str(lldp_tia_location_datum_type_values, "unknown", *(tptr+20)),
*(tptr + 20)));
break;
case LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS:
if (tlv_len < 6) {
return hexdump;
}
lci_len = *(tptr+5);
if (lci_len < 3) {
return hexdump;
}
if (tlv_len < 7+lci_len) {
return hexdump;
}
ND_PRINT((ndo, "\n\t LCI length %u, LCI what %s (0x%02x), Country-code ",
lci_len,
tok2str(lldp_tia_location_lci_what_values, "unknown", *(tptr+6)),
*(tptr + 6)));
/* Country code */
safeputs(ndo, tptr + 7, 2);
lci_len = lci_len-3;
tptr = tptr + 9;
/* Decode each civic address element */
while (lci_len > 0) {
if (lci_len < 2) {
return hexdump;
}
ca_type = *(tptr);
ca_len = *(tptr+1);
tptr += 2;
lci_len -= 2;
ND_PRINT((ndo, "\n\t CA type \'%s\' (%u), length %u: ",
tok2str(lldp_tia_location_lci_catype_values, "unknown", ca_type),
ca_type, ca_len));
/* basic sanity check */
if ( ca_type == 0 || ca_len == 0) {
return hexdump;
}
if (lci_len < ca_len) {
return hexdump;
}
safeputs(ndo, tptr, ca_len);
tptr += ca_len;
lci_len -= ca_len;
}
break;
case LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN:
ND_PRINT((ndo, "\n\t ECS ELIN id "));
safeputs(ndo, tptr + 5, tlv_len - 5);
break;
default:
ND_PRINT((ndo, "\n\t Location ID "));
print_unknown_data(ndo, tptr + 5, "\n\t ", tlv_len - 5);
}
break;
case LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Power type [%s]",
(*(tptr + 4) & 0xC0 >> 6) ? "PD device" : "PSE device"));
ND_PRINT((ndo, ", Power source [%s]",
tok2str(lldp_tia_power_source_values, "none", (*(tptr + 4) & 0x30) >> 4)));
ND_PRINT((ndo, "\n\t Power priority [%s] (0x%02x)",
tok2str(lldp_tia_power_priority_values, "none", *(tptr+4)&0x0f),
*(tptr + 4) & 0x0f));
power_val = EXTRACT_16BITS(tptr+5);
if (power_val < LLDP_TIA_POWER_VAL_MAX) {
ND_PRINT((ndo, ", Power %.1f Watts", ((float)power_val) / 10));
} else {
ND_PRINT((ndo, ", Power %u (Reserved)", power_val));
}
break;
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID:
ND_PRINT((ndo, "\n\t %s ",
tok2str(lldp_tia_inventory_values, "unknown", subtype)));
safeputs(ndo, tptr + 4, tlv_len - 4);
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
/*
* Print DCBX Protocol fields (V 1.01).
*/
static int
lldp_private_dcbx_print(netdissect_options *ndo,
const u_char *pptr, u_int len)
{
int subtype, hexdump = FALSE;
uint8_t tval;
uint16_t tlv;
uint32_t i, pgval, uval;
u_int tlen, tlv_type, tlv_len;
const u_char *tptr, *mptr;
if (len < 4) {
return hexdump;
}
subtype = *(pptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_dcbx_subtype_values, "unknown", subtype),
subtype));
/* by passing old version */
if (subtype == LLDP_DCBX_SUBTYPE_1)
return TRUE;
tptr = pptr + 4;
tlen = len - 4;
while (tlen >= sizeof(tlv)) {
ND_TCHECK2(*tptr, sizeof(tlv));
tlv = EXTRACT_16BITS(tptr);
tlv_type = LLDP_EXTRACT_TYPE(tlv);
tlv_len = LLDP_EXTRACT_LEN(tlv);
hexdump = FALSE;
tlen -= sizeof(tlv);
tptr += sizeof(tlv);
/* loop check */
if (!tlv_type || !tlv_len) {
break;
}
ND_TCHECK2(*tptr, tlv_len);
if (tlen < tlv_len) {
goto trunc;
}
/* decode every tlv */
switch (tlv_type) {
case LLDP_DCBX_CONTROL_TLV:
if (tlv_len < 10) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Control - Protocol Control (type 0x%x, length %d)",
LLDP_DCBX_CONTROL_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Sequence Number: %d", EXTRACT_32BITS(tptr + 2)));
ND_PRINT((ndo, "\n\t Acknowledgement Number: %d",
EXTRACT_32BITS(tptr + 6)));
break;
case LLDP_DCBX_PRIORITY_GROUPS_TLV:
if (tlv_len < 17) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Feature - Priority Group (type 0x%x, length %d)",
LLDP_DCBX_PRIORITY_GROUPS_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2)));
tval = *(tptr+2);
ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d",
(tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0,
(tval & 0x20) ? 1 : 0));
ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3)));
ND_PRINT((ndo, "\n\t Priority Allocation"));
/*
* Array of 8 4-bit priority group ID values; we fetch all
* 32 bits and extract each nibble.
*/
pgval = EXTRACT_32BITS(tptr+4);
for (i = 0; i <= 7; i++) {
ND_PRINT((ndo, "\n\t PgId_%d: %d",
i, (pgval >> (28 - 4 * i)) & 0xF));
}
ND_PRINT((ndo, "\n\t Priority Group Allocation"));
for (i = 0; i <= 7; i++)
ND_PRINT((ndo, "\n\t Pg percentage[%d]: %d", i, *(tptr + 8 + i)));
ND_PRINT((ndo, "\n\t NumTCsSupported: %d", *(tptr + 8 + 8)));
break;
case LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV:
if (tlv_len < 6) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Feature - Priority Flow Control"));
ND_PRINT((ndo, " (type 0x%x, length %d)",
LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2)));
tval = *(tptr+2);
ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d",
(tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0,
(tval & 0x20) ? 1 : 0));
ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3)));
tval = *(tptr+4);
ND_PRINT((ndo, "\n\t PFC Config (0x%02X)", *(tptr + 4)));
for (i = 0; i <= 7; i++)
ND_PRINT((ndo, "\n\t Priority Bit %d: %s",
i, (tval & (1 << i)) ? "Enabled" : "Disabled"));
ND_PRINT((ndo, "\n\t NumTCPFCSupported: %d", *(tptr + 5)));
break;
case LLDP_DCBX_APPLICATION_TLV:
if (tlv_len < 4) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Feature - Application (type 0x%x, length %d)",
LLDP_DCBX_APPLICATION_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2)));
tval = *(tptr+2);
ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d",
(tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0,
(tval & 0x20) ? 1 : 0));
ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3)));
tval = tlv_len - 4;
mptr = tptr + 4;
while (tval >= 6) {
ND_PRINT((ndo, "\n\t Application Value"));
ND_PRINT((ndo, "\n\t Application Protocol ID: 0x%04x",
EXTRACT_16BITS(mptr)));
uval = EXTRACT_24BITS(mptr+2);
ND_PRINT((ndo, "\n\t SF (0x%x) Application Protocol ID is %s",
(uval >> 22),
(uval >> 22) ? "Socket Number" : "L2 EtherType"));
ND_PRINT((ndo, "\n\t OUI: 0x%06x", uval & 0x3fffff));
ND_PRINT((ndo, "\n\t User Priority Map: 0x%02x", *(mptr + 5)));
tval = tval - 6;
mptr = mptr + 6;
}
break;
default:
hexdump = TRUE;
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) {
print_unknown_data(ndo, tptr, "\n\t ", tlv_len);
}
tlen -= tlv_len;
tptr += tlv_len;
}
trunc:
return hexdump;
}
static char *
lldp_network_addr_print(netdissect_options *ndo, const u_char *tptr, u_int len)
{
uint8_t af;
static char buf[BUFSIZE];
const char * (*pfunc)(netdissect_options *, const u_char *);
if (len < 1)
return NULL;
len--;
af = *tptr;
switch (af) {
case AFNUM_INET:
if (len < 4)
return NULL;
/* This cannot be assigned to ipaddr_string(), which is a macro. */
pfunc = getname;
break;
case AFNUM_INET6:
if (len < 16)
return NULL;
/* This cannot be assigned to ip6addr_string(), which is a macro. */
pfunc = getname6;
break;
case AFNUM_802:
if (len < 6)
return NULL;
pfunc = etheraddr_string;
break;
default:
pfunc = NULL;
break;
}
if (!pfunc) {
snprintf(buf, sizeof(buf), "AFI %s (%u), no AF printer !",
tok2str(af_values, "Unknown", af), af);
} else {
snprintf(buf, sizeof(buf), "AFI %s (%u): %s",
tok2str(af_values, "Unknown", af), af, (*pfunc)(ndo, tptr+1));
}
return buf;
}
static int
lldp_mgmt_addr_tlv_print(netdissect_options *ndo,
const u_char *pptr, u_int len)
{
uint8_t mgmt_addr_len, intf_num_subtype, oid_len;
const u_char *tptr;
u_int tlen;
char *mgmt_addr;
tlen = len;
tptr = pptr;
if (tlen < 1) {
return 0;
}
mgmt_addr_len = *tptr++;
tlen--;
if (tlen < mgmt_addr_len) {
return 0;
}
mgmt_addr = lldp_network_addr_print(ndo, tptr, mgmt_addr_len);
if (mgmt_addr == NULL) {
return 0;
}
ND_PRINT((ndo, "\n\t Management Address length %u, %s",
mgmt_addr_len, mgmt_addr));
tptr += mgmt_addr_len;
tlen -= mgmt_addr_len;
if (tlen < LLDP_INTF_NUM_LEN) {
return 0;
}
intf_num_subtype = *tptr;
ND_PRINT((ndo, "\n\t %s Interface Numbering (%u): %u",
tok2str(lldp_intf_numb_subtype_values, "Unknown", intf_num_subtype),
intf_num_subtype,
EXTRACT_32BITS(tptr + 1)));
tptr += LLDP_INTF_NUM_LEN;
tlen -= LLDP_INTF_NUM_LEN;
/*
* The OID is optional.
*/
if (tlen) {
oid_len = *tptr;
if (tlen < 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_2703_0 |
crossvul-cpp_data_bad_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)
{
struct sock_exterr_skb *serr;
int err;
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;
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);
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;
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);
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);
}
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/bad_3254_1 |
crossvul-cpp_data_good_5869_0 | /*
* The two pass scaling function is based on:
* Filtered Image Rescaling
* Based on Gems III
* - Schumacher general filtered image rescaling
* (pp. 414-424)
* by Dale Schumacher
*
* Additional changes by Ray Gardener, Daylon Graphics Ltd.
* December 4, 1999
*
* Ported to libgd by Pierre Joye. Support for multiple channels
* added (argb for now).
*
* Initial sources code is avaibable in the Gems Source Code Packages:
* http://www.acm.org/pubs/tog/GraphicsGems/GGemsIII.tar.gz
*
*/
/*
Summary:
- Horizontal filter contributions are calculated on the fly,
as each column is mapped from src to dst image. This lets
us omit having to allocate a temporary full horizontal stretch
of the src image.
- If none of the src pixels within a sampling region differ,
then the output pixel is forced to equal (any of) the source pixel.
This ensures that filters do not corrupt areas of constant color.
- Filter weight contribution results, after summing, are
rounded to the nearest pixel color value instead of
being casted to ILubyte (usually an int or char). Otherwise,
artifacting occurs.
*/
/*
Additional functions are available for simple rotation or up/downscaling.
downscaling using the fixed point implementations are usually much faster
than the existing gdImageCopyResampled while having a similar or better
quality.
For image rotations, the optimized versions have a lazy antialiasing for
the edges of the images. For a much better antialiased result, the affine
function is recommended.
*/
/*
TODO:
- Optimize pixel accesses and loops once we have continuous buffer
- Add scale support for a portion only of an image (equivalent of copyresized/resampled)
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "gd.h"
#include "gdhelpers.h"
#ifdef _MSC_VER
# pragma optimize("t", on)
# include <emmintrin.h>
#endif
#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#define MIN3(a,b,c) ((a)<(b)?(MIN(a,c)):(MIN(b,c)))
#ifndef MAX
#define MAX(a,b) ((a)<(b)?(b):(a))
#endif
#define MAX3(a,b,c) ((a)<(b)?(MAX(b,c)):(MAX(a,c)))
#define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))
/* only used here, let do a generic fixed point integers later if required by other
part of GD */
typedef long gdFixed;
/* Integer to fixed point */
#define gd_itofx(x) ((x) << 8)
/* Float to fixed point */
#define gd_ftofx(x) (long)((x) * 256)
/* Double to fixed point */
#define gd_dtofx(x) (long)((x) * 256)
/* Fixed point to integer */
#define gd_fxtoi(x) ((x) >> 8)
/* Fixed point to float */
# define gd_fxtof(x) ((float)(x) / 256)
/* Fixed point to double */
#define gd_fxtod(x) ((double)(x) / 256)
/* Multiply a fixed by a fixed */
#define gd_mulfx(x,y) (((x) * (y)) >> 8)
/* Divide a fixed by a fixed */
#define gd_divfx(x,y) (((x) << 8) / (y))
typedef struct
{
double *Weights; /* Normalized weights of neighboring pixels */
int Left,Right; /* Bounds of source pixels window */
} ContributionType; /* Contirbution information for a single pixel */
typedef struct
{
ContributionType *ContribRow; /* Row (or column) of contribution weights */
unsigned int WindowSize, /* Filter window size (of affecting source pixels) */
LineLength; /* Length of line (no. or rows / cols) */
} LineContribType;
/* Each core filter has its own radius */
#define DEFAULT_FILTER_BICUBIC 3.0
#define DEFAULT_FILTER_BOX 0.5
#define DEFAULT_FILTER_GENERALIZED_CUBIC 0.5
#define DEFAULT_FILTER_RADIUS 1.0
#define DEFAULT_LANCZOS8_RADIUS 8.0
#define DEFAULT_LANCZOS3_RADIUS 3.0
#define DEFAULT_HERMITE_RADIUS 1.0
#define DEFAULT_BOX_RADIUS 0.5
#define DEFAULT_TRIANGLE_RADIUS 1.0
#define DEFAULT_BELL_RADIUS 1.5
#define DEFAULT_CUBICSPLINE_RADIUS 2.0
#define DEFAULT_MITCHELL_RADIUS 2.0
#define DEFAULT_COSINE_RADIUS 1.0
#define DEFAULT_CATMULLROM_RADIUS 2.0
#define DEFAULT_QUADRATIC_RADIUS 1.5
#define DEFAULT_QUADRATICBSPLINE_RADIUS 1.5
#define DEFAULT_CUBICCONVOLUTION_RADIUS 3.0
#define DEFAULT_GAUSSIAN_RADIUS 1.0
#define DEFAULT_HANNING_RADIUS 1.0
#define DEFAULT_HAMMING_RADIUS 1.0
#define DEFAULT_SINC_RADIUS 1.0
#define DEFAULT_WELSH_RADIUS 1.0
enum GD_RESIZE_FILTER_TYPE{
FILTER_DEFAULT = 0,
FILTER_BELL,
FILTER_BESSEL,
FILTER_BLACKMAN,
FILTER_BOX,
FILTER_BSPLINE,
FILTER_CATMULLROM,
FILTER_COSINE,
FILTER_CUBICCONVOLUTION,
FILTER_CUBICSPLINE,
FILTER_HERMITE,
FILTER_LANCZOS3,
FILTER_LANCZOS8,
FILTER_MITCHELL,
FILTER_QUADRATIC,
FILTER_QUADRATICBSPLINE,
FILTER_TRIANGLE,
FILTER_GAUSSIAN,
FILTER_HANNING,
FILTER_HAMMING,
FILTER_SINC,
FILTER_WELSH,
FILTER_CALLBACK = 999
};
typedef enum GD_RESIZE_FILTER_TYPE gdResizeFilterType;
static double KernelBessel_J1(const double x)
{
double p, q;
register long i;
static const double
Pone[] =
{
0.581199354001606143928050809e+21,
-0.6672106568924916298020941484e+20,
0.2316433580634002297931815435e+19,
-0.3588817569910106050743641413e+17,
0.2908795263834775409737601689e+15,
-0.1322983480332126453125473247e+13,
0.3413234182301700539091292655e+10,
-0.4695753530642995859767162166e+7,
0.270112271089232341485679099e+4
},
Qone[] =
{
0.11623987080032122878585294e+22,
0.1185770712190320999837113348e+20,
0.6092061398917521746105196863e+17,
0.2081661221307607351240184229e+15,
0.5243710262167649715406728642e+12,
0.1013863514358673989967045588e+10,
0.1501793594998585505921097578e+7,
0.1606931573481487801970916749e+4,
0.1e+1
};
p = Pone[8];
q = Qone[8];
for (i=7; i >= 0; i--)
{
p = p*x*x+Pone[i];
q = q*x*x+Qone[i];
}
return (double)(p/q);
}
static double KernelBessel_P1(const double x)
{
double p, q;
register long i;
static const double
Pone[] =
{
0.352246649133679798341724373e+5,
0.62758845247161281269005675e+5,
0.313539631109159574238669888e+5,
0.49854832060594338434500455e+4,
0.2111529182853962382105718e+3,
0.12571716929145341558495e+1
},
Qone[] =
{
0.352246649133679798068390431e+5,
0.626943469593560511888833731e+5,
0.312404063819041039923015703e+5,
0.4930396490181088979386097e+4,
0.2030775189134759322293574e+3,
0.1e+1
};
p = Pone[5];
q = Qone[5];
for (i=4; i >= 0; i--)
{
p = p*(8.0/x)*(8.0/x)+Pone[i];
q = q*(8.0/x)*(8.0/x)+Qone[i];
}
return (double)(p/q);
}
static double KernelBessel_Q1(const double x)
{
double p, q;
register long i;
static const double
Pone[] =
{
0.3511751914303552822533318e+3,
0.7210391804904475039280863e+3,
0.4259873011654442389886993e+3,
0.831898957673850827325226e+2,
0.45681716295512267064405e+1,
0.3532840052740123642735e-1
},
Qone[] =
{
0.74917374171809127714519505e+4,
0.154141773392650970499848051e+5,
0.91522317015169922705904727e+4,
0.18111867005523513506724158e+4,
0.1038187585462133728776636e+3,
0.1e+1
};
p = Pone[5];
q = Qone[5];
for (i=4; i >= 0; i--)
{
p = p*(8.0/x)*(8.0/x)+Pone[i];
q = q*(8.0/x)*(8.0/x)+Qone[i];
}
return (double)(p/q);
}
static double KernelBessel_Order1(double x)
{
double p, q;
if (x == 0.0)
return (0.0f);
p = x;
if (x < 0.0)
x=(-x);
if (x < 8.0)
return (p*KernelBessel_J1(x));
q = (double)sqrt(2.0f/(M_PI*x))*(double)(KernelBessel_P1(x)*(1.0f/sqrt(2.0f)*(sin(x)-cos(x)))-8.0f/x*KernelBessel_Q1(x)*
(-1.0f/sqrt(2.0f)*(sin(x)+cos(x))));
if (p < 0.0f)
q = (-q);
return (q);
}
static double filter_bessel(const double x)
{
if (x == 0.0f)
return (double)(M_PI/4.0f);
return (KernelBessel_Order1((double)M_PI*x)/(2.0f*x));
}
static double filter_blackman(const double x)
{
return (0.42f+0.5f*(double)cos(M_PI*x)+0.08f*(double)cos(2.0f*M_PI*x));
}
/**
* Bicubic interpolation kernel (a=-1):
\verbatim
/
| 1-2|t|**2+|t|**3 , if |t| < 1
h(t) = | 4-8|t|+5|t|**2-|t|**3 , if 1<=|t|<2
| 0 , otherwise
\
\endverbatim
* ***bd*** 2.2004
*/
static double filter_bicubic(const double t)
{
const double abs_t = (double)fabs(t);
const double abs_t_sq = abs_t * abs_t;
if (abs_t<1) return 1-2*abs_t_sq+abs_t_sq*abs_t;
if (abs_t<2) return 4 - 8*abs_t +5*abs_t_sq - abs_t_sq*abs_t;
return 0;
}
/**
* Generalized cubic kernel (for a=-1 it is the same as BicubicKernel):
\verbatim
/
| (a+2)|t|**3 - (a+3)|t|**2 + 1 , |t| <= 1
h(t) = | a|t|**3 - 5a|t|**2 + 8a|t| - 4a , 1 < |t| <= 2
| 0 , otherwise
\
\endverbatim
* Often used values for a are -1 and -1/2.
*/
static double filter_generalized_cubic(const double t)
{
const double a = -DEFAULT_FILTER_GENERALIZED_CUBIC;
double abs_t = (double)fabs(t);
double abs_t_sq = abs_t * abs_t;
if (abs_t < 1) return (a + 2) * abs_t_sq * abs_t - (a + 3) * abs_t_sq + 1;
if (abs_t < 2) return a * abs_t_sq * abs_t - 5 * a * abs_t_sq + 8 * a * abs_t - 4 * a;
return 0;
}
#ifdef FUNCTION_NOT_USED_YET
/* CubicSpline filter, default radius 2 */
static double filter_cubic_spline(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 1.0 ) {
const double x2 = x*x;
return (0.5 * x2 * x - x2 + 2.0 / 3.0);
}
if (x < 2.0) {
return (pow(2.0 - x, 3.0)/6.0);
}
return 0;
}
#endif
#ifdef FUNCTION_NOT_USED_YET
/* CubicConvolution filter, default radius 3 */
static double filter_cubic_convolution(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
const double x2 = x1 * x1;
const double x2_x = x2 * x;
if (x <= 1.0) return ((4.0 / 3.0)* x2_x - (7.0 / 3.0) * x2 + 1.0);
if (x <= 2.0) return (- (7.0 / 12.0) * x2_x + 3 * x2 - (59.0 / 12.0) * x + 2.5);
if (x <= 3.0) return ( (1.0/12.0) * x2_x - (2.0 / 3.0) * x2 + 1.75 * x - 1.5);
return 0;
}
#endif
static double filter_box(double x) {
if (x < - DEFAULT_FILTER_BOX)
return 0.0f;
if (x < DEFAULT_FILTER_BOX)
return 1.0f;
return 0.0f;
}
static double filter_catmullrom(const double x)
{
if (x < -2.0)
return(0.0f);
if (x < -1.0)
return(0.5f*(4.0f+x*(8.0f+x*(5.0f+x))));
if (x < 0.0)
return(0.5f*(2.0f+x*x*(-5.0f-3.0f*x)));
if (x < 1.0)
return(0.5f*(2.0f+x*x*(-5.0f+3.0f*x)));
if (x < 2.0)
return(0.5f*(4.0f+x*(-8.0f+x*(5.0f-x))));
return(0.0f);
}
#ifdef FUNCTION_NOT_USED_YET
static double filter_filter(double t)
{
/* f(t) = 2|t|^3 - 3|t|^2 + 1, -1 <= t <= 1 */
if(t < 0.0) t = -t;
if(t < 1.0) return((2.0 * t - 3.0) * t * t + 1.0);
return(0.0);
}
#endif
#ifdef FUNCTION_NOT_USED_YET
/* Lanczos8 filter, default radius 8 */
static double filter_lanczos8(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
#define R DEFAULT_LANCZOS8_RADIUS
if ( x == 0.0) return 1;
if ( x < R) {
return R * sin(x*M_PI) * sin(x * M_PI/ R) / (x * M_PI * x * M_PI);
}
return 0.0;
#undef R
}
#endif
#ifdef FUNCTION_NOT_USED_YET
/* Lanczos3 filter, default radius 3 */
static double filter_lanczos3(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
#define R DEFAULT_LANCZOS3_RADIUS
if ( x == 0.0) return 1;
if ( x < R)
{
return R * sin(x*M_PI) * sin(x * M_PI / R) / (x * M_PI * x * M_PI);
}
return 0.0;
#undef R
}
#endif
/* Hermite filter, default radius 1 */
static double filter_hermite(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 1.0) return ((2.0 * x - 3) * x * x + 1.0 );
return 0.0;
}
/* Trangle filter, default radius 1 */
static double filter_triangle(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 1.0) return (1.0 - x);
return 0.0;
}
/* Bell filter, default radius 1.5 */
static double filter_bell(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 0.5) return (0.75 - x*x);
if (x < 1.5) return (0.5 * pow(x - 1.5, 2.0));
return 0.0;
}
/* Mitchell filter, default radius 2.0 */
static double filter_mitchell(const double x)
{
#define KM_B (1.0f/3.0f)
#define KM_C (1.0f/3.0f)
#define KM_P0 (( 6.0f - 2.0f * KM_B ) / 6.0f)
#define KM_P2 ((-18.0f + 12.0f * KM_B + 6.0f * KM_C) / 6.0f)
#define KM_P3 (( 12.0f - 9.0f * KM_B - 6.0f * KM_C) / 6.0f)
#define KM_Q0 (( 8.0f * KM_B + 24.0f * KM_C) / 6.0f)
#define KM_Q1 ((-12.0f * KM_B - 48.0f * KM_C) / 6.0f)
#define KM_Q2 (( 6.0f * KM_B + 30.0f * KM_C) / 6.0f)
#define KM_Q3 (( -1.0f * KM_B - 6.0f * KM_C) / 6.0f)
if (x < -2.0)
return(0.0f);
if (x < -1.0)
return(KM_Q0-x*(KM_Q1-x*(KM_Q2-x*KM_Q3)));
if (x < 0.0f)
return(KM_P0+x*x*(KM_P2-x*KM_P3));
if (x < 1.0f)
return(KM_P0+x*x*(KM_P2+x*KM_P3));
if (x < 2.0f)
return(KM_Q0+x*(KM_Q1+x*(KM_Q2+x*KM_Q3)));
return(0.0f);
}
#ifdef FUNCTION_NOT_USED_YET
/* Cosine filter, default radius 1 */
static double filter_cosine(const double x)
{
if ((x >= -1.0) && (x <= 1.0)) return ((cos(x * M_PI) + 1.0)/2.0);
return 0;
}
#endif
/* Quadratic filter, default radius 1.5 */
static double filter_quadratic(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x <= 0.5) return (- 2.0 * x * x + 1);
if (x <= 1.5) return (x * x - 2.5* x + 1.5);
return 0.0;
}
static double filter_bspline(const double x)
{
if (x>2.0f) {
return 0.0f;
} else {
double a, b, c, d;
/* Was calculated anyway cause the "if((x-1.0f) < 0)" */
const double xm1 = x - 1.0f;
const double xp1 = x + 1.0f;
const double xp2 = x + 2.0f;
if ((xp2) <= 0.0f) a = 0.0f; else a = xp2*xp2*xp2;
if ((xp1) <= 0.0f) b = 0.0f; else b = xp1*xp1*xp1;
if (x <= 0) c = 0.0f; else c = x*x*x;
if ((xm1) <= 0.0f) d = 0.0f; else d = xm1*xm1*xm1;
return (0.16666666666666666667f * (a - (4.0f * b) + (6.0f * c) - (4.0f * d)));
}
}
#ifdef FUNCTION_NOT_USED_YET
/* QuadraticBSpline filter, default radius 1.5 */
static double filter_quadratic_bspline(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x <= 0.5) return (- x * x + 0.75);
if (x <= 1.5) return (0.5 * x * x - 1.5 * x + 1.125);
return 0.0;
}
#endif
static double filter_gaussian(const double x)
{
/* return(exp((double) (-2.0 * x * x)) * sqrt(2.0 / M_PI)); */
return (double)(exp(-2.0f * x * x) * 0.79788456080287f);
}
static double filter_hanning(const double x)
{
/* A Cosine windowing function */
return(0.5 + 0.5 * cos(M_PI * x));
}
static double filter_hamming(const double x)
{
/* should be
(0.54+0.46*cos(M_PI*(double) x));
but this approximation is sufficient */
if (x < -1.0f)
return 0.0f;
if (x < 0.0f)
return 0.92f*(-2.0f*x-3.0f)*x*x+1.0f;
if (x < 1.0f)
return 0.92f*(2.0f*x-3.0f)*x*x+1.0f;
return 0.0f;
}
static double filter_power(const double x)
{
const double a = 2.0f;
if (fabs(x)>1) return 0.0f;
return (1.0f - (double)fabs(pow(x,a)));
}
static double filter_sinc(const double x)
{
/* X-scaled Sinc(x) function. */
if (x == 0.0) return(1.0);
return (sin(M_PI * (double) x) / (M_PI * (double) x));
}
#ifdef FUNCTION_NOT_USED_YET
static double filter_welsh(const double x)
{
/* Welsh parabolic windowing filter */
if (x < 1.0)
return(1 - x*x);
return(0.0);
}
#endif
#if defined(_MSC_VER) && !defined(inline)
# define inline __inline
#endif
/* Copied from upstream's libgd */
static inline int _color_blend (const int dst, const int src)
{
const int src_alpha = gdTrueColorGetAlpha(src);
if( src_alpha == gdAlphaOpaque ) {
return src;
} else {
const int dst_alpha = gdTrueColorGetAlpha(dst);
if( src_alpha == gdAlphaTransparent ) return dst;
if( dst_alpha == gdAlphaTransparent ) {
return src;
} else {
register int alpha, red, green, blue;
const int src_weight = gdAlphaTransparent - src_alpha;
const int dst_weight = (gdAlphaTransparent - dst_alpha) * src_alpha / gdAlphaMax;
const int tot_weight = src_weight + dst_weight;
alpha = src_alpha * dst_alpha / gdAlphaMax;
red = (gdTrueColorGetRed(src) * src_weight
+ gdTrueColorGetRed(dst) * dst_weight) / tot_weight;
green = (gdTrueColorGetGreen(src) * src_weight
+ gdTrueColorGetGreen(dst) * dst_weight) / tot_weight;
blue = (gdTrueColorGetBlue(src) * src_weight
+ gdTrueColorGetBlue(dst) * dst_weight) / tot_weight;
return ((alpha << 24) + (red << 16) + (green << 8) + blue);
}
}
}
static inline int _setEdgePixel(const gdImagePtr src, unsigned int x, unsigned int y, gdFixed coverage, const int bgColor)
{
const gdFixed f_127 = gd_itofx(127);
register int c = src->tpixels[y][x];
c = c | (( (int) (gd_fxtof(gd_mulfx(coverage, f_127)) + 50.5f)) << 24);
return _color_blend(bgColor, c);
}
static inline int getPixelOverflowTC(gdImagePtr im, const int x, const int y, const int bgColor)
{
if (gdImageBoundsSafe(im, x, y)) {
const int c = im->tpixels[y][x];
if (c == im->transparent) {
return bgColor == -1 ? gdTrueColorAlpha(0, 0, 0, 127) : bgColor;
}
return c;
} else {
register int border = 0;
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y > im->cy2) {
if (x >= im->cx1 && x <= im->cx1) {
border = im->tpixels[im->cy2][x];
goto processborder;
} else {
return gdTrueColorAlpha(0, 0, 0, 127);
}
}
/* y is bound safe at this point */
if (x < im->cx1) {
border = im->tpixels[y][im->cx1];
goto processborder;
}
if (x > im->cx2) {
border = im->tpixels[y][im->cx2];
}
processborder:
if (border == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
} else{
return gdTrueColorAlpha(gdTrueColorGetRed(border), gdTrueColorGetGreen(border), gdTrueColorGetBlue(border), 127);
}
}
}
#define colorIndex2RGBA(c) gdTrueColorAlpha(im->red[(c)], im->green[(c)], im->blue[(c)], im->alpha[(c)])
#define colorIndex2RGBcustomA(c, a) gdTrueColorAlpha(im->red[(c)], im->green[(c)], im->blue[(c)], im->alpha[(a)])
static inline int getPixelOverflowPalette(gdImagePtr im, const int x, const int y, const int bgColor)
{
if (gdImageBoundsSafe(im, x, y)) {
const int c = im->pixels[y][x];
if (c == im->transparent) {
return bgColor == -1 ? gdTrueColorAlpha(0, 0, 0, 127) : bgColor;
}
return colorIndex2RGBA(c);
} else {
register int border = 0;
if (y < im->cy1) {
border = gdImageGetPixel(im, im->cx1, 0);
goto processborder;
}
if (y < im->cy1) {
border = gdImageGetPixel(im, im->cx1, 0);
goto processborder;
}
if (y > im->cy2) {
if (x >= im->cx1 && x <= im->cx1) {
border = gdImageGetPixel(im, x, im->cy2);
goto processborder;
} else {
return gdTrueColorAlpha(0, 0, 0, 127);
}
}
/* y is bound safe at this point */
if (x < im->cx1) {
border = gdImageGetPixel(im, im->cx1, y);
goto processborder;
}
if (x > im->cx2) {
border = gdImageGetPixel(im, im->cx2, y);
}
processborder:
if (border == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
} else{
return colorIndex2RGBcustomA(border, 127);
}
}
}
static int getPixelInterpolateWeight(gdImagePtr im, const double x, const double y, const int bgColor)
{
/* Closest pixel <= (xf,yf) */
int sx = (int)(x);
int sy = (int)(y);
const double xf = x - (double)sx;
const double yf = y - (double)sy;
const double nxf = (double) 1.0 - xf;
const double nyf = (double) 1.0 - yf;
const double m1 = xf * yf;
const double m2 = nxf * yf;
const double m3 = xf * nyf;
const double m4 = nxf * nyf;
/* get color values of neighbouring pixels */
const int c1 = im->trueColor == 1 ? getPixelOverflowTC(im, sx, sy, bgColor) : getPixelOverflowPalette(im, sx, sy, bgColor);
const int c2 = im->trueColor == 1 ? getPixelOverflowTC(im, sx - 1, sy, bgColor) : getPixelOverflowPalette(im, sx - 1, sy, bgColor);
const int c3 = im->trueColor == 1 ? getPixelOverflowTC(im, sx, sy - 1, bgColor) : getPixelOverflowPalette(im, sx, sy - 1, bgColor);
const int c4 = im->trueColor == 1 ? getPixelOverflowTC(im, sx - 1, sy - 1, bgColor) : getPixelOverflowPalette(im, sx, sy - 1, bgColor);
int r, g, b, a;
if (x < 0) sx--;
if (y < 0) sy--;
/* component-wise summing-up of color values */
if (im->trueColor) {
r = (int)(m1*gdTrueColorGetRed(c1) + m2*gdTrueColorGetRed(c2) + m3*gdTrueColorGetRed(c3) + m4*gdTrueColorGetRed(c4));
g = (int)(m1*gdTrueColorGetGreen(c1) + m2*gdTrueColorGetGreen(c2) + m3*gdTrueColorGetGreen(c3) + m4*gdTrueColorGetGreen(c4));
b = (int)(m1*gdTrueColorGetBlue(c1) + m2*gdTrueColorGetBlue(c2) + m3*gdTrueColorGetBlue(c3) + m4*gdTrueColorGetBlue(c4));
a = (int)(m1*gdTrueColorGetAlpha(c1) + m2*gdTrueColorGetAlpha(c2) + m3*gdTrueColorGetAlpha(c3) + m4*gdTrueColorGetAlpha(c4));
} else {
r = (int)(m1*im->red[(c1)] + m2*im->red[(c2)] + m3*im->red[(c3)] + m4*im->red[(c4)]);
g = (int)(m1*im->green[(c1)] + m2*im->green[(c2)] + m3*im->green[(c3)] + m4*im->green[(c4)]);
b = (int)(m1*im->blue[(c1)] + m2*im->blue[(c2)] + m3*im->blue[(c3)] + m4*im->blue[(c4)]);
a = (int)(m1*im->alpha[(c1)] + m2*im->alpha[(c2)] + m3*im->alpha[(c3)] + m4*im->alpha[(c4)]);
}
r = CLAMP(r, 0, 255);
g = CLAMP(g, 0, 255);
b = CLAMP(b, 0, 255);
a = CLAMP(a, 0, gdAlphaMax);
return gdTrueColorAlpha(r, g, b, a);
}
/**
* Function: getPixelInterpolated
* Returns the interpolated color value using the default interpolation
* method. The returned color is always in the ARGB format (truecolor).
*
* Parameters:
* im - Image to set the default interpolation method
* y - X value of the ideal position
* y - Y value of the ideal position
* method - Interpolation method <gdInterpolationMethod>
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*
* See also:
* <gdSetInterpolationMethod>
*/
int getPixelInterpolated(gdImagePtr im, const double x, const double y, const int bgColor)
{
const int xi=(int)((x) < 0 ? x - 1: x);
const int yi=(int)((y) < 0 ? y - 1: y);
int yii;
int i;
double kernel, kernel_cache_y;
double kernel_x[12], kernel_y[4];
double new_r = 0.0f, new_g = 0.0f, new_b = 0.0f, new_a = 0.0f;
/* These methods use special implementations */
if (im->interpolation_id == GD_BILINEAR_FIXED || im->interpolation_id == GD_BICUBIC_FIXED || im->interpolation_id == GD_NEAREST_NEIGHBOUR) {
return -1;
}
if (im->interpolation_id == GD_WEIGHTED4) {
return getPixelInterpolateWeight(im, x, y, bgColor);
}
if (im->interpolation_id == GD_NEAREST_NEIGHBOUR) {
if (im->trueColor == 1) {
return getPixelOverflowTC(im, xi, yi, bgColor);
} else {
return getPixelOverflowPalette(im, xi, yi, bgColor);
}
}
if (im->interpolation) {
for (i=0; i<4; i++) {
kernel_x[i] = (double) im->interpolation((double)(xi+i-1-x));
kernel_y[i] = (double) im->interpolation((double)(yi+i-1-y));
}
} else {
return -1;
}
/*
* TODO: use the known fast rgba multiplication implementation once
* the new formats are in place
*/
for (yii = yi-1; yii < yi+3; yii++) {
int xii;
kernel_cache_y = kernel_y[yii-(yi-1)];
if (im->trueColor) {
for (xii=xi-1; xii<xi+3; xii++) {
const int rgbs = getPixelOverflowTC(im, xii, yii, bgColor);
kernel = kernel_cache_y * kernel_x[xii-(xi-1)];
new_r += kernel * gdTrueColorGetRed(rgbs);
new_g += kernel * gdTrueColorGetGreen(rgbs);
new_b += kernel * gdTrueColorGetBlue(rgbs);
new_a += kernel * gdTrueColorGetAlpha(rgbs);
}
} else {
for (xii=xi-1; xii<xi+3; xii++) {
const int rgbs = getPixelOverflowPalette(im, xii, yii, bgColor);
kernel = kernel_cache_y * kernel_x[xii-(xi-1)];
new_r += kernel * gdTrueColorGetRed(rgbs);
new_g += kernel * gdTrueColorGetGreen(rgbs);
new_b += kernel * gdTrueColorGetBlue(rgbs);
new_a += kernel * gdTrueColorGetAlpha(rgbs);
}
}
}
new_r = CLAMP(new_r, 0, 255);
new_g = CLAMP(new_g, 0, 255);
new_b = CLAMP(new_b, 0, 255);
new_a = CLAMP(new_a, 0, gdAlphaMax);
return gdTrueColorAlpha(((int)new_r), ((int)new_g), ((int)new_b), ((int)new_a));
}
static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size)
{
unsigned int u = 0;
LineContribType *res;
res = (LineContribType *) gdMalloc(sizeof(LineContribType));
if (!res) {
return NULL;
}
res->WindowSize = windows_size;
res->LineLength = line_length;
res->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType));
for (u = 0 ; u < line_length ; u++) {
res->ContribRow[u].Weights = (double *) gdMalloc(windows_size * sizeof(double));
}
return res;
}
static inline void _gdContributionsFree(LineContribType * p)
{
unsigned int u;
for (u = 0; u < p->LineLength; u++) {
gdFree(p->ContribRow[u].Weights);
}
gdFree(p->ContribRow);
gdFree(p);
}
static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)
{
double width_d;
double scale_f_d = 1.0;
const double filter_width_d = DEFAULT_BOX_RADIUS;
int windows_size;
unsigned int u;
LineContribType *res;
if (scale_d < 1.0) {
width_d = filter_width_d / scale_d;
scale_f_d = scale_d;
} else {
width_d= filter_width_d;
}
windows_size = 2 * (int)ceil(width_d) + 1;
res = _gdContributionsAlloc(line_size, windows_size);
for (u = 0; u < line_size; u++) {
const double dCenter = (double)u / scale_d;
/* get the significant edge points affecting the pixel */
register int iLeft = MAX(0, (int)floor (dCenter - width_d));
int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);
double dTotalWeight = 0.0;
int iSrc;
/* Cut edge points to fit in filter window in case of spill-off */
if (iRight - iLeft + 1 > windows_size) {
if (iLeft < ((int)src_size - 1 / 2)) {
iLeft++;
} else {
iRight--;
}
}
res->ContribRow[u].Left = iLeft;
res->ContribRow[u].Right = iRight;
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));
}
if (dTotalWeight < 0.0) {
_gdContributionsFree(res);
return NULL;
}
if (dTotalWeight > 0.0) {
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;
}
}
}
return res;
}
static inline void _gdScaleRow(gdImagePtr pSrc, unsigned int src_width, gdImagePtr dst, unsigned int dst_width, unsigned int row, LineContribType *contrib)
{
int *p_src_row = pSrc->tpixels[row];
int *p_dst_row = dst->tpixels[row];
unsigned int x;
for (x = 0; x < dst_width - 1; x++) {
register unsigned char r = 0, g = 0, b = 0, a = 0;
const int left = contrib->ContribRow[x].Left;
const int right = contrib->ContribRow[x].Right;
int i;
/* Accumulate each channel */
for (i = left; i <= right; i++) {
const int left_channel = i - left;
r += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetRed(p_src_row[i])));
g += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetGreen(p_src_row[i])));
b += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetBlue(p_src_row[i])));
a += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetAlpha(p_src_row[i])));
}
p_dst_row[x] = gdTrueColorAlpha(r, g, b, a);
}
}
static inline void _gdScaleHoriz(gdImagePtr pSrc, unsigned int src_width, unsigned int src_height, gdImagePtr pDst, unsigned int dst_width, unsigned int dst_height)
{
unsigned int u;
LineContribType * contrib;
/* same width, just copy it */
if (dst_width == src_width) {
unsigned int y;
for (y = 0; y < src_height - 1; ++y) {
memcpy(pDst->tpixels[y], pSrc->tpixels[y], src_width);
}
}
contrib = _gdContributionsCalc(dst_width, src_width, (double)dst_width / (double)src_width, pSrc->interpolation);
if (contrib == NULL) {
return;
}
/* Scale each row */
for (u = 0; u < dst_height - 1; u++) {
_gdScaleRow(pSrc, src_width, pDst, dst_width, u, contrib);
}
_gdContributionsFree (contrib);
}
static inline void _gdScaleCol (gdImagePtr pSrc, unsigned int src_width, gdImagePtr pRes, unsigned int dst_width, unsigned int dst_height, unsigned int uCol, LineContribType *contrib)
{
unsigned int y;
for (y = 0; y < dst_height - 1; y++) {
register unsigned char r = 0, g = 0, b = 0, a = 0;
const int iLeft = contrib->ContribRow[y].Left;
const int iRight = contrib->ContribRow[y].Right;
int i;
/* Accumulate each channel */
for (i = iLeft; i <= iRight; i++) {
const int pCurSrc = pSrc->tpixels[i][uCol];
const int i_iLeft = i - iLeft;
r += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetRed(pCurSrc)));
g += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetGreen(pCurSrc)));
b += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetBlue(pCurSrc)));
a += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetAlpha(pCurSrc)));
}
pRes->tpixels[y][uCol] = gdTrueColorAlpha(r, g, b, a);
}
}
static inline void _gdScaleVert (const gdImagePtr pSrc, const unsigned int src_width, const unsigned int src_height, const gdImagePtr pDst, const unsigned int dst_width, const unsigned int dst_height)
{
unsigned int u;
LineContribType * contrib;
/* same height, copy it */
if (src_height == dst_height) {
unsigned int y;
for (y = 0; y < src_height - 1; ++y) {
memcpy(pDst->tpixels[y], pSrc->tpixels[y], src_width);
}
}
contrib = _gdContributionsCalc(dst_height, src_height, (double)(dst_height) / (double)(src_height), pSrc->interpolation);
/* scale each column */
for (u = 0; u < dst_width - 1; u++) {
_gdScaleCol(pSrc, src_width, pDst, dst_width, dst_height, u, contrib);
}
_gdContributionsFree(contrib);
}
gdImagePtr gdImageScaleTwoPass(const gdImagePtr src, const unsigned int src_width, const unsigned int src_height, const unsigned int new_width, const unsigned int new_height)
{
gdImagePtr tmp_im;
gdImagePtr dst;
tmp_im = gdImageCreateTrueColor(new_width, src_height);
if (tmp_im == NULL) {
return NULL;
}
gdImageSetInterpolationMethod(tmp_im, src->interpolation_id);
_gdScaleHoriz(src, src_width, src_height, tmp_im, new_width, src_height);
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst == NULL) {
gdFree(tmp_im);
return NULL;
}
_gdScaleVert(tmp_im, new_width, src_height, dst, new_width, new_height);
gdFree(tmp_im);
return dst;
}
gdImagePtr Scale(const gdImagePtr src, const unsigned int src_width, const unsigned int src_height, const gdImagePtr dst, const unsigned int new_width, const unsigned int new_height)
{
gdImagePtr tmp_im;
tmp_im = gdImageCreateTrueColor(new_width, src_height);
if (tmp_im == NULL) {
return NULL;
}
_gdScaleHoriz(src, src_width, src_height, tmp_im, new_width, src_height);
_gdScaleVert(tmp_im, new_width, src_height, dst, new_width, new_height);
gdFree(tmp_im);
return dst;
}
/*
BilinearFixed, BicubicFixed and nearest implementations are rewamped versions of the implementation in CBitmapEx
http://www.codeproject.com/Articles/29121/CBitmapEx-Free-C-Bitmap-Manipulation-Class
Integer only implementation, good to have for common usages like pre scale very large
images before using another interpolation methods for the last step.
*/
gdImagePtr gdImageScaleNearestNeighbour(gdImagePtr im, const unsigned int width, const unsigned int height)
{
const unsigned long new_width = MAX(1, width);
const unsigned long new_height = MAX(1, height);
const float dx = (float)im->sx / (float)new_width;
const float dy = (float)im->sy / (float)new_height;
const gdFixed f_dx = gd_ftofx(dx);
const gdFixed f_dy = gd_ftofx(dy);
gdImagePtr dst_img;
unsigned long dst_offset_x;
unsigned long dst_offset_y = 0;
unsigned int i;
dst_img = gdImageCreateTrueColor(new_width, new_height);
if (dst_img == NULL) {
return NULL;
}
for (i=0; i<new_height; i++) {
unsigned int j;
dst_offset_x = 0;
if (im->trueColor) {
for (j=0; j<new_width; j++) {
const gdFixed f_i = gd_itofx(i);
const gdFixed f_j = gd_itofx(j);
const gdFixed f_a = gd_mulfx(f_i, f_dy);
const gdFixed f_b = gd_mulfx(f_j, f_dx);
const long m = gd_fxtoi(f_a);
const long n = gd_fxtoi(f_b);
dst_img->tpixels[dst_offset_y][dst_offset_x++] = im->tpixels[m][n];
}
} else {
for (j=0; j<new_width; j++) {
const gdFixed f_i = gd_itofx(i);
const gdFixed f_j = gd_itofx(j);
const gdFixed f_a = gd_mulfx(f_i, f_dy);
const gdFixed f_b = gd_mulfx(f_j, f_dx);
const long m = gd_fxtoi(f_a);
const long n = gd_fxtoi(f_b);
dst_img->tpixels[dst_offset_y][dst_offset_x++] = colorIndex2RGBA(im->pixels[m][n]);
}
}
dst_offset_y++;
}
return dst_img;
}
static inline int getPixelOverflowColorTC(gdImagePtr im, const int x, const int y, const int color)
{
if (gdImageBoundsSafe(im, x, y)) {
const int c = im->tpixels[y][x];
if (c == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
}
return c;
} else {
register int border = 0;
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y > im->cy2) {
if (x >= im->cx1 && x <= im->cx1) {
border = im->tpixels[im->cy2][x];
goto processborder;
} else {
return gdTrueColorAlpha(0, 0, 0, 127);
}
}
/* y is bound safe at this point */
if (x < im->cx1) {
border = im->tpixels[y][im->cx1];
goto processborder;
}
if (x > im->cx2) {
border = im->tpixels[y][im->cx2];
}
processborder:
if (border == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
} else{
return gdTrueColorAlpha(gdTrueColorGetRed(border), gdTrueColorGetGreen(border), gdTrueColorGetBlue(border), 127);
}
}
}
static gdImagePtr gdImageScaleBilinearPalette(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
long _width = MAX(1, new_width);
long _height = MAX(1, new_height);
float dx = (float)gdImageSX(im) / (float)_width;
float dy = (float)gdImageSY(im) / (float)_height;
gdFixed f_dx = gd_ftofx(dx);
gdFixed f_dy = gd_ftofx(dy);
gdFixed f_1 = gd_itofx(1);
int dst_offset_h;
int dst_offset_v = 0;
long i;
gdImagePtr new_img;
const int transparent = im->transparent;
new_img = gdImageCreateTrueColor(new_width, new_height);
if (new_img == NULL) {
return NULL;
}
new_img->transparent = gdTrueColorAlpha(im->red[transparent], im->green[transparent], im->blue[transparent], im->alpha[transparent]);
for (i=0; i < _height; i++) {
long j;
const gdFixed f_i = gd_itofx(i);
const gdFixed f_a = gd_mulfx(f_i, f_dy);
register long m = gd_fxtoi(f_a);
dst_offset_h = 0;
for (j=0; j < _width; j++) {
/* Update bitmap */
gdFixed f_j = gd_itofx(j);
gdFixed f_b = gd_mulfx(f_j, f_dx);
const long n = gd_fxtoi(f_b);
gdFixed f_f = f_a - gd_itofx(m);
gdFixed f_g = f_b - gd_itofx(n);
const gdFixed f_w1 = gd_mulfx(f_1-f_f, f_1-f_g);
const gdFixed f_w2 = gd_mulfx(f_1-f_f, f_g);
const gdFixed f_w3 = gd_mulfx(f_f, f_1-f_g);
const gdFixed f_w4 = gd_mulfx(f_f, f_g);
unsigned int pixel1;
unsigned int pixel2;
unsigned int pixel3;
unsigned int pixel4;
register gdFixed f_r1, f_r2, f_r3, f_r4,
f_g1, f_g2, f_g3, f_g4,
f_b1, f_b2, f_b3, f_b4,
f_a1, f_a2, f_a3, f_a4;
/* zero for the background color, nothig gets outside anyway */
pixel1 = getPixelOverflowPalette(im, n, m, 0);
pixel2 = getPixelOverflowPalette(im, n + 1, m, 0);
pixel3 = getPixelOverflowPalette(im, n, m + 1, 0);
pixel4 = getPixelOverflowPalette(im, n + 1, m + 1, 0);
f_r1 = gd_itofx(gdTrueColorGetRed(pixel1));
f_r2 = gd_itofx(gdTrueColorGetRed(pixel2));
f_r3 = gd_itofx(gdTrueColorGetRed(pixel3));
f_r4 = gd_itofx(gdTrueColorGetRed(pixel4));
f_g1 = gd_itofx(gdTrueColorGetGreen(pixel1));
f_g2 = gd_itofx(gdTrueColorGetGreen(pixel2));
f_g3 = gd_itofx(gdTrueColorGetGreen(pixel3));
f_g4 = gd_itofx(gdTrueColorGetGreen(pixel4));
f_b1 = gd_itofx(gdTrueColorGetBlue(pixel1));
f_b2 = gd_itofx(gdTrueColorGetBlue(pixel2));
f_b3 = gd_itofx(gdTrueColorGetBlue(pixel3));
f_b4 = gd_itofx(gdTrueColorGetBlue(pixel4));
f_a1 = gd_itofx(gdTrueColorGetAlpha(pixel1));
f_a2 = gd_itofx(gdTrueColorGetAlpha(pixel2));
f_a3 = gd_itofx(gdTrueColorGetAlpha(pixel3));
f_a4 = gd_itofx(gdTrueColorGetAlpha(pixel4));
{
const char red = (char) gd_fxtoi(gd_mulfx(f_w1, f_r1) + gd_mulfx(f_w2, f_r2) + gd_mulfx(f_w3, f_r3) + gd_mulfx(f_w4, f_r4));
const char green = (char) gd_fxtoi(gd_mulfx(f_w1, f_g1) + gd_mulfx(f_w2, f_g2) + gd_mulfx(f_w3, f_g3) + gd_mulfx(f_w4, f_g4));
const char blue = (char) gd_fxtoi(gd_mulfx(f_w1, f_b1) + gd_mulfx(f_w2, f_b2) + gd_mulfx(f_w3, f_b3) + gd_mulfx(f_w4, f_b4));
const char alpha = (char) gd_fxtoi(gd_mulfx(f_w1, f_a1) + gd_mulfx(f_w2, f_a2) + gd_mulfx(f_w3, f_a3) + gd_mulfx(f_w4, f_a4));
new_img->tpixels[dst_offset_v][dst_offset_h] = gdTrueColorAlpha(red, green, blue, alpha);
}
dst_offset_h++;
}
dst_offset_v++;
}
return new_img;
}
static gdImagePtr gdImageScaleBilinearTC(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
long dst_w = MAX(1, new_width);
long dst_h = MAX(1, new_height);
float dx = (float)gdImageSX(im) / (float)dst_w;
float dy = (float)gdImageSY(im) / (float)dst_h;
gdFixed f_dx = gd_ftofx(dx);
gdFixed f_dy = gd_ftofx(dy);
gdFixed f_1 = gd_itofx(1);
int dst_offset_h;
int dst_offset_v = 0;
long i;
gdImagePtr new_img;
new_img = gdImageCreateTrueColor(new_width, new_height);
if (!new_img){
return NULL;
}
for (i=0; i < dst_h; i++) {
long j;
dst_offset_h = 0;
for (j=0; j < dst_w; j++) {
/* Update bitmap */
gdFixed f_i = gd_itofx(i);
gdFixed f_j = gd_itofx(j);
gdFixed f_a = gd_mulfx(f_i, f_dy);
gdFixed f_b = gd_mulfx(f_j, f_dx);
const long m = gd_fxtoi(f_a);
const long n = gd_fxtoi(f_b);
gdFixed f_f = f_a - gd_itofx(m);
gdFixed f_g = f_b - gd_itofx(n);
const gdFixed f_w1 = gd_mulfx(f_1-f_f, f_1-f_g);
const gdFixed f_w2 = gd_mulfx(f_1-f_f, f_g);
const gdFixed f_w3 = gd_mulfx(f_f, f_1-f_g);
const gdFixed f_w4 = gd_mulfx(f_f, f_g);
unsigned int pixel1;
unsigned int pixel2;
unsigned int pixel3;
unsigned int pixel4;
register gdFixed f_r1, f_r2, f_r3, f_r4,
f_g1, f_g2, f_g3, f_g4,
f_b1, f_b2, f_b3, f_b4,
f_a1, f_a2, f_a3, f_a4;
/* 0 for bgColor, nothing gets outside anyway */
pixel1 = getPixelOverflowTC(im, n, m, 0);
pixel2 = getPixelOverflowTC(im, n + 1, m, 0);
pixel3 = getPixelOverflowTC(im, n, m + 1, 0);
pixel4 = getPixelOverflowTC(im, n + 1, m + 1, 0);
f_r1 = gd_itofx(gdTrueColorGetRed(pixel1));
f_r2 = gd_itofx(gdTrueColorGetRed(pixel2));
f_r3 = gd_itofx(gdTrueColorGetRed(pixel3));
f_r4 = gd_itofx(gdTrueColorGetRed(pixel4));
f_g1 = gd_itofx(gdTrueColorGetGreen(pixel1));
f_g2 = gd_itofx(gdTrueColorGetGreen(pixel2));
f_g3 = gd_itofx(gdTrueColorGetGreen(pixel3));
f_g4 = gd_itofx(gdTrueColorGetGreen(pixel4));
f_b1 = gd_itofx(gdTrueColorGetBlue(pixel1));
f_b2 = gd_itofx(gdTrueColorGetBlue(pixel2));
f_b3 = gd_itofx(gdTrueColorGetBlue(pixel3));
f_b4 = gd_itofx(gdTrueColorGetBlue(pixel4));
f_a1 = gd_itofx(gdTrueColorGetAlpha(pixel1));
f_a2 = gd_itofx(gdTrueColorGetAlpha(pixel2));
f_a3 = gd_itofx(gdTrueColorGetAlpha(pixel3));
f_a4 = gd_itofx(gdTrueColorGetAlpha(pixel4));
{
const char red = (char) gd_fxtoi(gd_mulfx(f_w1, f_r1) + gd_mulfx(f_w2, f_r2) + gd_mulfx(f_w3, f_r3) + gd_mulfx(f_w4, f_r4));
const char green = (char) gd_fxtoi(gd_mulfx(f_w1, f_g1) + gd_mulfx(f_w2, f_g2) + gd_mulfx(f_w3, f_g3) + gd_mulfx(f_w4, f_g4));
const char blue = (char) gd_fxtoi(gd_mulfx(f_w1, f_b1) + gd_mulfx(f_w2, f_b2) + gd_mulfx(f_w3, f_b3) + gd_mulfx(f_w4, f_b4));
const char alpha = (char) gd_fxtoi(gd_mulfx(f_w1, f_a1) + gd_mulfx(f_w2, f_a2) + gd_mulfx(f_w3, f_a3) + gd_mulfx(f_w4, f_a4));
new_img->tpixels[dst_offset_v][dst_offset_h] = gdTrueColorAlpha(red, green, blue, alpha);
}
dst_offset_h++;
}
dst_offset_v++;
}
return new_img;
}
gdImagePtr gdImageScaleBilinear(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
if (im->trueColor) {
return gdImageScaleBilinearTC(im, new_width, new_height);
} else {
return gdImageScaleBilinearPalette(im, new_width, new_height);
}
}
gdImagePtr gdImageScaleBicubicFixed(gdImagePtr src, const unsigned int width, const unsigned int height)
{
const long new_width = MAX(1, width);
const long new_height = MAX(1, height);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const gdFixed f_dx = gd_ftofx((float)src_w / (float)new_width);
const gdFixed f_dy = gd_ftofx((float)src_h / (float)new_height);
const gdFixed f_1 = gd_itofx(1);
const gdFixed f_2 = gd_itofx(2);
const gdFixed f_4 = gd_itofx(4);
const gdFixed f_6 = gd_itofx(6);
const gdFixed f_gamma = gd_ftofx(1.04f);
gdImagePtr dst;
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
long i;
/* impact perf a bit, but not that much. Implementation for palette
images can be done at a later point.
*/
if (src->trueColor == 0) {
gdImagePaletteToTrueColor(src);
}
dst = gdImageCreateTrueColor(new_width, new_height);
if (!dst) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i=0; i < new_height; i++) {
long j;
dst_offset_x = 0;
for (j=0; j < new_width; j++) {
const gdFixed f_a = gd_mulfx(gd_itofx(i), f_dy);
const gdFixed f_b = gd_mulfx(gd_itofx(j), f_dx);
const long m = gd_fxtoi(f_a);
const long n = gd_fxtoi(f_b);
const gdFixed f_f = f_a - gd_itofx(m);
const gdFixed f_g = f_b - gd_itofx(n);
unsigned int src_offset_x[16], src_offset_y[16];
long k;
register gdFixed f_red = 0, f_green = 0, f_blue = 0, f_alpha = 0;
unsigned char red, green, blue, alpha = 0;
int *dst_row = dst->tpixels[dst_offset_y];
if ((m < 1) || (n < 1)) {
src_offset_x[0] = n;
src_offset_y[0] = m;
} else {
src_offset_x[0] = n - 1;
src_offset_y[0] = m;
}
if (m < 1) {
src_offset_x[1] = n;
src_offset_y[1] = m;
} else {
src_offset_x[1] = n;
src_offset_y[1] = m;
}
if ((m < 1) || (n >= src_w - 1)) {
src_offset_x[2] = n;
src_offset_y[2] = m;
} else {
src_offset_x[2] = n + 1;
src_offset_y[2] = m;
}
if ((m < 1) || (n >= src_w - 2)) {
src_offset_x[3] = n;
src_offset_y[3] = m;
} else {
src_offset_x[3] = n + 1 + 1;
src_offset_y[3] = m;
}
if (n < 1) {
src_offset_x[4] = n;
src_offset_y[4] = m;
} else {
src_offset_x[4] = n - 1;
src_offset_y[4] = m;
}
src_offset_x[5] = n;
src_offset_y[5] = m;
if (n >= src_w-1) {
src_offset_x[6] = n;
src_offset_y[6] = m;
} else {
src_offset_x[6] = n + 1;
src_offset_y[6] = m;
}
if (n >= src_w - 2) {
src_offset_x[7] = n;
src_offset_y[7] = m;
} else {
src_offset_x[7] = n + 1 + 1;
src_offset_y[7] = m;
}
if ((m >= src_h - 1) || (n < 1)) {
src_offset_x[8] = n;
src_offset_y[8] = m;
} else {
src_offset_x[8] = n - 1;
src_offset_y[8] = m;
}
if (m >= src_h - 1) {
src_offset_x[8] = n;
src_offset_y[8] = m;
} else {
src_offset_x[9] = n;
src_offset_y[9] = m;
}
if ((m >= src_h-1) || (n >= src_w-1)) {
src_offset_x[10] = n;
src_offset_y[10] = m;
} else {
src_offset_x[10] = n + 1;
src_offset_y[10] = m;
}
if ((m >= src_h - 1) || (n >= src_w - 2)) {
src_offset_x[11] = n;
src_offset_y[11] = m;
} else {
src_offset_x[11] = n + 1 + 1;
src_offset_y[11] = m;
}
if ((m >= src_h - 2) || (n < 1)) {
src_offset_x[12] = n;
src_offset_y[12] = m;
} else {
src_offset_x[12] = n - 1;
src_offset_y[12] = m;
}
if (m >= src_h - 2) {
src_offset_x[13] = n;
src_offset_y[13] = m;
} else {
src_offset_x[13] = n;
src_offset_y[13] = m;
}
if ((m >= src_h - 2) || (n >= src_w - 1)) {
src_offset_x[14] = n;
src_offset_y[14] = m;
} else {
src_offset_x[14] = n + 1;
src_offset_y[14] = m;
}
if ((m >= src_h - 2) || (n >= src_w - 2)) {
src_offset_x[15] = n;
src_offset_y[15] = m;
} else {
src_offset_x[15] = n + 1 + 1;
src_offset_y[15] = m;
}
for (k = -1; k < 3; k++) {
const gdFixed f = gd_itofx(k)-f_f;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
register gdFixed f_a = 0, f_b = 0, f_d = 0, f_c = 0;
register gdFixed f_RY;
int l;
if (f_fp2 > 0) f_a = gd_mulfx(f_fp2, gd_mulfx(f_fp2,f_fp2));
if (f_fp1 > 0) f_b = gd_mulfx(f_fp1, gd_mulfx(f_fp1,f_fp1));
if (f > 0) f_c = gd_mulfx(f, gd_mulfx(f,f));
if (f_fm1 > 0) f_d = gd_mulfx(f_fm1, gd_mulfx(f_fm1,f_fm1));
f_RY = gd_divfx((f_a - gd_mulfx(f_4,f_b) + gd_mulfx(f_6,f_c) - gd_mulfx(f_4,f_d)),f_6);
for (l = -1; l < 3; l++) {
const gdFixed f = gd_itofx(l) - f_g;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
register gdFixed f_a = 0, f_b = 0, f_c = 0, f_d = 0;
register gdFixed f_RX, f_R, f_rs, f_gs, f_bs, f_ba;
register int c;
const int _k = ((k+1)*4) + (l+1);
if (f_fp2 > 0) f_a = gd_mulfx(f_fp2,gd_mulfx(f_fp2,f_fp2));
if (f_fp1 > 0) f_b = gd_mulfx(f_fp1,gd_mulfx(f_fp1,f_fp1));
if (f > 0) f_c = gd_mulfx(f,gd_mulfx(f,f));
if (f_fm1 > 0) f_d = gd_mulfx(f_fm1,gd_mulfx(f_fm1,f_fm1));
f_RX = gd_divfx((f_a-gd_mulfx(f_4,f_b)+gd_mulfx(f_6,f_c)-gd_mulfx(f_4,f_d)),f_6);
f_R = gd_mulfx(f_RY,f_RX);
c = src->tpixels[*(src_offset_y + _k)][*(src_offset_x + _k)];
f_rs = gd_itofx(gdTrueColorGetRed(c));
f_gs = gd_itofx(gdTrueColorGetGreen(c));
f_bs = gd_itofx(gdTrueColorGetBlue(c));
f_ba = gd_itofx(gdTrueColorGetAlpha(c));
f_red += gd_mulfx(f_rs,f_R);
f_green += gd_mulfx(f_gs,f_R);
f_blue += gd_mulfx(f_bs,f_R);
f_alpha += gd_mulfx(f_ba,f_R);
}
}
red = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_red, f_gamma)), 0, 255);
green = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_green, f_gamma)), 0, 255);
blue = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_blue, f_gamma)), 0, 255);
alpha = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_alpha, f_gamma)), 0, 127);
*(dst_row + dst_offset_x) = gdTrueColorAlpha(red, green, blue, alpha);
dst_offset_x++;
}
dst_offset_y++;
}
return dst;
}
BGD_DECLARE(gdImagePtr) gdImageScale(const gdImagePtr src, const unsigned int new_width, const unsigned int new_height)
{
gdImagePtr im_scaled = NULL;
if (src == NULL || src->interpolation_id < 0 || src->interpolation_id > GD_METHOD_COUNT) {
return 0;
}
switch (src->interpolation_id) {
/*Special cases, optimized implementations */
case GD_NEAREST_NEIGHBOUR:
im_scaled = gdImageScaleNearestNeighbour(src, new_width, new_height);
break;
case GD_BILINEAR_FIXED:
im_scaled = gdImageScaleBilinear(src, new_width, new_height);
break;
case GD_BICUBIC_FIXED:
im_scaled = gdImageScaleBicubicFixed(src, new_width, new_height);
break;
/* generic */
default:
if (src->interpolation == NULL) {
return NULL;
}
im_scaled = gdImageScaleTwoPass(src, src->sx, src->sy, new_width, new_height);
break;
}
return im_scaled;
}
gdImagePtr gdImageRotateNearestNeighbour(gdImagePtr src, const float degrees, const int bgColor)
{
float _angle = ((float) (-degrees / 180.0f) * (float)M_PI);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const unsigned int new_width = (unsigned int)(abs((int)(src_w * cos(_angle))) + abs((int)(src_h * sin(_angle))) + 0.5f);
const unsigned int new_height = (unsigned int)(abs((int)(src_w * sin(_angle))) + abs((int)(src_h * cos(_angle))) + 0.5f);
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int i;
gdImagePtr dst;
/* impact perf a bit, but not that much. Implementation for palette
images can be done at a later point.
*/
if (src->trueColor == 0) {
gdImagePaletteToTrueColor(src);
}
dst = gdImageCreateTrueColor(new_width, new_height);
if (!dst) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i = 0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j = 0; j < new_width; j++) {
gdFixed f_i = gd_itofx((int)i - (int)new_height / 2);
gdFixed f_j = gd_itofx((int)j - (int)new_width / 2);
gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
long m = gd_fxtoi(f_m);
long n = gd_fxtoi(f_n);
if ((m > 0) && (m < src_h-1) && (n > 0) && (n < src_w-1)) {
if (dst_offset_y < new_height) {
dst->tpixels[dst_offset_y][dst_offset_x++] = src->tpixels[m][n];
}
} else {
if (dst_offset_y < new_height) {
dst->tpixels[dst_offset_y][dst_offset_x++] = bgColor;
}
}
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageRotateGeneric(gdImagePtr src, const float degrees, const int bgColor)
{
float _angle = ((float) (-degrees / 180.0f) * (float)M_PI);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const unsigned int new_width = (unsigned int)(abs((int)(src_w * cos(_angle))) + abs((int)(src_h * sin(_angle))) + 0.5f);
const unsigned int new_height = (unsigned int)(abs((int)(src_w * sin(_angle))) + abs((int)(src_h * cos(_angle))) + 0.5f);
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int i;
gdImagePtr dst;
const gdFixed f_slop_y = f_sin;
const gdFixed f_slop_x = f_cos;
const gdFixed f_slop = f_slop_x > 0 && f_slop_x > 0 ?
f_slop_x > f_slop_y ? gd_divfx(f_slop_y, f_slop_x) : gd_divfx(f_slop_x, f_slop_y)
: 0;
if (bgColor < 0) {
return NULL;
}
/* impact perf a bit, but not that much. Implementation for palette
images can be done at a later point.
*/
if (src->trueColor == 0) {
gdImagePaletteToTrueColor(src);
}
dst = gdImageCreateTrueColor(new_width, new_height);
if (!dst) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i = 0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j = 0; j < new_width; j++) {
gdFixed f_i = gd_itofx((int)i - (int)new_height / 2);
gdFixed f_j = gd_itofx((int)j - (int)new_width / 2);
gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
long m = gd_fxtoi(f_m);
long n = gd_fxtoi(f_n);
if ((n <= 0) || (m <= 0) || (m >= src_h) || (n >= src_w)) {
dst->tpixels[dst_offset_y][dst_offset_x++] = bgColor;
} else if ((n <= 1) || (m <= 1) || (m >= src_h - 1) || (n >= src_w - 1)) {
register int c = getPixelInterpolated(src, n, m, bgColor);
c = c | (( gdTrueColorGetAlpha(c) + ((int)(127* gd_fxtof(f_slop)))) << 24);
dst->tpixels[dst_offset_y][dst_offset_x++] = _color_blend(bgColor, c);
} else {
dst->tpixels[dst_offset_y][dst_offset_x++] = getPixelInterpolated(src, n, m, bgColor);
}
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageRotateBilinear(gdImagePtr src, const float degrees, const int bgColor)
{
float _angle = (float)((- degrees / 180.0f) * M_PI);
const unsigned int src_w = gdImageSX(src);
const unsigned int src_h = gdImageSY(src);
unsigned int new_width = abs((int)(src_w*cos(_angle))) + abs((int)(src_h*sin(_angle) + 0.5f));
unsigned int new_height = abs((int)(src_w*sin(_angle))) + abs((int)(src_h*cos(_angle) + 0.5f));
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
const gdFixed f_1 = gd_itofx(1);
unsigned int i;
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int src_offset_x, src_offset_y;
gdImagePtr dst;
/* impact perf a bit, but not that much. Implementation for palette
images can be done at a later point.
*/
if (src->trueColor == 0) {
gdImagePaletteToTrueColor(src);
}
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst == NULL) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i = 0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j=0; j < new_width; j++) {
const gdFixed f_i = gd_itofx((int)i - (int)new_height / 2);
const gdFixed f_j = gd_itofx((int)j - (int)new_width / 2);
const gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
const gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
const unsigned int m = gd_fxtoi(f_m);
const unsigned int n = gd_fxtoi(f_n);
if ((m > 0) && (m < src_h - 1) && (n > 0) && (n < src_w - 1)) {
const gdFixed f_f = f_m - gd_itofx(m);
const gdFixed f_g = f_n - gd_itofx(n);
const gdFixed f_w1 = gd_mulfx(f_1-f_f, f_1-f_g);
const gdFixed f_w2 = gd_mulfx(f_1-f_f, f_g);
const gdFixed f_w3 = gd_mulfx(f_f, f_1-f_g);
const gdFixed f_w4 = gd_mulfx(f_f, f_g);
if (n < src_w - 1) {
src_offset_x = n + 1;
src_offset_y = m;
}
if (m < src_h - 1) {
src_offset_x = n;
src_offset_y = m + 1;
}
if (!((n >= src_w - 1) || (m >= src_h - 1))) {
src_offset_x = n + 1;
src_offset_y = m + 1;
}
{
const int pixel1 = src->tpixels[src_offset_y][src_offset_x];
register int pixel2, pixel3, pixel4;
if (src_offset_y + 1 >= src_h) {
pixel2 = bgColor;
pixel3 = bgColor;
pixel4 = bgColor;
} else if (src_offset_x + 1 >= src_w) {
pixel2 = bgColor;
pixel3 = bgColor;
pixel4 = bgColor;
} else {
pixel2 = src->tpixels[src_offset_y][src_offset_x + 1];
pixel3 = src->tpixels[src_offset_y + 1][src_offset_x];
pixel4 = src->tpixels[src_offset_y + 1][src_offset_x + 1];
}
{
const gdFixed f_r1 = gd_itofx(gdTrueColorGetRed(pixel1));
const gdFixed f_r2 = gd_itofx(gdTrueColorGetRed(pixel2));
const gdFixed f_r3 = gd_itofx(gdTrueColorGetRed(pixel3));
const gdFixed f_r4 = gd_itofx(gdTrueColorGetRed(pixel4));
const gdFixed f_g1 = gd_itofx(gdTrueColorGetGreen(pixel1));
const gdFixed f_g2 = gd_itofx(gdTrueColorGetGreen(pixel2));
const gdFixed f_g3 = gd_itofx(gdTrueColorGetGreen(pixel3));
const gdFixed f_g4 = gd_itofx(gdTrueColorGetGreen(pixel4));
const gdFixed f_b1 = gd_itofx(gdTrueColorGetBlue(pixel1));
const gdFixed f_b2 = gd_itofx(gdTrueColorGetBlue(pixel2));
const gdFixed f_b3 = gd_itofx(gdTrueColorGetBlue(pixel3));
const gdFixed f_b4 = gd_itofx(gdTrueColorGetBlue(pixel4));
const gdFixed f_a1 = gd_itofx(gdTrueColorGetAlpha(pixel1));
const gdFixed f_a2 = gd_itofx(gdTrueColorGetAlpha(pixel2));
const gdFixed f_a3 = gd_itofx(gdTrueColorGetAlpha(pixel3));
const gdFixed f_a4 = gd_itofx(gdTrueColorGetAlpha(pixel4));
const gdFixed f_red = gd_mulfx(f_w1, f_r1) + gd_mulfx(f_w2, f_r2) + gd_mulfx(f_w3, f_r3) + gd_mulfx(f_w4, f_r4);
const gdFixed f_green = gd_mulfx(f_w1, f_g1) + gd_mulfx(f_w2, f_g2) + gd_mulfx(f_w3, f_g3) + gd_mulfx(f_w4, f_g4);
const gdFixed f_blue = gd_mulfx(f_w1, f_b1) + gd_mulfx(f_w2, f_b2) + gd_mulfx(f_w3, f_b3) + gd_mulfx(f_w4, f_b4);
const gdFixed f_alpha = gd_mulfx(f_w1, f_a1) + gd_mulfx(f_w2, f_a2) + gd_mulfx(f_w3, f_a3) + gd_mulfx(f_w4, f_a4);
const unsigned char red = (unsigned char) CLAMP(gd_fxtoi(f_red), 0, 255);
const unsigned char green = (unsigned char) CLAMP(gd_fxtoi(f_green), 0, 255);
const unsigned char blue = (unsigned char) CLAMP(gd_fxtoi(f_blue), 0, 255);
const unsigned char alpha = (unsigned char) CLAMP(gd_fxtoi(f_alpha), 0, 127);
dst->tpixels[dst_offset_y][dst_offset_x++] = gdTrueColorAlpha(red, green, blue, alpha);
}
}
} else {
dst->tpixels[dst_offset_y][dst_offset_x++] = bgColor;
}
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageRotateBicubicFixed(gdImagePtr src, const float degrees, const int bgColor)
{
const float _angle = (float)((- degrees / 180.0f) * M_PI);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const unsigned int new_width = abs((int)(src_w*cos(_angle))) + abs((int)(src_h*sin(_angle) + 0.5f));
const unsigned int new_height = abs((int)(src_w*sin(_angle))) + abs((int)(src_h*cos(_angle) + 0.5f));
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
const gdFixed f_1 = gd_itofx(1);
const gdFixed f_2 = gd_itofx(2);
const gdFixed f_4 = gd_itofx(4);
const gdFixed f_6 = gd_itofx(6);
const gdFixed f_gama = gd_ftofx(1.04f);
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int i;
gdImagePtr dst;
/* impact perf a bit, but not that much. Implementation for palette
images can be done at a later point.
*/
if (src->trueColor == 0) {
gdImagePaletteToTrueColor(src);
}
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst == NULL) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i=0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j=0; j < new_width; j++) {
const gdFixed f_i = gd_itofx((int)i - (int)new_height / 2);
const gdFixed f_j = gd_itofx((int)j - (int)new_width / 2);
const gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
const gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
const int m = gd_fxtoi(f_m);
const int n = gd_fxtoi(f_n);
if ((m > 0) && (m < src_h - 1) && (n > 0) && (n < src_w-1)) {
const gdFixed f_f = f_m - gd_itofx(m);
const gdFixed f_g = f_n - gd_itofx(n);
unsigned int src_offset_x[16], src_offset_y[16];
unsigned char red, green, blue, alpha;
gdFixed f_red=0, f_green=0, f_blue=0, f_alpha=0;
int k;
if ((m < 1) || (n < 1)) {
src_offset_x[0] = n;
src_offset_y[0] = m;
} else {
src_offset_x[0] = n - 1;
src_offset_y[0] = m;
}
if (m < 1) {
src_offset_x[1] = n;
src_offset_y[1] = m;
} else {
src_offset_x[1] = n;
src_offset_y[1] = m ;
}
if ((m < 1) || (n >= src_w-1)) {
src_offset_x[2] = - 1;
src_offset_y[2] = - 1;
} else {
src_offset_x[2] = n + 1;
src_offset_y[2] = m ;
}
if ((m < 1) || (n >= src_w-2)) {
src_offset_x[3] = - 1;
src_offset_y[3] = - 1;
} else {
src_offset_x[3] = n + 1 + 1;
src_offset_y[3] = m ;
}
if (n < 1) {
src_offset_x[4] = - 1;
src_offset_y[4] = - 1;
} else {
src_offset_x[4] = n - 1;
src_offset_y[4] = m;
}
src_offset_x[5] = n;
src_offset_y[5] = m;
if (n >= src_w-1) {
src_offset_x[6] = - 1;
src_offset_y[6] = - 1;
} else {
src_offset_x[6] = n + 1;
src_offset_y[6] = m;
}
if (n >= src_w-2) {
src_offset_x[7] = - 1;
src_offset_y[7] = - 1;
} else {
src_offset_x[7] = n + 1 + 1;
src_offset_y[7] = m;
}
if ((m >= src_h-1) || (n < 1)) {
src_offset_x[8] = - 1;
src_offset_y[8] = - 1;
} else {
src_offset_x[8] = n - 1;
src_offset_y[8] = m;
}
if (m >= src_h-1) {
src_offset_x[8] = - 1;
src_offset_y[8] = - 1;
} else {
src_offset_x[9] = n;
src_offset_y[9] = m;
}
if ((m >= src_h-1) || (n >= src_w-1)) {
src_offset_x[10] = - 1;
src_offset_y[10] = - 1;
} else {
src_offset_x[10] = n + 1;
src_offset_y[10] = m;
}
if ((m >= src_h-1) || (n >= src_w-2)) {
src_offset_x[11] = - 1;
src_offset_y[11] = - 1;
} else {
src_offset_x[11] = n + 1 + 1;
src_offset_y[11] = m;
}
if ((m >= src_h-2) || (n < 1)) {
src_offset_x[12] = - 1;
src_offset_y[12] = - 1;
} else {
src_offset_x[12] = n - 1;
src_offset_y[12] = m;
}
if (m >= src_h-2) {
src_offset_x[13] = - 1;
src_offset_y[13] = - 1;
} else {
src_offset_x[13] = n;
src_offset_y[13] = m;
}
if ((m >= src_h-2) || (n >= src_w - 1)) {
src_offset_x[14] = - 1;
src_offset_y[14] = - 1;
} else {
src_offset_x[14] = n + 1;
src_offset_y[14] = m;
}
if ((m >= src_h-2) || (n >= src_w-2)) {
src_offset_x[15] = - 1;
src_offset_y[15] = - 1;
} else {
src_offset_x[15] = n + 1 + 1;
src_offset_y[15] = m;
}
for (k=-1; k<3; k++) {
const gdFixed f = gd_itofx(k)-f_f;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
gdFixed f_a = 0, f_b = 0,f_c = 0, f_d = 0;
gdFixed f_RY;
int l;
if (f_fp2 > 0) {
f_a = gd_mulfx(f_fp2,gd_mulfx(f_fp2,f_fp2));
}
if (f_fp1 > 0) {
f_b = gd_mulfx(f_fp1,gd_mulfx(f_fp1,f_fp1));
}
if (f > 0) {
f_c = gd_mulfx(f,gd_mulfx(f,f));
}
if (f_fm1 > 0) {
f_d = gd_mulfx(f_fm1,gd_mulfx(f_fm1,f_fm1));
}
f_RY = gd_divfx((f_a-gd_mulfx(f_4,f_b)+gd_mulfx(f_6,f_c)-gd_mulfx(f_4,f_d)),f_6);
for (l=-1; l< 3; l++) {
const gdFixed f = gd_itofx(l) - f_g;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
gdFixed f_a = 0, f_b = 0, f_c = 0, f_d = 0;
gdFixed f_RX, f_R;
const int _k = ((k + 1) * 4) + (l + 1);
register gdFixed f_rs, f_gs, f_bs, f_as;
register int c;
if (f_fp2 > 0) {
f_a = gd_mulfx(f_fp2,gd_mulfx(f_fp2,f_fp2));
}
if (f_fp1 > 0) {
f_b = gd_mulfx(f_fp1,gd_mulfx(f_fp1,f_fp1));
}
if (f > 0) {
f_c = gd_mulfx(f,gd_mulfx(f,f));
}
if (f_fm1 > 0) {
f_d = gd_mulfx(f_fm1,gd_mulfx(f_fm1,f_fm1));
}
f_RX = gd_divfx((f_a - gd_mulfx(f_4, f_b) + gd_mulfx(f_6, f_c) - gd_mulfx(f_4, f_d)), f_6);
f_R = gd_mulfx(f_RY, f_RX);
if ((src_offset_x[_k] <= 0) || (src_offset_y[_k] <= 0) || (src_offset_y[_k] >= src_h) || (src_offset_x[_k] >= src_w)) {
c = bgColor;
} else if ((src_offset_x[_k] <= 1) || (src_offset_y[_k] <= 1) || (src_offset_y[_k] >= (int)src_h - 1) || (src_offset_x[_k] >= (int)src_w - 1)) {
gdFixed f_127 = gd_itofx(127);
c = src->tpixels[src_offset_y[_k]][src_offset_x[_k]];
c = c | (( (int) (gd_fxtof(gd_mulfx(f_R, f_127)) + 50.5f)) << 24);
c = _color_blend(bgColor, c);
} else {
c = src->tpixels[src_offset_y[_k]][src_offset_x[_k]];
}
f_rs = gd_itofx(gdTrueColorGetRed(c));
f_gs = gd_itofx(gdTrueColorGetGreen(c));
f_bs = gd_itofx(gdTrueColorGetBlue(c));
f_as = gd_itofx(gdTrueColorGetAlpha(c));
f_red += gd_mulfx(f_rs, f_R);
f_green += gd_mulfx(f_gs, f_R);
f_blue += gd_mulfx(f_bs, f_R);
f_alpha += gd_mulfx(f_as, f_R);
}
}
red = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_red, f_gama)), 0, 255);
green = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_green, f_gama)), 0, 255);
blue = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_blue, f_gama)), 0, 255);
alpha = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_alpha, f_gama)), 0, 127);
dst->tpixels[dst_offset_y][dst_offset_x] = gdTrueColorAlpha(red, green, blue, alpha);
} else {
dst->tpixels[dst_offset_y][dst_offset_x] = bgColor;
}
dst_offset_x++;
}
dst_offset_y++;
}
return dst;
}
BGD_DECLARE(gdImagePtr) gdImageRotateInterpolated(const gdImagePtr src, const float angle, int bgcolor)
{
/* round to two decimals and keep the 100x multiplication to use it in the common square angles
case later. Keep the two decimal precisions so smaller rotation steps can be done, useful for
slow animations, f.e. */
const int angle_rounded = fmod((int) floorf(angle * 100), 360 * 100);
if (bgcolor < 0) {
return NULL;
}
/* 0 && 90 degrees multiple rotation, 0 rotation simply clones the return image and convert it
to truecolor, as we must return truecolor image. */
switch (angle_rounded) {
case 0: {
gdImagePtr dst = gdImageClone(src);
if (dst == NULL) {
return NULL;
}
if (dst->trueColor == 0) {
gdImagePaletteToTrueColor(dst);
}
return dst;
}
case -2700:
case 9000:
return gdImageRotate90(src, 0);
case -18000:
case 18000:
return gdImageRotate180(src, 0);
case -9000:
case 27000:
return gdImageRotate270(src, 0);
}
if (src == NULL || src->interpolation_id < 1 || src->interpolation_id > GD_METHOD_COUNT) {
return NULL;
}
switch (src->interpolation_id) {
case GD_NEAREST_NEIGHBOUR:
return gdImageRotateNearestNeighbour(src, angle, bgcolor);
break;
case GD_BILINEAR_FIXED:
return gdImageRotateBilinear(src, angle, bgcolor);
break;
case GD_BICUBIC_FIXED:
return gdImageRotateBicubicFixed(src, angle, bgcolor);
break;
default:
return gdImageRotateGeneric(src, angle, bgcolor);
}
return NULL;
}
/**
* Title: Affine transformation
**/
/**
* Group: Transform
**/
static void gdImageClipRectangle(gdImagePtr im, gdRectPtr r)
{
int c1x, c1y, c2x, c2y;
int x1,y1;
gdImageGetClip(im, &c1x, &c1y, &c2x, &c2y);
x1 = r->x + r->width - 1;
y1 = r->y + r->height - 1;
r->x = CLAMP(r->x, c1x, c2x);
r->y = CLAMP(r->y, c1y, c2y);
r->width = CLAMP(x1, c1x, c2x) - r->x + 1;
r->height = CLAMP(y1, c1y, c2y) - r->y + 1;
}
void gdDumpRect(const char *msg, gdRectPtr r)
{
printf("%s (%i, %i) (%i, %i)\n", msg, r->x, r->y, r->width, r->height);
}
/**
* Function: gdTransformAffineGetImage
* Applies an affine transformation to a region and return an image
* containing the complete transformation.
*
* Parameters:
* dst - Pointer to a gdImagePtr to store the created image, NULL when
* the creation or the transformation failed
* src - Source image
* src_area - rectangle defining the source region to transform
* dstY - Y position in the destination image
* affine - The desired affine transformation
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*/
BGD_DECLARE(int) gdTransformAffineGetImage(gdImagePtr *dst,
const gdImagePtr src,
gdRectPtr src_area,
const double affine[6])
{
int res;
double m[6];
gdRect bbox;
gdRect area_full;
if (src_area == NULL) {
area_full.x = 0;
area_full.y = 0;
area_full.width = gdImageSX(src);
area_full.height = gdImageSY(src);
src_area = &area_full;
}
gdTransformAffineBoundingBox(src_area, affine, &bbox);
*dst = gdImageCreateTrueColor(bbox.width, bbox.height);
if (*dst == NULL) {
return GD_FALSE;
}
(*dst)->saveAlphaFlag = 1;
if (!src->trueColor) {
gdImagePaletteToTrueColor(src);
}
/* Translate to dst origin (0,0) */
gdAffineTranslate(m, -bbox.x, -bbox.y);
gdAffineConcat(m, affine, m);
gdImageAlphaBlending(*dst, 0);
res = gdTransformAffineCopy(*dst,
0,0,
src,
src_area,
m);
if (res != GD_TRUE) {
gdImageDestroy(*dst);
dst = NULL;
return GD_FALSE;
} else {
return GD_TRUE;
}
}
/**
* Function: gdTransformAffineCopy
* Applies an affine transformation to a region and copy the result
* in a destination to the given position.
*
* Parameters:
* dst - Image to draw the transformed image
* src - Source image
* dstX - X position in the destination image
* dstY - Y position in the destination image
* src_area - Rectangular region to rotate in the src image
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*/
BGD_DECLARE(int) gdTransformAffineCopy(gdImagePtr dst,
int dst_x, int dst_y,
const gdImagePtr src,
gdRectPtr src_region,
const double affine[6])
{
int c1x,c1y,c2x,c2y;
int backclip = 0;
int backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2;
register int x, y, src_offset_x, src_offset_y;
double inv[6];
int *dst_p;
gdPointF pt, src_pt;
gdRect bbox;
int end_x, end_y;
gdInterpolationMethod interpolation_id_bak = GD_DEFAULT;
/* These methods use special implementations */
if (src->interpolation_id == GD_BILINEAR_FIXED || src->interpolation_id == GD_BICUBIC_FIXED || src->interpolation_id == GD_NEAREST_NEIGHBOUR) {
interpolation_id_bak = src->interpolation_id;
gdImageSetInterpolationMethod(src, GD_BICUBIC);
}
gdImageClipRectangle(src, src_region);
if (src_region->x > 0 || src_region->y > 0
|| src_region->width < gdImageSX(src)
|| src_region->height < gdImageSY(src)) {
backclip = 1;
gdImageGetClip(src, &backup_clipx1, &backup_clipy1,
&backup_clipx2, &backup_clipy2);
gdImageSetClip(src, src_region->x, src_region->y,
src_region->x + src_region->width - 1,
src_region->y + src_region->height - 1);
}
if (!gdTransformAffineBoundingBox(src_region, affine, &bbox)) {
if (backclip) {
gdImageSetClip(src, backup_clipx1, backup_clipy1,
backup_clipx2, backup_clipy2);
}
gdImageSetInterpolationMethod(src, interpolation_id_bak);
return GD_FALSE;
}
gdImageGetClip(dst, &c1x, &c1y, &c2x, &c2y);
end_x = bbox.width + (int) fabs(bbox.x);
end_y = bbox.height + (int) fabs(bbox.y);
/* Get inverse affine to let us work with destination -> source */
gdAffineInvert(inv, affine);
src_offset_x = src_region->x;
src_offset_y = src_region->y;
if (dst->alphaBlendingFlag) {
for (y = bbox.y; y <= end_y; y++) {
pt.y = y + 0.5;
for (x = 0; x <= end_x; x++) {
pt.x = x + 0.5;
gdAffineApplyToPointF(&src_pt, &pt, inv);
gdImageSetPixel(dst, dst_x + x, dst_y + y, getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, 0));
}
}
} else {
for (y = 0; y <= end_y; y++) {
pt.y = y + 0.5 + bbox.y;
if ((dst_y + y) < 0 || ((dst_y + y) > gdImageSY(dst) -1)) {
continue;
}
dst_p = dst->tpixels[dst_y + y] + dst_x;
for (x = 0; x <= end_x; x++) {
pt.x = x + 0.5 + bbox.x;
gdAffineApplyToPointF(&src_pt, &pt, inv);
if ((dst_x + x) < 0 || (dst_x + x) > (gdImageSX(dst) - 1)) {
break;
}
*(dst_p++) = getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, -1);
}
}
}
/* Restore clip if required */
if (backclip) {
gdImageSetClip(src, backup_clipx1, backup_clipy1,
backup_clipx2, backup_clipy2);
}
gdImageSetInterpolationMethod(src, interpolation_id_bak);
return GD_TRUE;
}
/**
* Function: gdTransformAffineBoundingBox
* Returns the bounding box of an affine transformation applied to a
* rectangular area <gdRect>
*
* Parameters:
* src - Rectangular source area for the affine transformation
* affine - the affine transformation
* bbox - the resulting bounding box
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*/
BGD_DECLARE(int) gdTransformAffineBoundingBox(gdRectPtr src, const double affine[6], gdRectPtr bbox)
{
gdPointF extent[4], min, max, point;
int i;
extent[0].x=0.0;
extent[0].y=0.0;
extent[1].x=(double) src->width;
extent[1].y=0.0;
extent[2].x=(double) src->width;
extent[2].y=(double) src->height;
extent[3].x=0.0;
extent[3].y=(double) src->height;
for (i=0; i < 4; i++) {
point=extent[i];
if (gdAffineApplyToPointF(&extent[i], &point, affine) != GD_TRUE) {
return GD_FALSE;
}
}
min=extent[0];
max=extent[0];
for (i=1; i < 4; i++) {
if (min.x > extent[i].x)
min.x=extent[i].x;
if (min.y > extent[i].y)
min.y=extent[i].y;
if (max.x < extent[i].x)
max.x=extent[i].x;
if (max.y < extent[i].y)
max.y=extent[i].y;
}
bbox->x = (int) min.x;
bbox->y = (int) min.y;
bbox->width = (int) floor(max.x - min.x) - 1;
bbox->height = (int) floor(max.y - min.y);
return GD_TRUE;
}
BGD_DECLARE(int) gdImageSetInterpolationMethod(gdImagePtr im, gdInterpolationMethod id)
{
if (im == NULL || id < 0 || id > GD_METHOD_COUNT) {
return 0;
}
switch (id) {
case GD_DEFAULT:
im->interpolation_id = GD_BILINEAR_FIXED;
im->interpolation = NULL;
break;
/* Optimized versions */
case GD_BILINEAR_FIXED:
case GD_BICUBIC_FIXED:
case GD_NEAREST_NEIGHBOUR:
case GD_WEIGHTED4:
im->interpolation = NULL;
break;
/* generic versions*/
case GD_BELL:
im->interpolation = filter_bell;
break;
case GD_BESSEL:
im->interpolation = filter_bessel;
break;
case GD_BICUBIC:
im->interpolation = filter_bicubic;
break;
case GD_BLACKMAN:
im->interpolation = filter_blackman;
break;
case GD_BOX:
im->interpolation = filter_box;
break;
case GD_BSPLINE:
im->interpolation = filter_bspline;
break;
case GD_CATMULLROM:
im->interpolation = filter_catmullrom;
break;
case GD_GAUSSIAN:
im->interpolation = filter_gaussian;
break;
case GD_GENERALIZED_CUBIC:
im->interpolation = filter_generalized_cubic;
break;
case GD_HERMITE:
im->interpolation = filter_hermite;
break;
case GD_HAMMING:
im->interpolation = filter_hamming;
break;
case GD_HANNING:
im->interpolation = filter_hanning;
break;
case GD_MITCHELL:
im->interpolation = filter_mitchell;
break;
case GD_POWER:
im->interpolation = filter_power;
break;
case GD_QUADRATIC:
im->interpolation = filter_quadratic;
break;
case GD_SINC:
im->interpolation = filter_sinc;
break;
case GD_TRIANGLE:
im->interpolation = filter_triangle;
break;
default:
return 0;
break;
}
im->interpolation_id = id;
return 1;
}
#ifdef _MSC_VER
# pragma optimize("", on)
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5869_0 |
crossvul-cpp_data_good_2717_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 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 Internet Control Message Protocol (ICMPv6) 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 "addrtostr.h"
#include "extract.h"
#include "ip6.h"
#include "ipproto.h"
#include "udp.h"
#include "ah.h"
/* NetBSD: icmp6.h,v 1.13 2000/08/03 16:30:37 itojun Exp */
/* $KAME: icmp6.h,v 1.22 2000/08/03 15:25:16 jinmei Exp $ */
/*
* 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.
*/
struct icmp6_hdr {
uint8_t icmp6_type; /* type field */
uint8_t icmp6_code; /* code field */
uint16_t icmp6_cksum; /* checksum field */
union {
uint32_t icmp6_un_data32[1]; /* type-specific field */
uint16_t icmp6_un_data16[2]; /* type-specific field */
uint8_t icmp6_un_data8[4]; /* type-specific field */
} icmp6_dataun;
};
#define icmp6_data32 icmp6_dataun.icmp6_un_data32
#define icmp6_data16 icmp6_dataun.icmp6_un_data16
#define icmp6_data8 icmp6_dataun.icmp6_un_data8
#define icmp6_pptr icmp6_data32[0] /* parameter prob */
#define icmp6_mtu icmp6_data32[0] /* packet too big */
#define icmp6_id icmp6_data16[0] /* echo request/reply */
#define icmp6_seq icmp6_data16[1] /* echo request/reply */
#define icmp6_maxdelay icmp6_data16[0] /* mcast group membership */
#define ICMP6_DST_UNREACH 1 /* dest unreachable, codes: */
#define ICMP6_PACKET_TOO_BIG 2 /* packet too big */
#define ICMP6_TIME_EXCEEDED 3 /* time exceeded, code: */
#define ICMP6_PARAM_PROB 4 /* ip6 header bad */
#define ICMP6_ECHO_REQUEST 128 /* echo service */
#define ICMP6_ECHO_REPLY 129 /* echo reply */
#define ICMP6_MEMBERSHIP_QUERY 130 /* group membership query */
#define MLD6_LISTENER_QUERY 130 /* multicast listener query */
#define ICMP6_MEMBERSHIP_REPORT 131 /* group membership report */
#define MLD6_LISTENER_REPORT 131 /* multicast listener report */
#define ICMP6_MEMBERSHIP_REDUCTION 132 /* group membership termination */
#define MLD6_LISTENER_DONE 132 /* multicast listener done */
#define ND_ROUTER_SOLICIT 133 /* router solicitation */
#define ND_ROUTER_ADVERT 134 /* router advertisement */
#define ND_NEIGHBOR_SOLICIT 135 /* neighbor solicitation */
#define ND_NEIGHBOR_ADVERT 136 /* neighbor advertisement */
#define ND_REDIRECT 137 /* redirect */
#define ICMP6_ROUTER_RENUMBERING 138 /* router renumbering */
#define ICMP6_WRUREQUEST 139 /* who are you request */
#define ICMP6_WRUREPLY 140 /* who are you reply */
#define ICMP6_FQDN_QUERY 139 /* FQDN query */
#define ICMP6_FQDN_REPLY 140 /* FQDN reply */
#define ICMP6_NI_QUERY 139 /* node information request */
#define ICMP6_NI_REPLY 140 /* node information reply */
#define IND_SOLICIT 141 /* inverse neighbor solicitation */
#define IND_ADVERT 142 /* inverse neighbor advertisement */
#define ICMP6_V2_MEMBERSHIP_REPORT 143 /* v2 membership report */
#define MLDV2_LISTENER_REPORT 143 /* v2 multicast listener report */
#define ICMP6_HADISCOV_REQUEST 144
#define ICMP6_HADISCOV_REPLY 145
#define ICMP6_MOBILEPREFIX_SOLICIT 146
#define ICMP6_MOBILEPREFIX_ADVERT 147
#define MLD6_MTRACE_RESP 200 /* mtrace response(to sender) */
#define MLD6_MTRACE 201 /* mtrace messages */
#define ICMP6_MAXTYPE 201
#define ICMP6_DST_UNREACH_NOROUTE 0 /* no route to destination */
#define ICMP6_DST_UNREACH_ADMIN 1 /* administratively prohibited */
#define ICMP6_DST_UNREACH_NOTNEIGHBOR 2 /* not a neighbor(obsolete) */
#define ICMP6_DST_UNREACH_BEYONDSCOPE 2 /* beyond scope of source address */
#define ICMP6_DST_UNREACH_ADDR 3 /* address unreachable */
#define ICMP6_DST_UNREACH_NOPORT 4 /* port unreachable */
#define ICMP6_TIME_EXCEED_TRANSIT 0 /* ttl==0 in transit */
#define ICMP6_TIME_EXCEED_REASSEMBLY 1 /* ttl==0 in reass */
#define ICMP6_PARAMPROB_HEADER 0 /* erroneous header field */
#define ICMP6_PARAMPROB_NEXTHEADER 1 /* unrecognized next header */
#define ICMP6_PARAMPROB_OPTION 2 /* unrecognized option */
#define ICMP6_INFOMSG_MASK 0x80 /* all informational messages */
#define ICMP6_NI_SUBJ_IPV6 0 /* Query Subject is an IPv6 address */
#define ICMP6_NI_SUBJ_FQDN 1 /* Query Subject is a Domain name */
#define ICMP6_NI_SUBJ_IPV4 2 /* Query Subject is an IPv4 address */
#define ICMP6_NI_SUCCESS 0 /* node information successful reply */
#define ICMP6_NI_REFUSED 1 /* node information request is refused */
#define ICMP6_NI_UNKNOWN 2 /* unknown Qtype */
#define ICMP6_ROUTER_RENUMBERING_COMMAND 0 /* rr command */
#define ICMP6_ROUTER_RENUMBERING_RESULT 1 /* rr result */
#define ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET 255 /* rr seq num reset */
/* Used in kernel only */
#define ND_REDIRECT_ONLINK 0 /* redirect to an on-link node */
#define ND_REDIRECT_ROUTER 1 /* redirect to a better router */
/*
* Multicast Listener Discovery
*/
struct mld6_hdr {
struct icmp6_hdr mld6_hdr;
struct in6_addr mld6_addr; /* multicast address */
};
#define mld6_type mld6_hdr.icmp6_type
#define mld6_code mld6_hdr.icmp6_code
#define mld6_cksum mld6_hdr.icmp6_cksum
#define mld6_maxdelay mld6_hdr.icmp6_data16[0]
#define mld6_reserved mld6_hdr.icmp6_data16[1]
#define MLD_MINLEN 24
#define MLDV2_MINLEN 28
/*
* Neighbor Discovery
*/
struct nd_router_solicit { /* router solicitation */
struct icmp6_hdr nd_rs_hdr;
/* could be followed by options */
};
#define nd_rs_type nd_rs_hdr.icmp6_type
#define nd_rs_code nd_rs_hdr.icmp6_code
#define nd_rs_cksum nd_rs_hdr.icmp6_cksum
#define nd_rs_reserved nd_rs_hdr.icmp6_data32[0]
struct nd_router_advert { /* router advertisement */
struct icmp6_hdr nd_ra_hdr;
uint32_t nd_ra_reachable; /* reachable time */
uint32_t nd_ra_retransmit; /* retransmit timer */
/* could be followed by options */
};
#define nd_ra_type nd_ra_hdr.icmp6_type
#define nd_ra_code nd_ra_hdr.icmp6_code
#define nd_ra_cksum nd_ra_hdr.icmp6_cksum
#define nd_ra_curhoplimit nd_ra_hdr.icmp6_data8[0]
#define nd_ra_flags_reserved nd_ra_hdr.icmp6_data8[1]
#define ND_RA_FLAG_MANAGED 0x80
#define ND_RA_FLAG_OTHER 0x40
#define ND_RA_FLAG_HOME_AGENT 0x20
/*
* Router preference values based on draft-draves-ipngwg-router-selection-01.
* These are non-standard definitions.
*/
#define ND_RA_FLAG_RTPREF_MASK 0x18 /* 00011000 */
#define ND_RA_FLAG_RTPREF_HIGH 0x08 /* 00001000 */
#define ND_RA_FLAG_RTPREF_MEDIUM 0x00 /* 00000000 */
#define ND_RA_FLAG_RTPREF_LOW 0x18 /* 00011000 */
#define ND_RA_FLAG_RTPREF_RSV 0x10 /* 00010000 */
#define nd_ra_router_lifetime nd_ra_hdr.icmp6_data16[1]
struct nd_neighbor_solicit { /* neighbor solicitation */
struct icmp6_hdr nd_ns_hdr;
struct in6_addr nd_ns_target; /*target address */
/* could be followed by options */
};
#define nd_ns_type nd_ns_hdr.icmp6_type
#define nd_ns_code nd_ns_hdr.icmp6_code
#define nd_ns_cksum nd_ns_hdr.icmp6_cksum
#define nd_ns_reserved nd_ns_hdr.icmp6_data32[0]
struct nd_neighbor_advert { /* neighbor advertisement */
struct icmp6_hdr nd_na_hdr;
struct in6_addr nd_na_target; /* target address */
/* could be followed by options */
};
#define nd_na_type nd_na_hdr.icmp6_type
#define nd_na_code nd_na_hdr.icmp6_code
#define nd_na_cksum nd_na_hdr.icmp6_cksum
#define nd_na_flags_reserved nd_na_hdr.icmp6_data32[0]
#define ND_NA_FLAG_ROUTER 0x80000000
#define ND_NA_FLAG_SOLICITED 0x40000000
#define ND_NA_FLAG_OVERRIDE 0x20000000
struct nd_redirect { /* redirect */
struct icmp6_hdr nd_rd_hdr;
struct in6_addr nd_rd_target; /* target address */
struct in6_addr nd_rd_dst; /* destination address */
/* could be followed by options */
};
#define nd_rd_type nd_rd_hdr.icmp6_type
#define nd_rd_code nd_rd_hdr.icmp6_code
#define nd_rd_cksum nd_rd_hdr.icmp6_cksum
#define nd_rd_reserved nd_rd_hdr.icmp6_data32[0]
struct nd_opt_hdr { /* Neighbor discovery option header */
uint8_t nd_opt_type;
uint8_t nd_opt_len;
/* followed by option specific data*/
};
#define ND_OPT_SOURCE_LINKADDR 1
#define ND_OPT_TARGET_LINKADDR 2
#define ND_OPT_PREFIX_INFORMATION 3
#define ND_OPT_REDIRECTED_HEADER 4
#define ND_OPT_MTU 5
#define ND_OPT_ADVINTERVAL 7
#define ND_OPT_HOMEAGENT_INFO 8
#define ND_OPT_ROUTE_INFO 24 /* RFC4191 */
#define ND_OPT_RDNSS 25
#define ND_OPT_DNSSL 31
struct nd_opt_prefix_info { /* prefix information */
nd_uint8_t nd_opt_pi_type;
nd_uint8_t nd_opt_pi_len;
nd_uint8_t nd_opt_pi_prefix_len;
nd_uint8_t nd_opt_pi_flags_reserved;
nd_uint32_t nd_opt_pi_valid_time;
nd_uint32_t nd_opt_pi_preferred_time;
nd_uint32_t nd_opt_pi_reserved2;
struct in6_addr nd_opt_pi_prefix;
};
#define ND_OPT_PI_FLAG_ONLINK 0x80
#define ND_OPT_PI_FLAG_AUTO 0x40
#define ND_OPT_PI_FLAG_ROUTER 0x20 /*2292bis*/
struct nd_opt_rd_hdr { /* redirected header */
uint8_t nd_opt_rh_type;
uint8_t nd_opt_rh_len;
uint16_t nd_opt_rh_reserved1;
uint32_t nd_opt_rh_reserved2;
/* followed by IP header and data */
};
struct nd_opt_mtu { /* MTU option */
uint8_t nd_opt_mtu_type;
uint8_t nd_opt_mtu_len;
uint16_t nd_opt_mtu_reserved;
uint32_t nd_opt_mtu_mtu;
};
struct nd_opt_rdnss { /* RDNSS RFC 6106 5.1 */
uint8_t nd_opt_rdnss_type;
uint8_t nd_opt_rdnss_len;
uint16_t nd_opt_rdnss_reserved;
uint32_t nd_opt_rdnss_lifetime;
struct in6_addr nd_opt_rdnss_addr[1]; /* variable-length */
};
struct nd_opt_dnssl { /* DNSSL RFC 6106 5.2 */
uint8_t nd_opt_dnssl_type;
uint8_t nd_opt_dnssl_len;
uint16_t nd_opt_dnssl_reserved;
uint32_t nd_opt_dnssl_lifetime;
/* followed by list of DNS search domains, variable-length */
};
struct nd_opt_advinterval { /* Advertisement interval option */
uint8_t nd_opt_adv_type;
uint8_t nd_opt_adv_len;
uint16_t nd_opt_adv_reserved;
uint32_t nd_opt_adv_interval;
};
struct nd_opt_homeagent_info { /* Home Agent info */
uint8_t nd_opt_hai_type;
uint8_t nd_opt_hai_len;
uint16_t nd_opt_hai_reserved;
int16_t nd_opt_hai_preference;
uint16_t nd_opt_hai_lifetime;
};
struct nd_opt_route_info { /* route info */
uint8_t nd_opt_rti_type;
uint8_t nd_opt_rti_len;
uint8_t nd_opt_rti_prefixlen;
uint8_t nd_opt_rti_flags;
uint32_t nd_opt_rti_lifetime;
/* prefix follows */
};
/*
* icmp6 namelookup
*/
struct icmp6_namelookup {
struct icmp6_hdr icmp6_nl_hdr;
uint8_t icmp6_nl_nonce[8];
int32_t icmp6_nl_ttl;
#if 0
uint8_t icmp6_nl_len;
uint8_t icmp6_nl_name[3];
#endif
/* could be followed by options */
};
/*
* icmp6 node information
*/
struct icmp6_nodeinfo {
struct icmp6_hdr icmp6_ni_hdr;
uint8_t icmp6_ni_nonce[8];
/* could be followed by reply data */
};
#define ni_type icmp6_ni_hdr.icmp6_type
#define ni_code icmp6_ni_hdr.icmp6_code
#define ni_cksum icmp6_ni_hdr.icmp6_cksum
#define ni_qtype icmp6_ni_hdr.icmp6_data16[0]
#define ni_flags icmp6_ni_hdr.icmp6_data16[1]
#define NI_QTYPE_NOOP 0 /* NOOP */
#define NI_QTYPE_SUPTYPES 1 /* Supported Qtypes */
#define NI_QTYPE_FQDN 2 /* FQDN (draft 04) */
#define NI_QTYPE_DNSNAME 2 /* DNS Name */
#define NI_QTYPE_NODEADDR 3 /* Node Addresses */
#define NI_QTYPE_IPV4ADDR 4 /* IPv4 Addresses */
/* network endian */
#define NI_SUPTYPE_FLAG_COMPRESS ((uint16_t)htons(0x1))
#define NI_FQDN_FLAG_VALIDTTL ((uint16_t)htons(0x1))
/* network endian */
#define NI_NODEADDR_FLAG_TRUNCATE ((uint16_t)htons(0x1))
#define NI_NODEADDR_FLAG_ALL ((uint16_t)htons(0x2))
#define NI_NODEADDR_FLAG_COMPAT ((uint16_t)htons(0x4))
#define NI_NODEADDR_FLAG_LINKLOCAL ((uint16_t)htons(0x8))
#define NI_NODEADDR_FLAG_SITELOCAL ((uint16_t)htons(0x10))
#define NI_NODEADDR_FLAG_GLOBAL ((uint16_t)htons(0x20))
#define NI_NODEADDR_FLAG_ANYCAST ((uint16_t)htons(0x40)) /* just experimental. not in spec */
struct ni_reply_fqdn {
uint32_t ni_fqdn_ttl; /* TTL */
uint8_t ni_fqdn_namelen; /* length in octets of the FQDN */
uint8_t ni_fqdn_name[3]; /* XXX: alignment */
};
/*
* Router Renumbering. as router-renum-08.txt
*/
struct icmp6_router_renum { /* router renumbering header */
struct icmp6_hdr rr_hdr;
uint8_t rr_segnum;
uint8_t rr_flags;
uint16_t rr_maxdelay;
uint32_t rr_reserved;
};
#define ICMP6_RR_FLAGS_TEST 0x80
#define ICMP6_RR_FLAGS_REQRESULT 0x40
#define ICMP6_RR_FLAGS_FORCEAPPLY 0x20
#define ICMP6_RR_FLAGS_SPECSITE 0x10
#define ICMP6_RR_FLAGS_PREVDONE 0x08
#define rr_type rr_hdr.icmp6_type
#define rr_code rr_hdr.icmp6_code
#define rr_cksum rr_hdr.icmp6_cksum
#define rr_seqnum rr_hdr.icmp6_data32[0]
struct rr_pco_match { /* match prefix part */
uint8_t rpm_code;
uint8_t rpm_len;
uint8_t rpm_ordinal;
uint8_t rpm_matchlen;
uint8_t rpm_minlen;
uint8_t rpm_maxlen;
uint16_t rpm_reserved;
struct in6_addr rpm_prefix;
};
#define RPM_PCO_ADD 1
#define RPM_PCO_CHANGE 2
#define RPM_PCO_SETGLOBAL 3
#define RPM_PCO_MAX 4
struct rr_pco_use { /* use prefix part */
uint8_t rpu_uselen;
uint8_t rpu_keeplen;
uint8_t rpu_ramask;
uint8_t rpu_raflags;
uint32_t rpu_vltime;
uint32_t rpu_pltime;
uint32_t rpu_flags;
struct in6_addr rpu_prefix;
};
#define ICMP6_RR_PCOUSE_RAFLAGS_ONLINK 0x80
#define ICMP6_RR_PCOUSE_RAFLAGS_AUTO 0x40
/* network endian */
#define ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME ((uint32_t)htonl(0x80000000))
#define ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME ((uint32_t)htonl(0x40000000))
struct rr_result { /* router renumbering result message */
uint16_t rrr_flags;
uint8_t rrr_ordinal;
uint8_t rrr_matchedlen;
uint32_t rrr_ifid;
struct in6_addr rrr_prefix;
};
/* network endian */
#define ICMP6_RR_RESULT_FLAGS_OOB ((uint16_t)htons(0x0002))
#define ICMP6_RR_RESULT_FLAGS_FORBIDDEN ((uint16_t)htons(0x0001))
static const char *get_rtpref(u_int);
static const char *get_lifetime(uint32_t);
static void print_lladdr(netdissect_options *ndo, const u_char *, size_t);
static void icmp6_opt_print(netdissect_options *ndo, const u_char *, int);
static void mld6_print(netdissect_options *ndo, const u_char *);
static void mldv2_report_print(netdissect_options *ndo, const u_char *, u_int);
static void mldv2_query_print(netdissect_options *ndo, const u_char *, u_int);
static const struct udphdr *get_upperlayer(netdissect_options *ndo, const u_char *, u_int *);
static void dnsname_print(netdissect_options *ndo, const u_char *, const u_char *);
static void icmp6_nodeinfo_print(netdissect_options *ndo, u_int, const u_char *, const u_char *);
static void icmp6_rrenum_print(netdissect_options *ndo, const u_char *, const u_char *);
#ifndef abs
#define abs(a) ((0 < (a)) ? (a) : -(a))
#endif
#include "rpl.h"
static const struct tok icmp6_type_values[] = {
{ ICMP6_DST_UNREACH, "destination unreachable"},
{ ICMP6_PACKET_TOO_BIG, "packet too big"},
{ ICMP6_TIME_EXCEEDED, "time exceeded in-transit"},
{ ICMP6_PARAM_PROB, "parameter problem"},
{ ICMP6_ECHO_REQUEST, "echo request"},
{ ICMP6_ECHO_REPLY, "echo reply"},
{ MLD6_LISTENER_QUERY, "multicast listener query"},
{ MLD6_LISTENER_REPORT, "multicast listener report"},
{ MLD6_LISTENER_DONE, "multicast listener done"},
{ ND_ROUTER_SOLICIT, "router solicitation"},
{ ND_ROUTER_ADVERT, "router advertisement"},
{ ND_NEIGHBOR_SOLICIT, "neighbor solicitation"},
{ ND_NEIGHBOR_ADVERT, "neighbor advertisement"},
{ ND_REDIRECT, "redirect"},
{ ICMP6_ROUTER_RENUMBERING, "router renumbering"},
{ IND_SOLICIT, "inverse neighbor solicitation"},
{ IND_ADVERT, "inverse neighbor advertisement"},
{ MLDV2_LISTENER_REPORT, "multicast listener report v2"},
{ ICMP6_HADISCOV_REQUEST, "ha discovery request"},
{ ICMP6_HADISCOV_REPLY, "ha discovery reply"},
{ ICMP6_MOBILEPREFIX_SOLICIT, "mobile router solicitation"},
{ ICMP6_MOBILEPREFIX_ADVERT, "mobile router advertisement"},
{ ICMP6_WRUREQUEST, "who-are-you request"},
{ ICMP6_WRUREPLY, "who-are-you reply"},
{ ICMP6_NI_QUERY, "node information query"},
{ ICMP6_NI_REPLY, "node information reply"},
{ MLD6_MTRACE, "mtrace message"},
{ MLD6_MTRACE_RESP, "mtrace response"},
{ ND_RPL_MESSAGE, "RPL"},
{ 0, NULL }
};
static const struct tok icmp6_dst_unreach_code_values[] = {
{ ICMP6_DST_UNREACH_NOROUTE, "unreachable route" },
{ ICMP6_DST_UNREACH_ADMIN, " unreachable prohibited"},
{ ICMP6_DST_UNREACH_BEYONDSCOPE, "beyond scope"},
{ ICMP6_DST_UNREACH_ADDR, "unreachable address"},
{ ICMP6_DST_UNREACH_NOPORT, "unreachable port"},
{ 0, NULL }
};
static const struct tok icmp6_opt_pi_flag_values[] = {
{ ND_OPT_PI_FLAG_ONLINK, "onlink" },
{ ND_OPT_PI_FLAG_AUTO, "auto" },
{ ND_OPT_PI_FLAG_ROUTER, "router" },
{ 0, NULL }
};
static const struct tok icmp6_opt_ra_flag_values[] = {
{ ND_RA_FLAG_MANAGED, "managed" },
{ ND_RA_FLAG_OTHER, "other stateful"},
{ ND_RA_FLAG_HOME_AGENT, "home agent"},
{ 0, NULL }
};
static const struct tok icmp6_nd_na_flag_values[] = {
{ ND_NA_FLAG_ROUTER, "router" },
{ ND_NA_FLAG_SOLICITED, "solicited" },
{ ND_NA_FLAG_OVERRIDE, "override" },
{ 0, NULL }
};
static const struct tok icmp6_opt_values[] = {
{ ND_OPT_SOURCE_LINKADDR, "source link-address"},
{ ND_OPT_TARGET_LINKADDR, "destination link-address"},
{ ND_OPT_PREFIX_INFORMATION, "prefix info"},
{ ND_OPT_REDIRECTED_HEADER, "redirected header"},
{ ND_OPT_MTU, "mtu"},
{ ND_OPT_RDNSS, "rdnss"},
{ ND_OPT_DNSSL, "dnssl"},
{ ND_OPT_ADVINTERVAL, "advertisement interval"},
{ ND_OPT_HOMEAGENT_INFO, "homeagent information"},
{ ND_OPT_ROUTE_INFO, "route info"},
{ 0, NULL }
};
/* mldv2 report types */
static const struct tok mldv2report2str[] = {
{ 1, "is_in" },
{ 2, "is_ex" },
{ 3, "to_in" },
{ 4, "to_ex" },
{ 5, "allow" },
{ 6, "block" },
{ 0, NULL }
};
static const char *
get_rtpref(u_int v)
{
static const char *rtpref_str[] = {
"medium", /* 00 */
"high", /* 01 */
"rsv", /* 10 */
"low" /* 11 */
};
return rtpref_str[((v & ND_RA_FLAG_RTPREF_MASK) >> 3) & 0xff];
}
static const char *
get_lifetime(uint32_t v)
{
static char buf[20];
if (v == (uint32_t)~0UL)
return "infinity";
else {
snprintf(buf, sizeof(buf), "%us", v);
return buf;
}
}
static void
print_lladdr(netdissect_options *ndo, const uint8_t *p, size_t l)
{
const uint8_t *ep, *q;
q = p;
ep = p + l;
while (l > 0 && q < ep) {
if (q > p)
ND_PRINT((ndo,":"));
ND_PRINT((ndo,"%02x", *q++));
l--;
}
}
static int icmp6_cksum(netdissect_options *ndo, const struct ip6_hdr *ip6,
const struct icmp6_hdr *icp, u_int len)
{
return nextproto6_cksum(ndo, ip6, (const uint8_t *)(const void *)icp, len, len,
IPPROTO_ICMPV6);
}
static const struct tok rpl_mop_values[] = {
{ RPL_DIO_NONSTORING, "nonstoring"},
{ RPL_DIO_STORING, "storing"},
{ RPL_DIO_NONSTORING_MULTICAST, "nonstoring-multicast"},
{ RPL_DIO_STORING_MULTICAST, "storing-multicast"},
{ 0, NULL},
};
static const struct tok rpl_subopt_values[] = {
{ RPL_OPT_PAD0, "pad0"},
{ RPL_OPT_PADN, "padN"},
{ RPL_DIO_METRICS, "metrics"},
{ RPL_DIO_ROUTINGINFO, "routinginfo"},
{ RPL_DIO_CONFIG, "config"},
{ RPL_DAO_RPLTARGET, "rpltarget"},
{ RPL_DAO_TRANSITINFO, "transitinfo"},
{ RPL_DIO_DESTPREFIX, "destprefix"},
{ RPL_DAO_RPLTARGET_DESC, "rpltargetdesc"},
{ 0, NULL},
};
static void
rpl_dio_printopt(netdissect_options *ndo,
const struct rpl_dio_genoption *opt,
u_int length)
{
if(length < RPL_DIO_GENOPTION_LEN) return;
length -= RPL_DIO_GENOPTION_LEN;
ND_TCHECK(opt->rpl_dio_len);
while((opt->rpl_dio_type == RPL_OPT_PAD0 &&
(const u_char *)opt < ndo->ndo_snapend) ||
ND_TTEST2(*opt,(opt->rpl_dio_len+2))) {
unsigned int optlen = opt->rpl_dio_len+2;
if(opt->rpl_dio_type == RPL_OPT_PAD0) {
optlen = 1;
ND_PRINT((ndo, " opt:pad0"));
} else {
ND_PRINT((ndo, " opt:%s len:%u ",
tok2str(rpl_subopt_values, "subopt:%u", opt->rpl_dio_type),
optlen));
if(ndo->ndo_vflag > 2) {
unsigned int paylen = opt->rpl_dio_len;
if(paylen > length) paylen = length;
hex_print(ndo,
" ",
((const uint8_t *)opt) + RPL_DIO_GENOPTION_LEN, /* content of DIO option */
paylen);
}
}
opt = (const struct rpl_dio_genoption *)(((const char *)opt) + optlen);
length -= optlen;
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
}
static void
rpl_dio_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_dio *dio = (const struct nd_rpl_dio *)bp;
const char *dagid_str;
ND_TCHECK(*dio);
dagid_str = ip6addr_string (ndo, dio->rpl_dagid);
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,rank:%u,%smop:%s,prf:%u]",
dagid_str,
dio->rpl_dtsn,
dio->rpl_instanceid,
EXTRACT_16BITS(&dio->rpl_dagrank),
RPL_DIO_GROUNDED(dio->rpl_mopprf) ? "grounded,":"",
tok2str(rpl_mop_values, "mop%u", RPL_DIO_MOP(dio->rpl_mopprf)),
RPL_DIO_PRF(dio->rpl_mopprf)));
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)&dio[1];
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
}
static void
rpl_dao_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_dao *dao = (const struct nd_rpl_dao *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK(*dao);
if (length < ND_RPL_DAO_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAO_MIN_LEN;
length -= ND_RPL_DAO_MIN_LEN;
if(RPL_DAO_D(dao->rpl_flags)) {
ND_TCHECK2(dao->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, dao->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u%s%s,%02x]",
dagid_str,
dao->rpl_daoseq,
dao->rpl_instanceid,
RPL_DAO_K(dao->rpl_flags) ? ",acK":"",
RPL_DAO_D(dao->rpl_flags) ? ",Dagid":"",
dao->rpl_flags));
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
tooshort:
ND_PRINT((ndo," [|length too short]"));
return;
}
static void
rpl_daoack_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_daoack *daoack = (const struct nd_rpl_daoack *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK2(*daoack, ND_RPL_DAOACK_MIN_LEN);
if (length < ND_RPL_DAOACK_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAOACK_MIN_LEN;
length -= ND_RPL_DAOACK_MIN_LEN;
if(RPL_DAOACK_D(daoack->rpl_flags)) {
ND_TCHECK2(daoack->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, daoack->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,status:%u]",
dagid_str,
daoack->rpl_daoseq,
daoack->rpl_instanceid,
daoack->rpl_status));
/* no officially defined options for DAOACK, but print any we find */
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|dao-truncated]"));
return;
tooshort:
ND_PRINT((ndo," [|dao-length too short]"));
return;
}
static void
rpl_print(netdissect_options *ndo,
const struct icmp6_hdr *hdr,
const u_char *bp, u_int length)
{
int secured = hdr->icmp6_code & 0x80;
int basecode= hdr->icmp6_code & 0x7f;
if(secured) {
ND_PRINT((ndo, ", (SEC) [worktodo]"));
/* XXX
* the next header pointer needs to move forward to
* skip the secure part.
*/
return;
} else {
ND_PRINT((ndo, ", (CLR)"));
}
switch(basecode) {
case ND_RPL_DAG_IS:
ND_PRINT((ndo, "DODAG Information Solicitation"));
if(ndo->ndo_vflag) {
}
break;
case ND_RPL_DAG_IO:
ND_PRINT((ndo, "DODAG Information Object"));
if(ndo->ndo_vflag) {
rpl_dio_print(ndo, bp, length);
}
break;
case ND_RPL_DAO:
ND_PRINT((ndo, "Destination Advertisement Object"));
if(ndo->ndo_vflag) {
rpl_dao_print(ndo, bp, length);
}
break;
case ND_RPL_DAO_ACK:
ND_PRINT((ndo, "Destination Advertisement Object Ack"));
if(ndo->ndo_vflag) {
rpl_daoack_print(ndo, bp, length);
}
break;
default:
ND_PRINT((ndo, "RPL message, unknown code %u",hdr->icmp6_code));
break;
}
return;
#if 0
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
#endif
}
void
icmp6_print(netdissect_options *ndo,
const u_char *bp, u_int length, const u_char *bp2, int fragmented)
{
const struct icmp6_hdr *dp;
const struct ip6_hdr *ip;
const struct ip6_hdr *oip;
const struct udphdr *ouh;
int dport;
const u_char *ep;
u_int prot;
dp = (const struct icmp6_hdr *)bp;
ip = (const struct ip6_hdr *)bp2;
oip = (const struct ip6_hdr *)(dp + 1);
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
ND_TCHECK(dp->icmp6_cksum);
if (ndo->ndo_vflag && !fragmented) {
uint16_t sum, udp_sum;
if (ND_TTEST2(bp[0], length)) {
udp_sum = EXTRACT_16BITS(&dp->icmp6_cksum);
sum = icmp6_cksum(ndo, ip, dp, length);
if (sum != 0)
ND_PRINT((ndo,"[bad icmp6 cksum 0x%04x -> 0x%04x!] ",
udp_sum,
in_cksum_shouldbe(udp_sum, sum)));
else
ND_PRINT((ndo,"[icmp6 sum ok] "));
}
}
ND_PRINT((ndo,"ICMP6, %s", tok2str(icmp6_type_values,"unknown icmp6 type (%u)",dp->icmp6_type)));
/* display cosmetics: print the packet length for printer that use the vflag now */
if (ndo->ndo_vflag && (dp->icmp6_type == ND_ROUTER_SOLICIT ||
dp->icmp6_type == ND_ROUTER_ADVERT ||
dp->icmp6_type == ND_NEIGHBOR_ADVERT ||
dp->icmp6_type == ND_NEIGHBOR_SOLICIT ||
dp->icmp6_type == ND_REDIRECT ||
dp->icmp6_type == ICMP6_HADISCOV_REPLY ||
dp->icmp6_type == ICMP6_MOBILEPREFIX_ADVERT ))
ND_PRINT((ndo,", length %u", length));
switch (dp->icmp6_type) {
case ICMP6_DST_UNREACH:
ND_TCHECK(oip->ip6_dst);
ND_PRINT((ndo,", %s", tok2str(icmp6_dst_unreach_code_values,"unknown unreach code (%u)",dp->icmp6_code)));
switch (dp->icmp6_code) {
case ICMP6_DST_UNREACH_NOROUTE: /* fall through */
case ICMP6_DST_UNREACH_ADMIN:
case ICMP6_DST_UNREACH_ADDR:
ND_PRINT((ndo," %s",ip6addr_string(ndo, &oip->ip6_dst)));
break;
case ICMP6_DST_UNREACH_BEYONDSCOPE:
ND_PRINT((ndo," %s, source address %s",
ip6addr_string(ndo, &oip->ip6_dst),
ip6addr_string(ndo, &oip->ip6_src)));
break;
case ICMP6_DST_UNREACH_NOPORT:
if ((ouh = get_upperlayer(ndo, (const u_char *)oip, &prot))
== NULL)
goto trunc;
dport = EXTRACT_16BITS(&ouh->uh_dport);
switch (prot) {
case IPPROTO_TCP:
ND_PRINT((ndo,", %s tcp port %s",
ip6addr_string(ndo, &oip->ip6_dst),
tcpport_string(ndo, dport)));
break;
case IPPROTO_UDP:
ND_PRINT((ndo,", %s udp port %s",
ip6addr_string(ndo, &oip->ip6_dst),
udpport_string(ndo, dport)));
break;
default:
ND_PRINT((ndo,", %s protocol %d port %d unreachable",
ip6addr_string(ndo, &oip->ip6_dst),
oip->ip6_nxt, dport));
break;
}
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, bp,"\n\t",length);
return;
}
break;
}
break;
case ICMP6_PACKET_TOO_BIG:
ND_TCHECK(dp->icmp6_mtu);
ND_PRINT((ndo,", mtu %u", EXTRACT_32BITS(&dp->icmp6_mtu)));
break;
case ICMP6_TIME_EXCEEDED:
ND_TCHECK(oip->ip6_dst);
switch (dp->icmp6_code) {
case ICMP6_TIME_EXCEED_TRANSIT:
ND_PRINT((ndo," for %s",
ip6addr_string(ndo, &oip->ip6_dst)));
break;
case ICMP6_TIME_EXCEED_REASSEMBLY:
ND_PRINT((ndo," (reassembly)"));
break;
default:
ND_PRINT((ndo,", unknown code (%u)", dp->icmp6_code));
break;
}
break;
case ICMP6_PARAM_PROB:
ND_TCHECK(oip->ip6_dst);
switch (dp->icmp6_code) {
case ICMP6_PARAMPROB_HEADER:
ND_PRINT((ndo,", erroneous - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr)));
break;
case ICMP6_PARAMPROB_NEXTHEADER:
ND_PRINT((ndo,", next header - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr)));
break;
case ICMP6_PARAMPROB_OPTION:
ND_PRINT((ndo,", option - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr)));
break;
default:
ND_PRINT((ndo,", code-#%d",
dp->icmp6_code));
break;
}
break;
case ICMP6_ECHO_REQUEST:
case ICMP6_ECHO_REPLY:
ND_TCHECK(dp->icmp6_seq);
ND_PRINT((ndo,", seq %u", EXTRACT_16BITS(&dp->icmp6_seq)));
break;
case ICMP6_MEMBERSHIP_QUERY:
if (length == MLD_MINLEN) {
mld6_print(ndo, (const u_char *)dp);
} else if (length >= MLDV2_MINLEN) {
ND_PRINT((ndo," v2"));
mldv2_query_print(ndo, (const u_char *)dp, length);
} else {
ND_PRINT((ndo," unknown-version (len %u) ", length));
}
break;
case ICMP6_MEMBERSHIP_REPORT:
mld6_print(ndo, (const u_char *)dp);
break;
case ICMP6_MEMBERSHIP_REDUCTION:
mld6_print(ndo, (const u_char *)dp);
break;
case ND_ROUTER_SOLICIT:
#define RTSOLLEN 8
if (ndo->ndo_vflag) {
icmp6_opt_print(ndo, (const u_char *)dp + RTSOLLEN,
length - RTSOLLEN);
}
break;
case ND_ROUTER_ADVERT:
#define RTADVLEN 16
if (ndo->ndo_vflag) {
const struct nd_router_advert *p;
p = (const struct nd_router_advert *)dp;
ND_TCHECK(p->nd_ra_retransmit);
ND_PRINT((ndo,"\n\thop limit %u, Flags [%s]" \
", pref %s, router lifetime %us, reachable time %us, retrans time %us",
(u_int)p->nd_ra_curhoplimit,
bittok2str(icmp6_opt_ra_flag_values,"none",(p->nd_ra_flags_reserved)),
get_rtpref(p->nd_ra_flags_reserved),
EXTRACT_16BITS(&p->nd_ra_router_lifetime),
EXTRACT_32BITS(&p->nd_ra_reachable),
EXTRACT_32BITS(&p->nd_ra_retransmit)));
icmp6_opt_print(ndo, (const u_char *)dp + RTADVLEN,
length - RTADVLEN);
}
break;
case ND_NEIGHBOR_SOLICIT:
{
const struct nd_neighbor_solicit *p;
p = (const struct nd_neighbor_solicit *)dp;
ND_TCHECK(p->nd_ns_target);
ND_PRINT((ndo,", who has %s", ip6addr_string(ndo, &p->nd_ns_target)));
if (ndo->ndo_vflag) {
#define NDSOLLEN 24
icmp6_opt_print(ndo, (const u_char *)dp + NDSOLLEN,
length - NDSOLLEN);
}
}
break;
case ND_NEIGHBOR_ADVERT:
{
const struct nd_neighbor_advert *p;
p = (const struct nd_neighbor_advert *)dp;
ND_TCHECK(p->nd_na_target);
ND_PRINT((ndo,", tgt is %s",
ip6addr_string(ndo, &p->nd_na_target)));
if (ndo->ndo_vflag) {
ND_PRINT((ndo,", Flags [%s]",
bittok2str(icmp6_nd_na_flag_values,
"none",
EXTRACT_32BITS(&p->nd_na_flags_reserved))));
#define NDADVLEN 24
icmp6_opt_print(ndo, (const u_char *)dp + NDADVLEN,
length - NDADVLEN);
#undef NDADVLEN
}
}
break;
case ND_REDIRECT:
#define RDR(i) ((const struct nd_redirect *)(i))
ND_TCHECK(RDR(dp)->nd_rd_dst);
ND_PRINT((ndo,", %s", ip6addr_string(ndo, &RDR(dp)->nd_rd_dst)));
ND_TCHECK(RDR(dp)->nd_rd_target);
ND_PRINT((ndo," to %s",
ip6addr_string(ndo, &RDR(dp)->nd_rd_target)));
#define REDIRECTLEN 40
if (ndo->ndo_vflag) {
icmp6_opt_print(ndo, (const u_char *)dp + REDIRECTLEN,
length - REDIRECTLEN);
}
break;
#undef REDIRECTLEN
#undef RDR
case ICMP6_ROUTER_RENUMBERING:
icmp6_rrenum_print(ndo, bp, ep);
break;
case ICMP6_NI_QUERY:
case ICMP6_NI_REPLY:
icmp6_nodeinfo_print(ndo, length, bp, ep);
break;
case IND_SOLICIT:
case IND_ADVERT:
break;
case ICMP6_V2_MEMBERSHIP_REPORT:
mldv2_report_print(ndo, (const u_char *) dp, length);
break;
case ICMP6_MOBILEPREFIX_SOLICIT: /* fall through */
case ICMP6_HADISCOV_REQUEST:
ND_TCHECK(dp->icmp6_data16[0]);
ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0])));
break;
case ICMP6_HADISCOV_REPLY:
if (ndo->ndo_vflag) {
const struct in6_addr *in6;
const u_char *cp;
ND_TCHECK(dp->icmp6_data16[0]);
ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0])));
cp = (const u_char *)dp + length;
in6 = (const struct in6_addr *)(dp + 1);
for (; (const u_char *)in6 < cp; in6++) {
ND_TCHECK(*in6);
ND_PRINT((ndo,", %s", ip6addr_string(ndo, in6)));
}
}
break;
case ICMP6_MOBILEPREFIX_ADVERT:
if (ndo->ndo_vflag) {
ND_TCHECK(dp->icmp6_data16[0]);
ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0])));
ND_TCHECK(dp->icmp6_data16[1]);
if (dp->icmp6_data16[1] & 0xc0)
ND_PRINT((ndo," "));
if (dp->icmp6_data16[1] & 0x80)
ND_PRINT((ndo,"M"));
if (dp->icmp6_data16[1] & 0x40)
ND_PRINT((ndo,"O"));
#define MPADVLEN 8
icmp6_opt_print(ndo, (const u_char *)dp + MPADVLEN,
length - MPADVLEN);
}
break;
case ND_RPL_MESSAGE:
/* plus 4, because struct icmp6_hdr contains 4 bytes of icmp payload */
rpl_print(ndo, dp, &dp->icmp6_data8[0], length-sizeof(struct icmp6_hdr)+4);
break;
default:
ND_PRINT((ndo,", length %u", length));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, bp,"\n\t", length);
return;
}
if (!ndo->ndo_vflag)
ND_PRINT((ndo,", length %u", length));
return;
trunc:
ND_PRINT((ndo, "[|icmp6]"));
}
static const struct udphdr *
get_upperlayer(netdissect_options *ndo, const u_char *bp, u_int *prot)
{
const u_char *ep;
const struct ip6_hdr *ip6 = (const struct ip6_hdr *)bp;
const struct udphdr *uh;
const struct ip6_hbh *hbh;
const struct ip6_frag *fragh;
const struct ah *ah;
u_int nh;
int hlen;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if (!ND_TTEST(ip6->ip6_nxt))
return NULL;
nh = ip6->ip6_nxt;
hlen = sizeof(struct ip6_hdr);
while (bp < ep) {
bp += hlen;
switch(nh) {
case IPPROTO_UDP:
case IPPROTO_TCP:
uh = (const struct udphdr *)bp;
if (ND_TTEST(uh->uh_dport)) {
*prot = nh;
return(uh);
}
else
return(NULL);
/* NOTREACHED */
case IPPROTO_HOPOPTS:
case IPPROTO_DSTOPTS:
case IPPROTO_ROUTING:
hbh = (const struct ip6_hbh *)bp;
if (!ND_TTEST(hbh->ip6h_len))
return(NULL);
nh = hbh->ip6h_nxt;
hlen = (hbh->ip6h_len + 1) << 3;
break;
case IPPROTO_FRAGMENT: /* this should be odd, but try anyway */
fragh = (const struct ip6_frag *)bp;
if (!ND_TTEST(fragh->ip6f_offlg))
return(NULL);
/* fragments with non-zero offset are meaningless */
if ((EXTRACT_16BITS(&fragh->ip6f_offlg) & IP6F_OFF_MASK) != 0)
return(NULL);
nh = fragh->ip6f_nxt;
hlen = sizeof(struct ip6_frag);
break;
case IPPROTO_AH:
ah = (const struct ah *)bp;
if (!ND_TTEST(ah->ah_len))
return(NULL);
nh = ah->ah_nxt;
hlen = (ah->ah_len + 2) << 2;
break;
default: /* unknown or undecodable header */
*prot = nh; /* meaningless, but set here anyway */
return(NULL);
}
}
return(NULL); /* should be notreached, though */
}
static void
icmp6_opt_print(netdissect_options *ndo, const u_char *bp, int resid)
{
const struct nd_opt_hdr *op;
const struct nd_opt_prefix_info *opp;
const struct nd_opt_mtu *opm;
const struct nd_opt_rdnss *oprd;
const struct nd_opt_dnssl *opds;
const struct nd_opt_advinterval *opa;
const struct nd_opt_homeagent_info *oph;
const struct nd_opt_route_info *opri;
const u_char *cp, *ep, *domp;
struct in6_addr in6;
const struct in6_addr *in6p;
size_t l;
u_int i;
#define ECHECK(var) if ((const u_char *)&(var) > ep - sizeof(var)) return
cp = bp;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
while (cp < ep) {
op = (const struct nd_opt_hdr *)cp;
ECHECK(op->nd_opt_len);
if (resid <= 0)
return;
if (op->nd_opt_len == 0)
goto trunc;
if (cp + (op->nd_opt_len << 3) > ep)
goto trunc;
ND_PRINT((ndo,"\n\t %s option (%u), length %u (%u): ",
tok2str(icmp6_opt_values, "unknown", op->nd_opt_type),
op->nd_opt_type,
op->nd_opt_len << 3,
op->nd_opt_len));
switch (op->nd_opt_type) {
case ND_OPT_SOURCE_LINKADDR:
l = (op->nd_opt_len << 3) - 2;
print_lladdr(ndo, cp + 2, l);
break;
case ND_OPT_TARGET_LINKADDR:
l = (op->nd_opt_len << 3) - 2;
print_lladdr(ndo, cp + 2, l);
break;
case ND_OPT_PREFIX_INFORMATION:
opp = (const struct nd_opt_prefix_info *)op;
ND_TCHECK(opp->nd_opt_pi_prefix);
ND_PRINT((ndo,"%s/%u%s, Flags [%s], valid time %s",
ip6addr_string(ndo, &opp->nd_opt_pi_prefix),
opp->nd_opt_pi_prefix_len,
(op->nd_opt_len != 4) ? "badlen" : "",
bittok2str(icmp6_opt_pi_flag_values, "none", opp->nd_opt_pi_flags_reserved),
get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_valid_time))));
ND_PRINT((ndo,", pref. time %s", get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_preferred_time))));
break;
case ND_OPT_REDIRECTED_HEADER:
print_unknown_data(ndo, bp,"\n\t ",op->nd_opt_len<<3);
/* xxx */
break;
case ND_OPT_MTU:
opm = (const struct nd_opt_mtu *)op;
ND_TCHECK(opm->nd_opt_mtu_mtu);
ND_PRINT((ndo," %u%s",
EXTRACT_32BITS(&opm->nd_opt_mtu_mtu),
(op->nd_opt_len != 1) ? "bad option length" : "" ));
break;
case ND_OPT_RDNSS:
oprd = (const struct nd_opt_rdnss *)op;
l = (op->nd_opt_len - 1) / 2;
ND_PRINT((ndo," lifetime %us,",
EXTRACT_32BITS(&oprd->nd_opt_rdnss_lifetime)));
for (i = 0; i < l; i++) {
ND_TCHECK(oprd->nd_opt_rdnss_addr[i]);
ND_PRINT((ndo," addr: %s",
ip6addr_string(ndo, &oprd->nd_opt_rdnss_addr[i])));
}
break;
case ND_OPT_DNSSL:
opds = (const struct nd_opt_dnssl *)op;
ND_PRINT((ndo," lifetime %us, domain(s):",
EXTRACT_32BITS(&opds->nd_opt_dnssl_lifetime)));
domp = cp + 8; /* domain names, variable-sized, RFC1035-encoded */
while (domp < cp + (op->nd_opt_len << 3) && *domp != '\0')
{
ND_PRINT((ndo, " "));
if ((domp = ns_nprint (ndo, domp, bp)) == NULL)
goto trunc;
}
break;
case ND_OPT_ADVINTERVAL:
opa = (const struct nd_opt_advinterval *)op;
ND_TCHECK(opa->nd_opt_adv_interval);
ND_PRINT((ndo," %ums", EXTRACT_32BITS(&opa->nd_opt_adv_interval)));
break;
case ND_OPT_HOMEAGENT_INFO:
oph = (const struct nd_opt_homeagent_info *)op;
ND_TCHECK(oph->nd_opt_hai_lifetime);
ND_PRINT((ndo," preference %u, lifetime %u",
EXTRACT_16BITS(&oph->nd_opt_hai_preference),
EXTRACT_16BITS(&oph->nd_opt_hai_lifetime)));
break;
case ND_OPT_ROUTE_INFO:
opri = (const struct nd_opt_route_info *)op;
ND_TCHECK(opri->nd_opt_rti_lifetime);
memset(&in6, 0, sizeof(in6));
in6p = (const struct in6_addr *)(opri + 1);
switch (op->nd_opt_len) {
case 1:
break;
case 2:
ND_TCHECK2(*in6p, 8);
memcpy(&in6, opri + 1, 8);
break;
case 3:
ND_TCHECK(*in6p);
memcpy(&in6, opri + 1, sizeof(in6));
break;
default:
goto trunc;
}
ND_PRINT((ndo," %s/%u", ip6addr_string(ndo, &in6),
opri->nd_opt_rti_prefixlen));
ND_PRINT((ndo,", pref=%s", get_rtpref(opri->nd_opt_rti_flags)));
ND_PRINT((ndo,", lifetime=%s",
get_lifetime(EXTRACT_32BITS(&opri->nd_opt_rti_lifetime))));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo,cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */
return;
}
break;
}
/* do we want to see an additional hexdump ? */
if (ndo->ndo_vflag> 1)
print_unknown_data(ndo, cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */
cp += op->nd_opt_len << 3;
resid -= op->nd_opt_len << 3;
}
return;
trunc:
ND_PRINT((ndo, "[ndp opt]"));
return;
#undef ECHECK
}
static void
mld6_print(netdissect_options *ndo, const u_char *bp)
{
const struct mld6_hdr *mp = (const struct mld6_hdr *)bp;
const u_char *ep;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if ((const u_char *)mp + sizeof(*mp) > ep)
return;
ND_PRINT((ndo,"max resp delay: %d ", EXTRACT_16BITS(&mp->mld6_maxdelay)));
ND_PRINT((ndo,"addr: %s", ip6addr_string(ndo, &mp->mld6_addr)));
}
static void
mldv2_report_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int group, nsrcs, ngroups;
u_int i, j;
/* Minimum len is 8 */
if (len < 8) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[1]);
ngroups = EXTRACT_16BITS(&icp->icmp6_data16[1]);
ND_PRINT((ndo,", %d group record(s)", ngroups));
if (ndo->ndo_vflag > 0) {
/* Print the group records */
group = 8;
for (i = 0; i < ngroups; i++) {
/* type(1) + auxlen(1) + numsrc(2) + grp(16) */
if (len < group + 20) {
ND_PRINT((ndo," [invalid number of groups]"));
return;
}
ND_TCHECK2(bp[group + 4], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[group + 4])));
ND_PRINT((ndo," %s", tok2str(mldv2report2str, " [v2-report-#%d]",
bp[group])));
nsrcs = (bp[group + 2] << 8) + bp[group + 3];
/* Check the number of sources and print them */
if (len < group + 20 + (nsrcs * sizeof(struct in6_addr))) {
ND_PRINT((ndo," [invalid number of sources %d]", nsrcs));
return;
}
if (ndo->ndo_vflag == 1)
ND_PRINT((ndo,", %d source(s)", nsrcs));
else {
/* Print the sources */
ND_PRINT((ndo," {"));
for (j = 0; j < nsrcs; j++) {
ND_TCHECK2(bp[group + 20 + j * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[group + 20 + j * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
}
/* Next group record */
group += 20 + nsrcs * sizeof(struct in6_addr);
ND_PRINT((ndo,"]"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
return;
}
static void
mldv2_query_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int mrc;
int mrt, qqi;
u_int nsrcs;
register u_int i;
/* Minimum len is 28 */
if (len < 28) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[0]);
mrc = EXTRACT_16BITS(&icp->icmp6_data16[0]);
if (mrc < 32768) {
mrt = mrc;
} else {
mrt = ((mrc & 0x0fff) | 0x1000) << (((mrc & 0x7000) >> 12) + 3);
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo," [max resp delay=%d]", mrt));
}
ND_TCHECK2(bp[8], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[8])));
if (ndo->ndo_vflag) {
ND_TCHECK(bp[25]);
if (bp[24] & 0x08) {
ND_PRINT((ndo," sflag"));
}
if (bp[24] & 0x07) {
ND_PRINT((ndo," robustness=%d", bp[24] & 0x07));
}
if (bp[25] < 128) {
qqi = bp[25];
} else {
qqi = ((bp[25] & 0x0f) | 0x10) << (((bp[25] & 0x70) >> 4) + 3);
}
ND_PRINT((ndo," qqi=%d", qqi));
}
ND_TCHECK2(bp[26], 2);
nsrcs = EXTRACT_16BITS(&bp[26]);
if (nsrcs > 0) {
if (len < 28 + nsrcs * sizeof(struct in6_addr))
ND_PRINT((ndo," [invalid number of sources]"));
else if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo," {"));
for (i = 0; i < nsrcs; i++) {
ND_TCHECK2(bp[28 + i * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[28 + i * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
} else
ND_PRINT((ndo,", %d source(s)", nsrcs));
}
ND_PRINT((ndo,"]"));
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
return;
}
static void
dnsname_print(netdissect_options *ndo, const u_char *cp, const u_char *ep)
{
int i;
/* DNS name decoding - no decompression */
ND_PRINT((ndo,", \""));
while (cp < ep) {
i = *cp++;
if (i) {
if (i > ep - cp) {
ND_PRINT((ndo,"???"));
break;
}
while (i-- && cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
if (cp + 1 < ep && *cp)
ND_PRINT((ndo,"."));
} else {
if (cp == ep) {
/* FQDN */
ND_PRINT((ndo,"."));
} else if (cp + 1 == ep && *cp == '\0') {
/* truncated */
} else {
/* invalid */
ND_PRINT((ndo,"???"));
}
break;
}
}
ND_PRINT((ndo,"\""));
}
static void
icmp6_nodeinfo_print(netdissect_options *ndo, u_int icmp6len, const u_char *bp, const u_char *ep)
{
const struct icmp6_nodeinfo *ni6;
const struct icmp6_hdr *dp;
const u_char *cp;
size_t siz, i;
int needcomma;
if (ep < bp)
return;
dp = (const struct icmp6_hdr *)bp;
ni6 = (const struct icmp6_nodeinfo *)bp;
siz = ep - bp;
switch (ni6->ni_type) {
case ICMP6_NI_QUERY:
if (siz == sizeof(*dp) + 4) {
/* KAME who-are-you */
ND_PRINT((ndo," who-are-you request"));
break;
}
ND_PRINT((ndo," node information query"));
ND_TCHECK2(*dp, sizeof(*ni6));
ni6 = (const struct icmp6_nodeinfo *)dp;
ND_PRINT((ndo," (")); /*)*/
switch (EXTRACT_16BITS(&ni6->ni_qtype)) {
case NI_QTYPE_NOOP:
ND_PRINT((ndo,"noop"));
break;
case NI_QTYPE_SUPTYPES:
ND_PRINT((ndo,"supported qtypes"));
i = EXTRACT_16BITS(&ni6->ni_flags);
if (i)
ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : ""));
break;
case NI_QTYPE_FQDN:
ND_PRINT((ndo,"DNS name"));
break;
case NI_QTYPE_NODEADDR:
ND_PRINT((ndo,"node addresses"));
i = ni6->ni_flags;
if (!i)
break;
/* NI_NODEADDR_FLAG_TRUNCATE undefined for query */
ND_PRINT((ndo," [%s%s%s%s%s%s]",
(i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "",
(i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "",
(i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "",
(i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "",
(i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "",
(i & NI_NODEADDR_FLAG_ALL) ? "A" : ""));
break;
default:
ND_PRINT((ndo,"unknown"));
break;
}
if (ni6->ni_qtype == NI_QTYPE_NOOP ||
ni6->ni_qtype == NI_QTYPE_SUPTYPES) {
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid len"));
/*(*/
ND_PRINT((ndo,")"));
break;
}
/* XXX backward compat, icmp-name-lookup-03 */
if (siz == sizeof(*ni6)) {
ND_PRINT((ndo,", 03 draft"));
/*(*/
ND_PRINT((ndo,")"));
break;
}
switch (ni6->ni_code) {
case ICMP6_NI_SUBJ_IPV6:
if (!ND_TTEST2(*dp,
sizeof(*ni6) + sizeof(struct in6_addr)))
break;
if (siz != sizeof(*ni6) + sizeof(struct in6_addr)) {
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid subject len"));
break;
}
ND_PRINT((ndo,", subject=%s",
ip6addr_string(ndo, ni6 + 1)));
break;
case ICMP6_NI_SUBJ_FQDN:
ND_PRINT((ndo,", subject=DNS name"));
cp = (const u_char *)(ni6 + 1);
if (cp[0] == ep - cp - 1) {
/* icmp-name-lookup-03, pascal string */
if (ndo->ndo_vflag)
ND_PRINT((ndo,", 03 draft"));
cp++;
ND_PRINT((ndo,", \""));
while (cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
ND_PRINT((ndo,"\""));
} else
dnsname_print(ndo, cp, ep);
break;
case ICMP6_NI_SUBJ_IPV4:
if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in_addr)))
break;
if (siz != sizeof(*ni6) + sizeof(struct in_addr)) {
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid subject len"));
break;
}
ND_PRINT((ndo,", subject=%s",
ipaddr_string(ndo, ni6 + 1)));
break;
default:
ND_PRINT((ndo,", unknown subject"));
break;
}
/*(*/
ND_PRINT((ndo,")"));
break;
case ICMP6_NI_REPLY:
if (icmp6len > siz) {
ND_PRINT((ndo,"[|icmp6: node information reply]"));
break;
}
needcomma = 0;
ND_TCHECK2(*dp, sizeof(*ni6));
ni6 = (const struct icmp6_nodeinfo *)dp;
ND_PRINT((ndo," node information reply"));
ND_PRINT((ndo," (")); /*)*/
switch (ni6->ni_code) {
case ICMP6_NI_SUCCESS:
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"success"));
needcomma++;
}
break;
case ICMP6_NI_REFUSED:
ND_PRINT((ndo,"refused"));
needcomma++;
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
case ICMP6_NI_UNKNOWN:
ND_PRINT((ndo,"unknown"));
needcomma++;
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
}
if (ni6->ni_code != ICMP6_NI_SUCCESS) {
/*(*/
ND_PRINT((ndo,")"));
break;
}
switch (EXTRACT_16BITS(&ni6->ni_qtype)) {
case NI_QTYPE_NOOP:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"noop"));
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
case NI_QTYPE_SUPTYPES:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"supported qtypes"));
i = EXTRACT_16BITS(&ni6->ni_flags);
if (i)
ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : ""));
break;
case NI_QTYPE_FQDN:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"DNS name"));
cp = (const u_char *)(ni6 + 1) + 4;
ND_TCHECK(cp[0]);
if (cp[0] == ep - cp - 1) {
/* icmp-name-lookup-03, pascal string */
if (ndo->ndo_vflag)
ND_PRINT((ndo,", 03 draft"));
cp++;
ND_PRINT((ndo,", \""));
while (cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
ND_PRINT((ndo,"\""));
} else
dnsname_print(ndo, cp, ep);
if ((EXTRACT_16BITS(&ni6->ni_flags) & 0x01) != 0)
ND_PRINT((ndo," [TTL=%u]", EXTRACT_32BITS(ni6 + 1)));
break;
case NI_QTYPE_NODEADDR:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"node addresses"));
i = sizeof(*ni6);
while (i < siz) {
if (i + sizeof(struct in6_addr) + sizeof(int32_t) > siz)
break;
ND_PRINT((ndo," %s", ip6addr_string(ndo, bp + i)));
i += sizeof(struct in6_addr);
ND_PRINT((ndo,"(%d)", (int32_t)EXTRACT_32BITS(bp + i)));
i += sizeof(int32_t);
}
i = ni6->ni_flags;
if (!i)
break;
ND_PRINT((ndo," [%s%s%s%s%s%s%s]",
(i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "",
(i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "",
(i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "",
(i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "",
(i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "",
(i & NI_NODEADDR_FLAG_ALL) ? "A" : "",
(i & NI_NODEADDR_FLAG_TRUNCATE) ? "T" : ""));
break;
default:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"unknown"));
break;
}
/*(*/
ND_PRINT((ndo,")"));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|icmp6]"));
}
static void
icmp6_rrenum_print(netdissect_options *ndo, const u_char *bp, const u_char *ep)
{
const struct icmp6_router_renum *rr6;
const char *cp;
const struct rr_pco_match *match;
const struct rr_pco_use *use;
char hbuf[NI_MAXHOST];
int n;
if (ep < bp)
return;
rr6 = (const struct icmp6_router_renum *)bp;
cp = (const char *)(rr6 + 1);
ND_TCHECK(rr6->rr_reserved);
switch (rr6->rr_code) {
case ICMP6_ROUTER_RENUMBERING_COMMAND:
ND_PRINT((ndo,"router renum: command"));
break;
case ICMP6_ROUTER_RENUMBERING_RESULT:
ND_PRINT((ndo,"router renum: result"));
break;
case ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET:
ND_PRINT((ndo,"router renum: sequence number reset"));
break;
default:
ND_PRINT((ndo,"router renum: code-#%d", rr6->rr_code));
break;
}
ND_PRINT((ndo,", seq=%u", EXTRACT_32BITS(&rr6->rr_seqnum)));
if (ndo->ndo_vflag) {
#define F(x, y) ((rr6->rr_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"[")); /*]*/
if (rr6->rr_flags) {
ND_PRINT((ndo,"%s%s%s%s%s,", F(ICMP6_RR_FLAGS_TEST, "T"),
F(ICMP6_RR_FLAGS_REQRESULT, "R"),
F(ICMP6_RR_FLAGS_FORCEAPPLY, "A"),
F(ICMP6_RR_FLAGS_SPECSITE, "S"),
F(ICMP6_RR_FLAGS_PREVDONE, "P")));
}
ND_PRINT((ndo,"seg=%u,", rr6->rr_segnum));
ND_PRINT((ndo,"maxdelay=%u", EXTRACT_16BITS(&rr6->rr_maxdelay)));
if (rr6->rr_reserved)
ND_PRINT((ndo,"rsvd=0x%x", EXTRACT_32BITS(&rr6->rr_reserved)));
/*[*/
ND_PRINT((ndo,"]"));
#undef F
}
if (rr6->rr_code == ICMP6_ROUTER_RENUMBERING_COMMAND) {
match = (const struct rr_pco_match *)cp;
cp = (const char *)(match + 1);
ND_TCHECK(match->rpm_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"match(")); /*)*/
switch (match->rpm_code) {
case RPM_PCO_ADD: ND_PRINT((ndo,"add")); break;
case RPM_PCO_CHANGE: ND_PRINT((ndo,"change")); break;
case RPM_PCO_SETGLOBAL: ND_PRINT((ndo,"setglobal")); break;
default: ND_PRINT((ndo,"#%u", match->rpm_code)); break;
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,",ord=%u", match->rpm_ordinal));
ND_PRINT((ndo,",min=%u", match->rpm_minlen));
ND_PRINT((ndo,",max=%u", match->rpm_maxlen));
}
if (addrtostr6(&match->rpm_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,",%s/%u", hbuf, match->rpm_matchlen));
else
ND_PRINT((ndo,",?/%u", match->rpm_matchlen));
/*(*/
ND_PRINT((ndo,")"));
n = match->rpm_len - 3;
if (n % 4)
goto trunc;
n /= 4;
while (n-- > 0) {
use = (const struct rr_pco_use *)cp;
cp = (const char *)(use + 1);
ND_TCHECK(use->rpu_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"use(")); /*)*/
if (use->rpu_flags) {
#define F(x, y) ((use->rpu_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"%s%s,",
F(ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME, "V"),
F(ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME, "P")));
#undef F
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"mask=0x%x,", use->rpu_ramask));
ND_PRINT((ndo,"raflags=0x%x,", use->rpu_raflags));
if (~use->rpu_vltime == 0)
ND_PRINT((ndo,"vltime=infty,"));
else
ND_PRINT((ndo,"vltime=%u,",
EXTRACT_32BITS(&use->rpu_vltime)));
if (~use->rpu_pltime == 0)
ND_PRINT((ndo,"pltime=infty,"));
else
ND_PRINT((ndo,"pltime=%u,",
EXTRACT_32BITS(&use->rpu_pltime)));
}
if (addrtostr6(&use->rpu_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,"%s/%u/%u", hbuf, use->rpu_uselen,
use->rpu_keeplen));
else
ND_PRINT((ndo,"?/%u/%u", use->rpu_uselen,
use->rpu_keeplen));
/*(*/
ND_PRINT((ndo,")"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2717_0 |
crossvul-cpp_data_bad_5870_0 | /*
* Filtered Image Rescaling
* Based on Gems III
* - Schumacher general filtered image rescaling
* (pp. 414-424)
* by Dale Schumacher
*
* Additional changes by Ray Gardener, Daylon Graphics Ltd.
* December 4, 1999
*
* Ported to libgd by Pierre Joye. Support for multiple channels
* added (argb for now).
*
* Initial sources code is avaibable in the Gems Source Code Packages:
* http://www.acm.org/pubs/tog/GraphicsGems/GGemsIII.tar.gz
*/
/*
Summary:
- Horizontal filter contributions are calculated on the fly,
as each column is mapped from src to dst image. This lets
us omit having to allocate a temporary full horizontal stretch
of the src image.
- If none of the src pixels within a sampling region differ,
then the output pixel is forced to equal (any of) the source pixel.
This ensures that filters do not corrupt areas of constant color.
- Filter weight contribution results, after summing, are
rounded to the nearest pixel color value instead of
being casted to ILubyte (usually an int or char). Otherwise,
artifacting occurs.
*/
/*
Additional functions are available for simple rotation or up/downscaling.
downscaling using the fixed point implementations are usually much faster
than the existing gdImageCopyResampled while having a similar or better
quality.
For image rotations, the optimized versions have a lazy antialiasing for
the edges of the images. For a much better antialiased result, the affine
function is recommended.
*/
/*
TODO:
- Optimize pixel accesses and loops once we have continuous buffer
- Add scale support for a portion only of an image (equivalent of copyresized/resampled)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gd.h>
#include "gdhelpers.h"
#ifdef _MSC_VER
# pragma optimize("t", on)
# include <emmintrin.h>
#endif
#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#define MIN3(a,b,c) ((a)<(b)?(MIN(a,c)):(MIN(b,c)))
#ifndef MAX
#define MAX(a,b) ((a)<(b)?(b):(a))
#endif
#define MAX3(a,b,c) ((a)<(b)?(MAX(b,c)):(MAX(a,c)))
#define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))
/* only used here, let do a generic fixed point integers later if required by other
part of GD */
typedef long gdFixed;
/* Integer to fixed point */
#define gd_itofx(x) ((x) << 8)
/* Float to fixed point */
#define gd_ftofx(x) (long)((x) * 256)
/* Double to fixed point */
#define gd_dtofx(x) (long)((x) * 256)
/* Fixed point to integer */
#define gd_fxtoi(x) ((x) >> 8)
/* Fixed point to float */
# define gd_fxtof(x) ((float)(x) / 256)
/* Fixed point to double */
#define gd_fxtod(x) ((double)(x) / 256)
/* Multiply a fixed by a fixed */
#define gd_mulfx(x,y) (((x) * (y)) >> 8)
/* Divide a fixed by a fixed */
#define gd_divfx(x,y) (((x) << 8) / (y))
typedef struct
{
double *Weights; /* Normalized weights of neighboring pixels */
int Left,Right; /* Bounds of source pixels window */
} ContributionType; /* Contirbution information for a single pixel */
typedef struct
{
ContributionType *ContribRow; /* Row (or column) of contribution weights */
unsigned int WindowSize, /* Filter window size (of affecting source pixels) */
LineLength; /* Length of line (no. or rows / cols) */
} LineContribType;
/* Each core filter has its own radius */
#define DEFAULT_FILTER_BICUBIC 3.0
#define DEFAULT_FILTER_BOX 0.5
#define DEFAULT_FILTER_GENERALIZED_CUBIC 0.5
#define DEFAULT_FILTER_RADIUS 1.0
#define DEFAULT_LANCZOS8_RADIUS 8.0
#define DEFAULT_LANCZOS3_RADIUS 3.0
#define DEFAULT_HERMITE_RADIUS 1.0
#define DEFAULT_BOX_RADIUS 0.5
#define DEFAULT_TRIANGLE_RADIUS 1.0
#define DEFAULT_BELL_RADIUS 1.5
#define DEFAULT_CUBICSPLINE_RADIUS 2.0
#define DEFAULT_MITCHELL_RADIUS 2.0
#define DEFAULT_COSINE_RADIUS 1.0
#define DEFAULT_CATMULLROM_RADIUS 2.0
#define DEFAULT_QUADRATIC_RADIUS 1.5
#define DEFAULT_QUADRATICBSPLINE_RADIUS 1.5
#define DEFAULT_CUBICCONVOLUTION_RADIUS 3.0
#define DEFAULT_GAUSSIAN_RADIUS 1.0
#define DEFAULT_HANNING_RADIUS 1.0
#define DEFAULT_HAMMING_RADIUS 1.0
#define DEFAULT_SINC_RADIUS 1.0
#define DEFAULT_WELSH_RADIUS 1.0
enum GD_RESIZE_FILTER_TYPE{
FILTER_DEFAULT = 0,
FILTER_BELL,
FILTER_BESSEL,
FILTER_BLACKMAN,
FILTER_BOX,
FILTER_BSPLINE,
FILTER_CATMULLROM,
FILTER_COSINE,
FILTER_CUBICCONVOLUTION,
FILTER_CUBICSPLINE,
FILTER_HERMITE,
FILTER_LANCZOS3,
FILTER_LANCZOS8,
FILTER_MITCHELL,
FILTER_QUADRATIC,
FILTER_QUADRATICBSPLINE,
FILTER_TRIANGLE,
FILTER_GAUSSIAN,
FILTER_HANNING,
FILTER_HAMMING,
FILTER_SINC,
FILTER_WELSH,
FILTER_CALLBACK = 999
};
typedef enum GD_RESIZE_FILTER_TYPE gdResizeFilterType;
static double KernelBessel_J1(const double x)
{
double p, q;
register long i;
static const double
Pone[] =
{
0.581199354001606143928050809e+21,
-0.6672106568924916298020941484e+20,
0.2316433580634002297931815435e+19,
-0.3588817569910106050743641413e+17,
0.2908795263834775409737601689e+15,
-0.1322983480332126453125473247e+13,
0.3413234182301700539091292655e+10,
-0.4695753530642995859767162166e+7,
0.270112271089232341485679099e+4
},
Qone[] =
{
0.11623987080032122878585294e+22,
0.1185770712190320999837113348e+20,
0.6092061398917521746105196863e+17,
0.2081661221307607351240184229e+15,
0.5243710262167649715406728642e+12,
0.1013863514358673989967045588e+10,
0.1501793594998585505921097578e+7,
0.1606931573481487801970916749e+4,
0.1e+1
};
p = Pone[8];
q = Qone[8];
for (i=7; i >= 0; i--)
{
p = p*x*x+Pone[i];
q = q*x*x+Qone[i];
}
return (double)(p/q);
}
static double KernelBessel_P1(const double x)
{
double p, q;
register long i;
static const double
Pone[] =
{
0.352246649133679798341724373e+5,
0.62758845247161281269005675e+5,
0.313539631109159574238669888e+5,
0.49854832060594338434500455e+4,
0.2111529182853962382105718e+3,
0.12571716929145341558495e+1
},
Qone[] =
{
0.352246649133679798068390431e+5,
0.626943469593560511888833731e+5,
0.312404063819041039923015703e+5,
0.4930396490181088979386097e+4,
0.2030775189134759322293574e+3,
0.1e+1
};
p = Pone[5];
q = Qone[5];
for (i=4; i >= 0; i--)
{
p = p*(8.0/x)*(8.0/x)+Pone[i];
q = q*(8.0/x)*(8.0/x)+Qone[i];
}
return (double)(p/q);
}
static double KernelBessel_Q1(const double x)
{
double p, q;
register long i;
static const double
Pone[] =
{
0.3511751914303552822533318e+3,
0.7210391804904475039280863e+3,
0.4259873011654442389886993e+3,
0.831898957673850827325226e+2,
0.45681716295512267064405e+1,
0.3532840052740123642735e-1
},
Qone[] =
{
0.74917374171809127714519505e+4,
0.154141773392650970499848051e+5,
0.91522317015169922705904727e+4,
0.18111867005523513506724158e+4,
0.1038187585462133728776636e+3,
0.1e+1
};
p = Pone[5];
q = Qone[5];
for (i=4; i >= 0; i--)
{
p = p*(8.0/x)*(8.0/x)+Pone[i];
q = q*(8.0/x)*(8.0/x)+Qone[i];
}
return (double)(p/q);
}
static double KernelBessel_Order1(double x)
{
double p, q;
if (x == 0.0)
return (0.0f);
p = x;
if (x < 0.0)
x=(-x);
if (x < 8.0)
return (p*KernelBessel_J1(x));
q = (double)sqrt(2.0f/(M_PI*x))*(double)(KernelBessel_P1(x)*(1.0f/sqrt(2.0f)*(sin(x)-cos(x)))-8.0f/x*KernelBessel_Q1(x)*
(-1.0f/sqrt(2.0f)*(sin(x)+cos(x))));
if (p < 0.0f)
q = (-q);
return (q);
}
static double filter_bessel(const double x)
{
if (x == 0.0f)
return (double)(M_PI/4.0f);
return (KernelBessel_Order1((double)M_PI*x)/(2.0f*x));
}
static double filter_blackman(const double x)
{
return (0.42f+0.5f*(double)cos(M_PI*x)+0.08f*(double)cos(2.0f*M_PI*x));
}
/**
* Bicubic interpolation kernel (a=-1):
\verbatim
/
| 1-2|t|**2+|t|**3 , if |t| < 1
h(t) = | 4-8|t|+5|t|**2-|t|**3 , if 1<=|t|<2
| 0 , otherwise
\
\endverbatim
* ***bd*** 2.2004
*/
static double filter_bicubic(const double t)
{
const double abs_t = (double)fabs(t);
const double abs_t_sq = abs_t * abs_t;
if (abs_t<1) return 1-2*abs_t_sq+abs_t_sq*abs_t;
if (abs_t<2) return 4 - 8*abs_t +5*abs_t_sq - abs_t_sq*abs_t;
return 0;
}
/**
* Generalized cubic kernel (for a=-1 it is the same as BicubicKernel):
\verbatim
/
| (a+2)|t|**3 - (a+3)|t|**2 + 1 , |t| <= 1
h(t) = | a|t|**3 - 5a|t|**2 + 8a|t| - 4a , 1 < |t| <= 2
| 0 , otherwise
\
\endverbatim
* Often used values for a are -1 and -1/2.
*/
static double filter_generalized_cubic(const double t)
{
const double a = -DEFAULT_FILTER_GENERALIZED_CUBIC;
double abs_t = (double)fabs(t);
double abs_t_sq = abs_t * abs_t;
if (abs_t < 1) return (a + 2) * abs_t_sq * abs_t - (a + 3) * abs_t_sq + 1;
if (abs_t < 2) return a * abs_t_sq * abs_t - 5 * a * abs_t_sq + 8 * a * abs_t - 4 * a;
return 0;
}
/* CubicSpline filter, default radius 2 */
static double filter_cubic_spline(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 1.0 ) {
const double x2 = x*x;
return (0.5 * x2 * x - x2 + 2.0 / 3.0);
}
if (x < 2.0) {
return (pow(2.0 - x, 3.0)/6.0);
}
return 0;
}
/* CubicConvolution filter, default radius 3 */
static double filter_cubic_convolution(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
const double x2 = x1 * x1;
const double x2_x = x2 * x;
if (x <= 1.0) return ((4.0 / 3.0)* x2_x - (7.0 / 3.0) * x2 + 1.0);
if (x <= 2.0) return (- (7.0 / 12.0) * x2_x + 3 * x2 - (59.0 / 12.0) * x + 2.5);
if (x <= 3.0) return ( (1.0/12.0) * x2_x - (2.0 / 3.0) * x2 + 1.75 * x - 1.5);
return 0;
}
static double filter_box(double x) {
if (x < - DEFAULT_FILTER_BOX)
return 0.0f;
if (x < DEFAULT_FILTER_BOX)
return 1.0f;
return 0.0f;
}
static double filter_catmullrom(const double x)
{
if (x < -2.0)
return(0.0f);
if (x < -1.0)
return(0.5f*(4.0f+x*(8.0f+x*(5.0f+x))));
if (x < 0.0)
return(0.5f*(2.0f+x*x*(-5.0f-3.0f*x)));
if (x < 1.0)
return(0.5f*(2.0f+x*x*(-5.0f+3.0f*x)));
if (x < 2.0)
return(0.5f*(4.0f+x*(-8.0f+x*(5.0f-x))));
return(0.0f);
}
static double filter_filter(double t)
{
/* f(t) = 2|t|^3 - 3|t|^2 + 1, -1 <= t <= 1 */
if(t < 0.0) t = -t;
if(t < 1.0) return((2.0 * t - 3.0) * t * t + 1.0);
return(0.0);
}
/* Lanczos8 filter, default radius 8 */
static double filter_lanczos8(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
#define R DEFAULT_LANCZOS8_RADIUS
if ( x == 0.0) return 1;
if ( x < R) {
return R * sin(x*M_PI) * sin(x * M_PI/ R) / (x * M_PI * x * M_PI);
}
return 0.0;
#undef R
}
/* Lanczos3 filter, default radius 3 */
static double filter_lanczos3(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
#define R DEFAULT_LANCZOS3_RADIUS
if ( x == 0.0) return 1;
if ( x < R)
{
return R * sin(x*M_PI) * sin(x * M_PI / R) / (x * M_PI * x * M_PI);
}
return 0.0;
#undef R
}
/* Hermite filter, default radius 1 */
static double filter_hermite(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 1.0) return ((2.0 * x - 3) * x * x + 1.0 );
return 0.0;
}
/* Trangle filter, default radius 1 */
static double filter_triangle(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 1.0) return (1.0 - x);
return 0.0;
}
/* Bell filter, default radius 1.5 */
static double filter_bell(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 0.5) return (0.75 - x*x);
if (x < 1.5) return (0.5 * pow(x - 1.5, 2.0));
return 0.0;
}
/* Mitchell filter, default radius 2.0 */
static double filter_mitchell(const double x)
{
#define KM_B (1.0f/3.0f)
#define KM_C (1.0f/3.0f)
#define KM_P0 (( 6.0f - 2.0f * KM_B ) / 6.0f)
#define KM_P2 ((-18.0f + 12.0f * KM_B + 6.0f * KM_C) / 6.0f)
#define KM_P3 (( 12.0f - 9.0f * KM_B - 6.0f * KM_C) / 6.0f)
#define KM_Q0 (( 8.0f * KM_B + 24.0f * KM_C) / 6.0f)
#define KM_Q1 ((-12.0f * KM_B - 48.0f * KM_C) / 6.0f)
#define KM_Q2 (( 6.0f * KM_B + 30.0f * KM_C) / 6.0f)
#define KM_Q3 (( -1.0f * KM_B - 6.0f * KM_C) / 6.0f)
if (x < -2.0)
return(0.0f);
if (x < -1.0)
return(KM_Q0-x*(KM_Q1-x*(KM_Q2-x*KM_Q3)));
if (x < 0.0f)
return(KM_P0+x*x*(KM_P2-x*KM_P3));
if (x < 1.0f)
return(KM_P0+x*x*(KM_P2+x*KM_P3));
if (x < 2.0f)
return(KM_Q0+x*(KM_Q1+x*(KM_Q2+x*KM_Q3)));
return(0.0f);
}
/* Cosine filter, default radius 1 */
static double filter_cosine(const double x)
{
if ((x >= -1.0) && (x <= 1.0)) return ((cos(x * M_PI) + 1.0)/2.0);
return 0;
}
/* Quadratic filter, default radius 1.5 */
static double filter_quadratic(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x <= 0.5) return (- 2.0 * x * x + 1);
if (x <= 1.5) return (x * x - 2.5* x + 1.5);
return 0.0;
}
static double filter_bspline(const double x)
{
if (x>2.0f) {
return 0.0f;
} else {
double a, b, c, d;
/* Was calculated anyway cause the "if((x-1.0f) < 0)" */
const double xm1 = x - 1.0f;
const double xp1 = x + 1.0f;
const double xp2 = x + 2.0f;
if ((xp2) <= 0.0f) a = 0.0f; else a = xp2*xp2*xp2;
if ((xp1) <= 0.0f) b = 0.0f; else b = xp1*xp1*xp1;
if (x <= 0) c = 0.0f; else c = x*x*x;
if ((xm1) <= 0.0f) d = 0.0f; else d = xm1*xm1*xm1;
return (0.16666666666666666667f * (a - (4.0f * b) + (6.0f * c) - (4.0f * d)));
}
}
/* QuadraticBSpline filter, default radius 1.5 */
static double filter_quadratic_bspline(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x <= 0.5) return (- x * x + 0.75);
if (x <= 1.5) return (0.5 * x * x - 1.5 * x + 1.125);
return 0.0;
}
static double filter_gaussian(const double x)
{
/* return(exp((double) (-2.0 * x * x)) * sqrt(2.0 / M_PI)); */
return (double)(exp(-2.0f * x * x) * 0.79788456080287f);
}
static double filter_hanning(const double x)
{
/* A Cosine windowing function */
return(0.5 + 0.5 * cos(M_PI * x));
}
static double filter_hamming(const double x)
{
/* should be
(0.54+0.46*cos(M_PI*(double) x));
but this approximation is sufficient */
if (x < -1.0f)
return 0.0f;
if (x < 0.0f)
return 0.92f*(-2.0f*x-3.0f)*x*x+1.0f;
if (x < 1.0f)
return 0.92f*(2.0f*x-3.0f)*x*x+1.0f;
return 0.0f;
}
static double filter_power(const double x)
{
const double a = 2.0f;
if (fabs(x)>1) return 0.0f;
return (1.0f - (double)fabs(pow(x,a)));
}
static double filter_sinc(const double x)
{
/* X-scaled Sinc(x) function. */
if (x == 0.0) return(1.0);
return (sin(M_PI * (double) x) / (M_PI * (double) x));
}
static double filter_welsh(const double x)
{
/* Welsh parabolic windowing filter */
if (x < 1.0)
return(1 - x*x);
return(0.0);
}
/* Copied from upstream's libgd */
static inline int _color_blend (const int dst, const int src)
{
const int src_alpha = gdTrueColorGetAlpha(src);
if( src_alpha == gdAlphaOpaque ) {
return src;
} else {
const int dst_alpha = gdTrueColorGetAlpha(dst);
if( src_alpha == gdAlphaTransparent ) return dst;
if( dst_alpha == gdAlphaTransparent ) {
return src;
} else {
register int alpha, red, green, blue;
const int src_weight = gdAlphaTransparent - src_alpha;
const int dst_weight = (gdAlphaTransparent - dst_alpha) * src_alpha / gdAlphaMax;
const int tot_weight = src_weight + dst_weight;
alpha = src_alpha * dst_alpha / gdAlphaMax;
red = (gdTrueColorGetRed(src) * src_weight
+ gdTrueColorGetRed(dst) * dst_weight) / tot_weight;
green = (gdTrueColorGetGreen(src) * src_weight
+ gdTrueColorGetGreen(dst) * dst_weight) / tot_weight;
blue = (gdTrueColorGetBlue(src) * src_weight
+ gdTrueColorGetBlue(dst) * dst_weight) / tot_weight;
return ((alpha << 24) + (red << 16) + (green << 8) + blue);
}
}
}
static inline int _setEdgePixel(const gdImagePtr src, unsigned int x, unsigned int y, gdFixed coverage, const int bgColor)
{
const gdFixed f_127 = gd_itofx(127);
register int c = src->tpixels[y][x];
c = c | (( (int) (gd_fxtof(gd_mulfx(coverage, f_127)) + 50.5f)) << 24);
return _color_blend(bgColor, c);
}
static inline int getPixelOverflowTC(gdImagePtr im, const int x, const int y, const int bgColor)
{
if (gdImageBoundsSafe(im, x, y)) {
const int c = im->tpixels[y][x];
if (c == im->transparent) {
return bgColor == -1 ? gdTrueColorAlpha(0, 0, 0, 127) : bgColor;
}
return c;
} else {
register int border = 0;
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y > im->cy2) {
if (x >= im->cx1 && x <= im->cx1) {
border = im->tpixels[im->cy2][x];
goto processborder;
} else {
return gdTrueColorAlpha(0, 0, 0, 127);
}
}
/* y is bound safe at this point */
if (x < im->cx1) {
border = im->tpixels[y][im->cx1];
goto processborder;
}
if (x > im->cx2) {
border = im->tpixels[y][im->cx2];
}
processborder:
if (border == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
} else{
return gdTrueColorAlpha(gdTrueColorGetRed(border), gdTrueColorGetGreen(border), gdTrueColorGetBlue(border), 127);
}
}
}
#define colorIndex2RGBA(c) gdTrueColorAlpha(im->red[(c)], im->green[(c)], im->blue[(c)], im->alpha[(c)])
#define colorIndex2RGBcustomA(c, a) gdTrueColorAlpha(im->red[(c)], im->green[(c)], im->blue[(c)], im->alpha[(a)])
static inline int getPixelOverflowPalette(gdImagePtr im, const int x, const int y, const int bgColor)
{
if (gdImageBoundsSafe(im, x, y)) {
const int c = im->pixels[y][x];
if (c == im->transparent) {
return bgColor == -1 ? gdTrueColorAlpha(0, 0, 0, 127) : bgColor;
}
return colorIndex2RGBA(c);
} else {
register int border = 0;
if (y < im->cy1) {
border = gdImageGetPixel(im, im->cx1, 0);
goto processborder;
}
if (y < im->cy1) {
border = gdImageGetPixel(im, im->cx1, 0);
goto processborder;
}
if (y > im->cy2) {
if (x >= im->cx1 && x <= im->cx1) {
border = gdImageGetPixel(im, x, im->cy2);
goto processborder;
} else {
return gdTrueColorAlpha(0, 0, 0, 127);
}
}
/* y is bound safe at this point */
if (x < im->cx1) {
border = gdImageGetPixel(im, im->cx1, y);
goto processborder;
}
if (x > im->cx2) {
border = gdImageGetPixel(im, im->cx2, y);
}
processborder:
if (border == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
} else{
return colorIndex2RGBcustomA(border, 127);
}
}
}
static int getPixelInterpolateWeight(gdImagePtr im, const double x, const double y, const int bgColor)
{
/* Closest pixel <= (xf,yf) */
int sx = (int)(x);
int sy = (int)(y);
const double xf = x - (double)sx;
const double yf = y - (double)sy;
const double nxf = (double) 1.0 - xf;
const double nyf = (double) 1.0 - yf;
const double m1 = xf * yf;
const double m2 = nxf * yf;
const double m3 = xf * nyf;
const double m4 = nxf * nyf;
/* get color values of neighbouring pixels */
const int c1 = im->trueColor == 1 ? getPixelOverflowTC(im, sx, sy, bgColor) : getPixelOverflowPalette(im, sx, sy, bgColor);
const int c2 = im->trueColor == 1 ? getPixelOverflowTC(im, sx - 1, sy, bgColor) : getPixelOverflowPalette(im, sx - 1, sy, bgColor);
const int c3 = im->trueColor == 1 ? getPixelOverflowTC(im, sx, sy - 1, bgColor) : getPixelOverflowPalette(im, sx, sy - 1, bgColor);
const int c4 = im->trueColor == 1 ? getPixelOverflowTC(im, sx - 1, sy - 1, bgColor) : getPixelOverflowPalette(im, sx, sy - 1, bgColor);
int r, g, b, a;
if (x < 0) sx--;
if (y < 0) sy--;
/* component-wise summing-up of color values */
if (im->trueColor) {
r = (int)(m1*gdTrueColorGetRed(c1) + m2*gdTrueColorGetRed(c2) + m3*gdTrueColorGetRed(c3) + m4*gdTrueColorGetRed(c4));
g = (int)(m1*gdTrueColorGetGreen(c1) + m2*gdTrueColorGetGreen(c2) + m3*gdTrueColorGetGreen(c3) + m4*gdTrueColorGetGreen(c4));
b = (int)(m1*gdTrueColorGetBlue(c1) + m2*gdTrueColorGetBlue(c2) + m3*gdTrueColorGetBlue(c3) + m4*gdTrueColorGetBlue(c4));
a = (int)(m1*gdTrueColorGetAlpha(c1) + m2*gdTrueColorGetAlpha(c2) + m3*gdTrueColorGetAlpha(c3) + m4*gdTrueColorGetAlpha(c4));
} else {
r = (int)(m1*im->red[(c1)] + m2*im->red[(c2)] + m3*im->red[(c3)] + m4*im->red[(c4)]);
g = (int)(m1*im->green[(c1)] + m2*im->green[(c2)] + m3*im->green[(c3)] + m4*im->green[(c4)]);
b = (int)(m1*im->blue[(c1)] + m2*im->blue[(c2)] + m3*im->blue[(c3)] + m4*im->blue[(c4)]);
a = (int)(m1*im->alpha[(c1)] + m2*im->alpha[(c2)] + m3*im->alpha[(c3)] + m4*im->alpha[(c4)]);
}
r = CLAMP(r, 0, 255);
g = CLAMP(g, 0, 255);
b = CLAMP(b, 0, 255);
a = CLAMP(a, 0, gdAlphaMax);
return gdTrueColorAlpha(r, g, b, a);
}
/**
* Function: getPixelInterpolated
* Returns the interpolated color value using the default interpolation
* method. The returned color is always in the ARGB format (truecolor).
*
* Parameters:
* im - Image to set the default interpolation method
* y - X value of the ideal position
* y - Y value of the ideal position
* method - Interpolation method <gdInterpolationMethod>
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*
* See also:
* <gdSetInterpolationMethod>
*/
int getPixelInterpolated(gdImagePtr im, const double x, const double y, const int bgColor)
{
const int xi=(int)((x) < 0 ? x - 1: x);
const int yi=(int)((y) < 0 ? y - 1: y);
int yii;
int i;
double kernel, kernel_cache_y;
double kernel_x[12], kernel_y[4];
double new_r = 0.0f, new_g = 0.0f, new_b = 0.0f, new_a = 0.0f;
/* These methods use special implementations */
if (im->interpolation_id == GD_BILINEAR_FIXED || im->interpolation_id == GD_BICUBIC_FIXED || im->interpolation_id == GD_NEAREST_NEIGHBOUR) {
return -1;
}
/* Default to full alpha */
if (bgColor == -1) {
}
if (im->interpolation_id == GD_WEIGHTED4) {
return getPixelInterpolateWeight(im, x, y, bgColor);
}
if (im->interpolation_id == GD_NEAREST_NEIGHBOUR) {
if (im->trueColor == 1) {
return getPixelOverflowTC(im, xi, yi, bgColor);
} else {
return getPixelOverflowPalette(im, xi, yi, bgColor);
}
}
if (im->interpolation) {
for (i=0; i<4; i++) {
kernel_x[i] = (double) im->interpolation((double)(xi+i-1-x));
kernel_y[i] = (double) im->interpolation((double)(yi+i-1-y));
}
} else {
return -1;
}
/*
* TODO: use the known fast rgba multiplication implementation once
* the new formats are in place
*/
for (yii = yi-1; yii < yi+3; yii++) {
int xii;
kernel_cache_y = kernel_y[yii-(yi-1)];
if (im->trueColor) {
for (xii=xi-1; xii<xi+3; xii++) {
const int rgbs = getPixelOverflowTC(im, xii, yii, bgColor);
kernel = kernel_cache_y * kernel_x[xii-(xi-1)];
new_r += kernel * gdTrueColorGetRed(rgbs);
new_g += kernel * gdTrueColorGetGreen(rgbs);
new_b += kernel * gdTrueColorGetBlue(rgbs);
new_a += kernel * gdTrueColorGetAlpha(rgbs);
}
} else {
for (xii=xi-1; xii<xi+3; xii++) {
const int rgbs = getPixelOverflowPalette(im, xii, yii, bgColor);
kernel = kernel_cache_y * kernel_x[xii-(xi-1)];
new_r += kernel * gdTrueColorGetRed(rgbs);
new_g += kernel * gdTrueColorGetGreen(rgbs);
new_b += kernel * gdTrueColorGetBlue(rgbs);
new_a += kernel * gdTrueColorGetAlpha(rgbs);
}
}
}
new_r = CLAMP(new_r, 0, 255);
new_g = CLAMP(new_g, 0, 255);
new_b = CLAMP(new_b, 0, 255);
new_a = CLAMP(new_a, 0, gdAlphaMax);
return gdTrueColorAlpha(((int)new_r), ((int)new_g), ((int)new_b), ((int)new_a));
}
static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size)
{
unsigned int u = 0;
LineContribType *res;
res = (LineContribType *) gdMalloc(sizeof(LineContribType));
if (!res) {
return NULL;
}
res->WindowSize = windows_size;
res->LineLength = line_length;
res->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType));
for (u = 0 ; u < line_length ; u++) {
res->ContribRow[u].Weights = (double *) gdMalloc(windows_size * sizeof(double));
}
return res;
}
static inline void _gdContributionsFree(LineContribType * p)
{
unsigned int u;
for (u = 0; u < p->LineLength; u++) {
gdFree(p->ContribRow[u].Weights);
}
gdFree(p->ContribRow);
gdFree(p);
}
static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)
{
double width_d;
double scale_f_d = 1.0;
const double filter_width_d = DEFAULT_BOX_RADIUS;
int windows_size;
unsigned int u;
LineContribType *res;
if (scale_d < 1.0) {
width_d = filter_width_d / scale_d;
scale_f_d = scale_d;
} else {
width_d= filter_width_d;
}
windows_size = 2 * (int)ceil(width_d) + 1;
res = _gdContributionsAlloc(line_size, windows_size);
for (u = 0; u < line_size; u++) {
const double dCenter = (double)u / scale_d;
/* get the significant edge points affecting the pixel */
register int iLeft = MAX(0, (int)floor (dCenter - width_d));
int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);
double dTotalWeight = 0.0;
int iSrc;
res->ContribRow[u].Left = iLeft;
res->ContribRow[u].Right = iRight;
/* Cut edge points to fit in filter window in case of spill-off */
if (iRight - iLeft + 1 > windows_size) {
if (iLeft < ((int)src_size - 1 / 2)) {
iLeft++;
} else {
iRight--;
}
}
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));
}
if (dTotalWeight < 0.0) {
_gdContributionsFree(res);
return NULL;
}
if (dTotalWeight > 0.0) {
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;
}
}
}
return res;
}
static inline void _gdScaleRow(gdImagePtr pSrc, unsigned int src_width, gdImagePtr dst, unsigned int dst_width, unsigned int row, LineContribType *contrib)
{
int *p_src_row = pSrc->tpixels[row];
int *p_dst_row = dst->tpixels[row];
unsigned int x;
for (x = 0; x < dst_width - 1; x++) {
register unsigned char r = 0, g = 0, b = 0, a = 0;
const int left = contrib->ContribRow[x].Left;
const int right = contrib->ContribRow[x].Right;
int i;
/* Accumulate each channel */
for (i = left; i <= right; i++) {
const int left_channel = i - left;
r += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetRed(p_src_row[i])));
g += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetGreen(p_src_row[i])));
b += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetBlue(p_src_row[i])));
a += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetAlpha(p_src_row[i])));
}
p_dst_row[x] = gdTrueColorAlpha(r, g, b, a);
}
}
static inline void _gdScaleHoriz(gdImagePtr pSrc, unsigned int src_width, unsigned int src_height, gdImagePtr pDst, unsigned int dst_width, unsigned int dst_height)
{
unsigned int u;
LineContribType * contrib;
/* same width, just copy it */
if (dst_width == src_width) {
unsigned int y;
for (y = 0; y < src_height - 1; ++y) {
memcpy(pDst->tpixels[y], pSrc->tpixels[y], src_width);
}
}
contrib = _gdContributionsCalc(dst_width, src_width, (double)dst_width / (double)src_width, pSrc->interpolation);
if (contrib == NULL) {
return;
}
/* Scale each row */
for (u = 0; u < dst_height - 1; u++) {
_gdScaleRow(pSrc, src_width, pDst, dst_width, u, contrib);
}
_gdContributionsFree (contrib);
}
static inline void _gdScaleCol (gdImagePtr pSrc, unsigned int src_width, gdImagePtr pRes, unsigned int dst_width, unsigned int dst_height, unsigned int uCol, LineContribType *contrib)
{
unsigned int y;
for (y = 0; y < dst_height - 1; y++) {
register unsigned char r = 0, g = 0, b = 0, a = 0;
const int iLeft = contrib->ContribRow[y].Left;
const int iRight = contrib->ContribRow[y].Right;
int i;
int *row = pRes->tpixels[y];
/* Accumulate each channel */
for (i = iLeft; i <= iRight; i++) {
const int pCurSrc = pSrc->tpixels[i][uCol];
const int i_iLeft = i - iLeft;
r += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetRed(pCurSrc)));
g += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetGreen(pCurSrc)));
b += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetBlue(pCurSrc)));
a += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetAlpha(pCurSrc)));
}
pRes->tpixels[y][uCol] = gdTrueColorAlpha(r, g, b, a);
}
}
static inline void _gdScaleVert (const gdImagePtr pSrc, const unsigned int src_width, const unsigned int src_height, const gdImagePtr pDst, const unsigned int dst_width, const unsigned int dst_height)
{
unsigned int u;
LineContribType * contrib;
/* same height, copy it */
if (src_height == dst_height) {
unsigned int y;
for (y = 0; y < src_height - 1; ++y) {
memcpy(pDst->tpixels[y], pSrc->tpixels[y], src_width);
}
}
contrib = _gdContributionsCalc(dst_height, src_height, (double)(dst_height) / (double)(src_height), pSrc->interpolation);
/* scale each column */
for (u = 0; u < dst_width - 1; u++) {
_gdScaleCol(pSrc, src_width, pDst, dst_width, dst_height, u, contrib);
}
_gdContributionsFree(contrib);
}
gdImagePtr gdImageScaleTwoPass(const gdImagePtr src, const unsigned int src_width, const unsigned int src_height, const unsigned int new_width, const unsigned int new_height)
{
gdImagePtr tmp_im;
gdImagePtr dst;
tmp_im = gdImageCreateTrueColor(new_width, src_height);
if (tmp_im == NULL) {
return NULL;
}
gdImageSetInterpolationMethod(tmp_im, src->interpolation_id);
_gdScaleHoriz(src, src_width, src_height, tmp_im, new_width, src_height);
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst == NULL) {
gdFree(tmp_im);
return NULL;
}
gdImageSetInterpolationMethod(dst, src->interpolation_id);
_gdScaleVert(tmp_im, new_width, src_height, dst, new_width, new_height);
gdFree(tmp_im);
return dst;
}
gdImagePtr Scale(const gdImagePtr src, const unsigned int src_width, const unsigned int src_height, const gdImagePtr dst, const unsigned int new_width, const unsigned int new_height)
{
gdImagePtr tmp_im;
tmp_im = gdImageCreateTrueColor(new_width, src_height);
if (tmp_im == NULL) {
return NULL;
}
gdImageSetInterpolationMethod(tmp_im, src->interpolation_id);
_gdScaleHoriz(src, src_width, src_height, tmp_im, new_width, src_height);
_gdScaleVert(tmp_im, new_width, src_height, dst, new_width, new_height);
gdFree(tmp_im);
return dst;
}
/*
BilinearFixed, BicubicFixed and nearest implementations are rewamped versions of the implementation in CBitmapEx
http://www.codeproject.com/Articles/29121/CBitmapEx-Free-C-Bitmap-Manipulation-Class
Integer only implementation, good to have for common usages like pre scale very large
images before using another interpolation methods for the last step.
*/
gdImagePtr gdImageScaleNearestNeighbour(gdImagePtr im, const unsigned int width, const unsigned int height)
{
const unsigned long new_width = MAX(1, width);
const unsigned long new_height = MAX(1, height);
const float dx = (float)im->sx / (float)new_width;
const float dy = (float)im->sy / (float)new_height;
const gdFixed f_dx = gd_ftofx(dx);
const gdFixed f_dy = gd_ftofx(dy);
gdImagePtr dst_img;
unsigned long dst_offset_x;
unsigned long dst_offset_y = 0;
unsigned int i;
dst_img = gdImageCreateTrueColor(new_width, new_height);
if (dst_img == NULL) {
return NULL;
}
for (i=0; i<new_height; i++) {
unsigned int j;
dst_offset_x = 0;
if (im->trueColor) {
for (j=0; j<new_width; j++) {
const gdFixed f_i = gd_itofx(i);
const gdFixed f_j = gd_itofx(j);
const gdFixed f_a = gd_mulfx(f_i, f_dy);
const gdFixed f_b = gd_mulfx(f_j, f_dx);
const long m = gd_fxtoi(f_a);
const long n = gd_fxtoi(f_b);
dst_img->tpixels[dst_offset_y][dst_offset_x++] = im->tpixels[m][n];
}
} else {
for (j=0; j<new_width; j++) {
const gdFixed f_i = gd_itofx(i);
const gdFixed f_j = gd_itofx(j);
const gdFixed f_a = gd_mulfx(f_i, f_dy);
const gdFixed f_b = gd_mulfx(f_j, f_dx);
const long m = gd_fxtoi(f_a);
const long n = gd_fxtoi(f_b);
dst_img->tpixels[dst_offset_y][dst_offset_x++] = colorIndex2RGBA(im->pixels[m][n]);
}
}
dst_offset_y++;
}
return dst_img;
}
static inline int getPixelOverflowColorTC(gdImagePtr im, const int x, const int y, const int color)
{
if (gdImageBoundsSafe(im, x, y)) {
const int c = im->tpixels[y][x];
if (c == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
}
return c;
} else {
register int border = 0;
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y > im->cy2) {
if (x >= im->cx1 && x <= im->cx1) {
border = im->tpixels[im->cy2][x];
goto processborder;
} else {
return gdTrueColorAlpha(0, 0, 0, 127);
}
}
/* y is bound safe at this point */
if (x < im->cx1) {
border = im->tpixels[y][im->cx1];
goto processborder;
}
if (x > im->cx2) {
border = im->tpixels[y][im->cx2];
}
processborder:
if (border == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
} else{
return gdTrueColorAlpha(gdTrueColorGetRed(border), gdTrueColorGetGreen(border), gdTrueColorGetBlue(border), 127);
}
}
}
static gdImagePtr gdImageScaleBilinearPalette(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
long _width = MAX(1, new_width);
long _height = MAX(1, new_height);
float dx = (float)gdImageSX(im) / (float)_width;
float dy = (float)gdImageSY(im) / (float)_height;
gdFixed f_dx = gd_ftofx(dx);
gdFixed f_dy = gd_ftofx(dy);
gdFixed f_1 = gd_itofx(1);
int dst_offset_h;
int dst_offset_v = 0;
long i;
gdImagePtr new_img;
const int transparent = im->transparent;
new_img = gdImageCreateTrueColor(new_width, new_height);
if (new_img == NULL) {
return NULL;
}
new_img->transparent = gdTrueColorAlpha(im->red[transparent], im->green[transparent], im->blue[transparent], im->alpha[transparent]);
for (i=0; i < _height; i++) {
long j;
const gdFixed f_i = gd_itofx(i);
const gdFixed f_a = gd_mulfx(f_i, f_dy);
register long m = gd_fxtoi(f_a);
dst_offset_h = 0;
for (j=0; j < _width; j++) {
/* Update bitmap */
gdFixed f_j = gd_itofx(j);
gdFixed f_b = gd_mulfx(f_j, f_dx);
const long n = gd_fxtoi(f_b);
gdFixed f_f = f_a - gd_itofx(m);
gdFixed f_g = f_b - gd_itofx(n);
const gdFixed f_w1 = gd_mulfx(f_1-f_f, f_1-f_g);
const gdFixed f_w2 = gd_mulfx(f_1-f_f, f_g);
const gdFixed f_w3 = gd_mulfx(f_f, f_1-f_g);
const gdFixed f_w4 = gd_mulfx(f_f, f_g);
unsigned int pixel1;
unsigned int pixel2;
unsigned int pixel3;
unsigned int pixel4;
register gdFixed f_r1, f_r2, f_r3, f_r4,
f_g1, f_g2, f_g3, f_g4,
f_b1, f_b2, f_b3, f_b4,
f_a1, f_a2, f_a3, f_a4;
/* zero for the background color, nothig gets outside anyway */
pixel1 = getPixelOverflowPalette(im, n, m, 0);
pixel2 = getPixelOverflowPalette(im, n + 1, m, 0);
pixel3 = getPixelOverflowPalette(im, n, m + 1, 0);
pixel4 = getPixelOverflowPalette(im, n + 1, m + 1, 0);
f_r1 = gd_itofx(gdTrueColorGetRed(pixel1));
f_r2 = gd_itofx(gdTrueColorGetRed(pixel2));
f_r3 = gd_itofx(gdTrueColorGetRed(pixel3));
f_r4 = gd_itofx(gdTrueColorGetRed(pixel4));
f_g1 = gd_itofx(gdTrueColorGetGreen(pixel1));
f_g2 = gd_itofx(gdTrueColorGetGreen(pixel2));
f_g3 = gd_itofx(gdTrueColorGetGreen(pixel3));
f_g4 = gd_itofx(gdTrueColorGetGreen(pixel4));
f_b1 = gd_itofx(gdTrueColorGetBlue(pixel1));
f_b2 = gd_itofx(gdTrueColorGetBlue(pixel2));
f_b3 = gd_itofx(gdTrueColorGetBlue(pixel3));
f_b4 = gd_itofx(gdTrueColorGetBlue(pixel4));
f_a1 = gd_itofx(gdTrueColorGetAlpha(pixel1));
f_a2 = gd_itofx(gdTrueColorGetAlpha(pixel2));
f_a3 = gd_itofx(gdTrueColorGetAlpha(pixel3));
f_a4 = gd_itofx(gdTrueColorGetAlpha(pixel4));
{
const char red = (char) gd_fxtoi(gd_mulfx(f_w1, f_r1) + gd_mulfx(f_w2, f_r2) + gd_mulfx(f_w3, f_r3) + gd_mulfx(f_w4, f_r4));
const char green = (char) gd_fxtoi(gd_mulfx(f_w1, f_g1) + gd_mulfx(f_w2, f_g2) + gd_mulfx(f_w3, f_g3) + gd_mulfx(f_w4, f_g4));
const char blue = (char) gd_fxtoi(gd_mulfx(f_w1, f_b1) + gd_mulfx(f_w2, f_b2) + gd_mulfx(f_w3, f_b3) + gd_mulfx(f_w4, f_b4));
const char alpha = (char) gd_fxtoi(gd_mulfx(f_w1, f_a1) + gd_mulfx(f_w2, f_a2) + gd_mulfx(f_w3, f_a3) + gd_mulfx(f_w4, f_a4));
new_img->tpixels[dst_offset_v][dst_offset_h] = gdTrueColorAlpha(red, green, blue, alpha);
}
dst_offset_h++;
}
dst_offset_v++;
}
return new_img;
}
static gdImagePtr gdImageScaleBilinearTC(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
long dst_w = MAX(1, new_width);
long dst_h = MAX(1, new_height);
float dx = (float)gdImageSX(im) / (float)dst_w;
float dy = (float)gdImageSY(im) / (float)dst_h;
gdFixed f_dx = gd_ftofx(dx);
gdFixed f_dy = gd_ftofx(dy);
gdFixed f_1 = gd_itofx(1);
int dst_offset_h;
int dst_offset_v = 0;
int dwSrcTotalOffset;
long i;
gdImagePtr new_img;
new_img = gdImageCreateTrueColor(new_width, new_height);
if (!new_img){
return NULL;
}
for (i=0; i < dst_h; i++) {
long j;
dst_offset_h = 0;
for (j=0; j < dst_w; j++) {
/* Update bitmap */
gdFixed f_i = gd_itofx(i);
gdFixed f_j = gd_itofx(j);
gdFixed f_a = gd_mulfx(f_i, f_dy);
gdFixed f_b = gd_mulfx(f_j, f_dx);
const gdFixed m = gd_fxtoi(f_a);
const gdFixed n = gd_fxtoi(f_b);
gdFixed f_f = f_a - gd_itofx(m);
gdFixed f_g = f_b - gd_itofx(n);
const gdFixed f_w1 = gd_mulfx(f_1-f_f, f_1-f_g);
const gdFixed f_w2 = gd_mulfx(f_1-f_f, f_g);
const gdFixed f_w3 = gd_mulfx(f_f, f_1-f_g);
const gdFixed f_w4 = gd_mulfx(f_f, f_g);
unsigned int pixel1;
unsigned int pixel2;
unsigned int pixel3;
unsigned int pixel4;
register gdFixed f_r1, f_r2, f_r3, f_r4,
f_g1, f_g2, f_g3, f_g4,
f_b1, f_b2, f_b3, f_b4,
f_a1, f_a2, f_a3, f_a4;
dwSrcTotalOffset = m + n;
/* 0 for bgColor, nothing gets outside anyway */
pixel1 = getPixelOverflowTC(im, n, m, 0);
pixel2 = getPixelOverflowTC(im, n + 1, m, 0);
pixel3 = getPixelOverflowTC(im, n, m + 1, 0);
pixel4 = getPixelOverflowTC(im, n + 1, m + 1, 0);
f_r1 = gd_itofx(gdTrueColorGetRed(pixel1));
f_r2 = gd_itofx(gdTrueColorGetRed(pixel2));
f_r3 = gd_itofx(gdTrueColorGetRed(pixel3));
f_r4 = gd_itofx(gdTrueColorGetRed(pixel4));
f_g1 = gd_itofx(gdTrueColorGetGreen(pixel1));
f_g2 = gd_itofx(gdTrueColorGetGreen(pixel2));
f_g3 = gd_itofx(gdTrueColorGetGreen(pixel3));
f_g4 = gd_itofx(gdTrueColorGetGreen(pixel4));
f_b1 = gd_itofx(gdTrueColorGetBlue(pixel1));
f_b2 = gd_itofx(gdTrueColorGetBlue(pixel2));
f_b3 = gd_itofx(gdTrueColorGetBlue(pixel3));
f_b4 = gd_itofx(gdTrueColorGetBlue(pixel4));
f_a1 = gd_itofx(gdTrueColorGetAlpha(pixel1));
f_a2 = gd_itofx(gdTrueColorGetAlpha(pixel2));
f_a3 = gd_itofx(gdTrueColorGetAlpha(pixel3));
f_a4 = gd_itofx(gdTrueColorGetAlpha(pixel4));
{
const unsigned char red = (unsigned char) gd_fxtoi(gd_mulfx(f_w1, f_r1) + gd_mulfx(f_w2, f_r2) + gd_mulfx(f_w3, f_r3) + gd_mulfx(f_w4, f_r4));
const unsigned char green = (unsigned char) gd_fxtoi(gd_mulfx(f_w1, f_g1) + gd_mulfx(f_w2, f_g2) + gd_mulfx(f_w3, f_g3) + gd_mulfx(f_w4, f_g4));
const unsigned char blue = (unsigned char) gd_fxtoi(gd_mulfx(f_w1, f_b1) + gd_mulfx(f_w2, f_b2) + gd_mulfx(f_w3, f_b3) + gd_mulfx(f_w4, f_b4));
const unsigned char alpha = (unsigned char) gd_fxtoi(gd_mulfx(f_w1, f_a1) + gd_mulfx(f_w2, f_a2) + gd_mulfx(f_w3, f_a3) + gd_mulfx(f_w4, f_a4));
new_img->tpixels[dst_offset_v][dst_offset_h] = gdTrueColorAlpha(red, green, blue, alpha);
}
dst_offset_h++;
}
dst_offset_v++;
}
return new_img;
}
gdImagePtr gdImageScaleBilinear(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
if (im->trueColor) {
return gdImageScaleBilinearTC(im, new_width, new_height);
} else {
return gdImageScaleBilinearPalette(im, new_width, new_height);
}
}
gdImagePtr gdImageScaleBicubicFixed(gdImagePtr src, const unsigned int width, const unsigned int height)
{
const long new_width = MAX(1, width);
const long new_height = MAX(1, height);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const gdFixed f_dx = gd_ftofx((float)src_w / (float)new_width);
const gdFixed f_dy = gd_ftofx((float)src_h / (float)new_height);
const gdFixed f_1 = gd_itofx(1);
const gdFixed f_2 = gd_itofx(2);
const gdFixed f_4 = gd_itofx(4);
const gdFixed f_6 = gd_itofx(6);
const gdFixed f_gamma = gd_ftofx(1.04f);
gdImagePtr dst;
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
long i;
/* impact perf a bit, but not that much. Implementation for palette
images can be done at a later point.
*/
if (src->trueColor == 0) {
gdImagePaletteToTrueColor(src);
}
dst = gdImageCreateTrueColor(new_width, new_height);
if (!dst) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i=0; i < new_height; i++) {
long j;
dst_offset_x = 0;
for (j=0; j < new_width; j++) {
const gdFixed f_a = gd_mulfx(gd_itofx(i), f_dy);
const gdFixed f_b = gd_mulfx(gd_itofx(j), f_dx);
const long m = gd_fxtoi(f_a);
const long n = gd_fxtoi(f_b);
const gdFixed f_f = f_a - gd_itofx(m);
const gdFixed f_g = f_b - gd_itofx(n);
unsigned int src_offset_x[16], src_offset_y[16];
long k;
register gdFixed f_red = 0, f_green = 0, f_blue = 0, f_alpha = 0;
unsigned char red, green, blue, alpha = 0;
int *dst_row = dst->tpixels[dst_offset_y];
if ((m < 1) || (n < 1)) {
src_offset_x[0] = n;
src_offset_y[0] = m;
} else {
src_offset_x[0] = n - 1;
src_offset_y[0] = m;
}
if (m < 1) {
src_offset_x[1] = n;
src_offset_y[1] = m;
} else {
src_offset_x[1] = n;
src_offset_y[1] = m;
}
if ((m < 1) || (n >= src_w - 1)) {
src_offset_x[2] = n;
src_offset_y[2] = m;
} else {
src_offset_x[2] = n + 1;
src_offset_y[2] = m;
}
if ((m < 1) || (n >= src_w - 2)) {
src_offset_x[3] = n;
src_offset_y[3] = m;
} else {
src_offset_x[3] = n + 1 + 1;
src_offset_y[3] = m;
}
if (n < 1) {
src_offset_x[4] = n;
src_offset_y[4] = m;
} else {
src_offset_x[4] = n - 1;
src_offset_y[4] = m;
}
src_offset_x[5] = n;
src_offset_y[5] = m;
if (n >= src_w-1) {
src_offset_x[6] = n;
src_offset_y[6] = m;
} else {
src_offset_x[6] = n + 1;
src_offset_y[6] = m;
}
if (n >= src_w - 2) {
src_offset_x[7] = n;
src_offset_y[7] = m;
} else {
src_offset_x[7] = n + 1 + 1;
src_offset_y[7] = m;
}
if ((m >= src_h - 1) || (n < 1)) {
src_offset_x[8] = n;
src_offset_y[8] = m;
} else {
src_offset_x[8] = n - 1;
src_offset_y[8] = m;
}
if (m >= src_h - 1) {
src_offset_x[8] = n;
src_offset_y[8] = m;
} else {
src_offset_x[9] = n;
src_offset_y[9] = m;
}
if ((m >= src_h-1) || (n >= src_w-1)) {
src_offset_x[10] = n;
src_offset_y[10] = m;
} else {
src_offset_x[10] = n + 1;
src_offset_y[10] = m;
}
if ((m >= src_h - 1) || (n >= src_w - 2)) {
src_offset_x[11] = n;
src_offset_y[11] = m;
} else {
src_offset_x[11] = n + 1 + 1;
src_offset_y[11] = m;
}
if ((m >= src_h - 2) || (n < 1)) {
src_offset_x[12] = n;
src_offset_y[12] = m;
} else {
src_offset_x[12] = n - 1;
src_offset_y[12] = m;
}
if (m >= src_h - 2) {
src_offset_x[13] = n;
src_offset_y[13] = m;
} else {
src_offset_x[13] = n;
src_offset_y[13] = m;
}
if ((m >= src_h - 2) || (n >= src_w - 1)) {
src_offset_x[14] = n;
src_offset_y[14] = m;
} else {
src_offset_x[14] = n + 1;
src_offset_y[14] = m;
}
if ((m >= src_h - 2) || (n >= src_w - 2)) {
src_offset_x[15] = n;
src_offset_y[15] = m;
} else {
src_offset_x[15] = n + 1 + 1;
src_offset_y[15] = m;
}
for (k = -1; k < 3; k++) {
const gdFixed f = gd_itofx(k)-f_f;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
register gdFixed f_a = 0, f_b = 0, f_d = 0, f_c = 0;
register gdFixed f_RY;
int l;
if (f_fp2 > 0) f_a = gd_mulfx(f_fp2, gd_mulfx(f_fp2,f_fp2));
if (f_fp1 > 0) f_b = gd_mulfx(f_fp1, gd_mulfx(f_fp1,f_fp1));
if (f > 0) f_c = gd_mulfx(f, gd_mulfx(f,f));
if (f_fm1 > 0) f_d = gd_mulfx(f_fm1, gd_mulfx(f_fm1,f_fm1));
f_RY = gd_divfx((f_a - gd_mulfx(f_4,f_b) + gd_mulfx(f_6,f_c) - gd_mulfx(f_4,f_d)),f_6);
for (l = -1; l < 3; l++) {
const gdFixed f = gd_itofx(l) - f_g;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
register gdFixed f_a = 0, f_b = 0, f_c = 0, f_d = 0;
register gdFixed f_RX, f_R, f_rs, f_gs, f_bs, f_ba;
register int c;
const int _k = ((k+1)*4) + (l+1);
if (f_fp2 > 0) f_a = gd_mulfx(f_fp2,gd_mulfx(f_fp2,f_fp2));
if (f_fp1 > 0) f_b = gd_mulfx(f_fp1,gd_mulfx(f_fp1,f_fp1));
if (f > 0) f_c = gd_mulfx(f,gd_mulfx(f,f));
if (f_fm1 > 0) f_d = gd_mulfx(f_fm1,gd_mulfx(f_fm1,f_fm1));
f_RX = gd_divfx((f_a-gd_mulfx(f_4,f_b)+gd_mulfx(f_6,f_c)-gd_mulfx(f_4,f_d)),f_6);
f_R = gd_mulfx(f_RY,f_RX);
c = src->tpixels[*(src_offset_y + _k)][*(src_offset_x + _k)];
f_rs = gd_itofx(gdTrueColorGetRed(c));
f_gs = gd_itofx(gdTrueColorGetGreen(c));
f_bs = gd_itofx(gdTrueColorGetBlue(c));
f_ba = gd_itofx(gdTrueColorGetAlpha(c));
f_red += gd_mulfx(f_rs,f_R);
f_green += gd_mulfx(f_gs,f_R);
f_blue += gd_mulfx(f_bs,f_R);
f_alpha += gd_mulfx(f_ba,f_R);
}
}
red = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_red, f_gamma)), 0, 255);
green = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_green, f_gamma)), 0, 255);
blue = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_blue, f_gamma)), 0, 255);
alpha = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_alpha, f_gamma)), 0, 127);
*(dst_row + dst_offset_x) = gdTrueColorAlpha(red, green, blue, alpha);
dst_offset_x++;
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageScale(const gdImagePtr src, const unsigned int new_width, const unsigned int new_height)
{
gdImagePtr im_scaled = NULL;
if (src == NULL || src->interpolation_id < 0 || src->interpolation_id > GD_METHOD_COUNT) {
return 0;
}
switch (src->interpolation_id) {
/*Special cases, optimized implementations */
case GD_NEAREST_NEIGHBOUR:
im_scaled = gdImageScaleNearestNeighbour(src, new_width, new_height);
break;
case GD_BILINEAR_FIXED:
im_scaled = gdImageScaleBilinear(src, new_width, new_height);
break;
case GD_BICUBIC_FIXED:
im_scaled = gdImageScaleBicubicFixed(src, new_width, new_height);
break;
/* generic */
default:
if (src->interpolation == NULL) {
return NULL;
}
im_scaled = gdImageScaleTwoPass(src, src->sx, src->sy, new_width, new_height);
break;
}
return im_scaled;
}
gdImagePtr gdImageRotateNearestNeighbour(gdImagePtr src, const float degrees, const int bgColor)
{
float _angle = ((float) (-degrees / 180.0f) * (float)M_PI);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const unsigned int new_width = (unsigned int)(abs((int)(src_w * cos(_angle))) + abs((int)(src_h * sin(_angle))) + 0.5f);
const unsigned int new_height = (unsigned int)(abs((int)(src_w * sin(_angle))) + abs((int)(src_h * cos(_angle))) + 0.5f);
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int i;
gdImagePtr dst;
dst = gdImageCreateTrueColor(new_width, new_height);
if (!dst) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i = 0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j = 0; j < new_width; j++) {
gdFixed f_i = gd_itofx((int)i - (int)new_height/2);
gdFixed f_j = gd_itofx((int)j - (int)new_width/2);
gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
long m = gd_fxtoi(f_m);
long n = gd_fxtoi(f_n);
if ((m > 0) && (m < src_h-1) && (n > 0) && (n < src_w-1)) {
if (dst_offset_y < new_height) {
dst->tpixels[dst_offset_y][dst_offset_x++] = src->tpixels[m][n];
}
} else {
if (dst_offset_y < new_height) {
dst->tpixels[dst_offset_y][dst_offset_x++] = bgColor;
}
}
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageRotateGeneric(gdImagePtr src, const float degrees, const int bgColor)
{
float _angle = ((float) (-degrees / 180.0f) * (float)M_PI);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const unsigned int new_width = (unsigned int)(abs((int)(src_w * cos(_angle))) + abs((int)(src_h * sin(_angle))) + 0.5f);
const unsigned int new_height = (unsigned int)(abs((int)(src_w * sin(_angle))) + abs((int)(src_h * cos(_angle))) + 0.5f);
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int i;
gdImagePtr dst;
const gdFixed f_slop_y = f_sin;
const gdFixed f_slop_x = f_cos;
const gdFixed f_slop = f_slop_x > 0 && f_slop_x > 0 ?
f_slop_x > f_slop_y ? gd_divfx(f_slop_y, f_slop_x) : gd_divfx(f_slop_x, f_slop_y)
: 0;
dst = gdImageCreateTrueColor(new_width, new_height);
if (!dst) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i = 0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j = 0; j < new_width; j++) {
gdFixed f_i = gd_itofx((int)i - (int)new_height/ 2);
gdFixed f_j = gd_itofx((int)j - (int)new_width / 2);
gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
long m = gd_fxtoi(f_m);
long n = gd_fxtoi(f_n);
if ((n <= 0) || (m <= 0) || (m >= src_h) || (n >= src_w)) {
dst->tpixels[dst_offset_y][dst_offset_x++] = bgColor;
} else if ((n <= 1) || (m <= 1) || (m >= src_h - 1) || (n >= src_w - 1)) {
gdFixed f_127 = gd_itofx(127);
register int c = getPixelInterpolated(src, n, m, bgColor);
c = c | (( gdTrueColorGetAlpha(c) + ((int)(127* gd_fxtof(f_slop)))) << 24);
dst->tpixels[dst_offset_y][dst_offset_x++] = _color_blend(bgColor, c);
} else {
dst->tpixels[dst_offset_y][dst_offset_x++] = getPixelInterpolated(src, n, m, bgColor);
}
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageRotateBilinear(gdImagePtr src, const float degrees, const int bgColor)
{
float _angle = (float)((- degrees / 180.0f) * M_PI);
const unsigned int src_w = gdImageSX(src);
const unsigned int src_h = gdImageSY(src);
unsigned int new_width = abs((int)(src_w*cos(_angle))) + abs((int)(src_h*sin(_angle) + 0.5f));
unsigned int new_height = abs((int)(src_w*sin(_angle))) + abs((int)(src_h*cos(_angle) + 0.5f));
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
const gdFixed f_1 = gd_itofx(1);
unsigned int i;
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int src_offset_x, src_offset_y;
gdImagePtr dst;
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst == NULL) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i = 0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j=0; j < new_width; j++) {
const gdFixed f_i = gd_itofx((int)i - (int)new_height/2);
const gdFixed f_j = gd_itofx((int)j - (int)new_width/2);
const gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
const gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
const unsigned int m = gd_fxtoi(f_m);
const unsigned int n = gd_fxtoi(f_n);
if ((m > 0) && (m < src_h - 1) && (n > 0) && (n < src_w - 1)) {
const gdFixed f_f = f_m - gd_itofx(m);
const gdFixed f_g = f_n - gd_itofx(n);
const gdFixed f_w1 = gd_mulfx(f_1-f_f, f_1-f_g);
const gdFixed f_w2 = gd_mulfx(f_1-f_f, f_g);
const gdFixed f_w3 = gd_mulfx(f_f, f_1-f_g);
const gdFixed f_w4 = gd_mulfx(f_f, f_g);
if (n < src_w - 1) {
src_offset_x = n + 1;
src_offset_y = m;
}
if (m < src_h-1) {
src_offset_x = n;
src_offset_y = m + 1;
}
if (!((n >= src_w-1) || (m >= src_h-1))) {
src_offset_x = n + 1;
src_offset_y = m + 1;
}
{
const int pixel1 = src->tpixels[src_offset_y][src_offset_x];
register int pixel2, pixel3, pixel4;
if (src_offset_y + 1 >= src_h) {
pixel2 = bgColor;
pixel3 = bgColor;
pixel4 = bgColor;
} else if (src_offset_x + 1 >= src_w) {
pixel2 = bgColor;
pixel3 = bgColor;
pixel4 = bgColor;
} else {
pixel2 = src->tpixels[src_offset_y][src_offset_x + 1];
pixel3 = src->tpixels[src_offset_y + 1][src_offset_x];
pixel4 = src->tpixels[src_offset_y + 1][src_offset_x + 1];
}
{
const gdFixed f_r1 = gd_itofx(gdTrueColorGetRed(pixel1));
const gdFixed f_r2 = gd_itofx(gdTrueColorGetRed(pixel2));
const gdFixed f_r3 = gd_itofx(gdTrueColorGetRed(pixel3));
const gdFixed f_r4 = gd_itofx(gdTrueColorGetRed(pixel4));
const gdFixed f_g1 = gd_itofx(gdTrueColorGetGreen(pixel1));
const gdFixed f_g2 = gd_itofx(gdTrueColorGetGreen(pixel2));
const gdFixed f_g3 = gd_itofx(gdTrueColorGetGreen(pixel3));
const gdFixed f_g4 = gd_itofx(gdTrueColorGetGreen(pixel4));
const gdFixed f_b1 = gd_itofx(gdTrueColorGetBlue(pixel1));
const gdFixed f_b2 = gd_itofx(gdTrueColorGetBlue(pixel2));
const gdFixed f_b3 = gd_itofx(gdTrueColorGetBlue(pixel3));
const gdFixed f_b4 = gd_itofx(gdTrueColorGetBlue(pixel4));
const gdFixed f_a1 = gd_itofx(gdTrueColorGetAlpha(pixel1));
const gdFixed f_a2 = gd_itofx(gdTrueColorGetAlpha(pixel2));
const gdFixed f_a3 = gd_itofx(gdTrueColorGetAlpha(pixel3));
const gdFixed f_a4 = gd_itofx(gdTrueColorGetAlpha(pixel4));
const gdFixed f_red = gd_mulfx(f_w1, f_r1) + gd_mulfx(f_w2, f_r2) + gd_mulfx(f_w3, f_r3) + gd_mulfx(f_w4, f_r4);
const gdFixed f_green = gd_mulfx(f_w1, f_g1) + gd_mulfx(f_w2, f_g2) + gd_mulfx(f_w3, f_g3) + gd_mulfx(f_w4, f_g4);
const gdFixed f_blue = gd_mulfx(f_w1, f_b1) + gd_mulfx(f_w2, f_b2) + gd_mulfx(f_w3, f_b3) + gd_mulfx(f_w4, f_b4);
const gdFixed f_alpha = gd_mulfx(f_w1, f_a1) + gd_mulfx(f_w2, f_a2) + gd_mulfx(f_w3, f_a3) + gd_mulfx(f_w4, f_a4);
const unsigned char red = (unsigned char) CLAMP(gd_fxtoi(f_red), 0, 255);
const unsigned char green = (unsigned char) CLAMP(gd_fxtoi(f_green), 0, 255);
const unsigned char blue = (unsigned char) CLAMP(gd_fxtoi(f_blue), 0, 255);
const unsigned char alpha = (unsigned char) CLAMP(gd_fxtoi(f_alpha), 0, 127);
dst->tpixels[dst_offset_y][dst_offset_x++] = gdTrueColorAlpha(red, green, blue, alpha);
}
}
} else {
dst->tpixels[dst_offset_y][dst_offset_x++] = bgColor;
}
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageRotateBicubicFixed(gdImagePtr src, const float degrees, const int bgColor)
{
const float _angle = (float)((- degrees / 180.0f) * M_PI);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const unsigned int new_width = abs((int)(src_w*cos(_angle))) + abs((int)(src_h*sin(_angle) + 0.5f));
const unsigned int new_height = abs((int)(src_w*sin(_angle))) + abs((int)(src_h*cos(_angle) + 0.5f));
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
const gdFixed f_1 = gd_itofx(1);
const gdFixed f_2 = gd_itofx(2);
const gdFixed f_4 = gd_itofx(4);
const gdFixed f_6 = gd_itofx(6);
const gdFixed f_gama = gd_ftofx(1.04f);
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int i;
gdImagePtr dst;
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst == NULL) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i=0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j=0; j < new_width; j++) {
const gdFixed f_i = gd_itofx((int)i - (int)new_height/2);
const gdFixed f_j = gd_itofx((int)j - (int)new_width/2);
const gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
const gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
const int m = gd_fxtoi(f_m);
const int n = gd_fxtoi(f_n);
if ((m > 0) && (m < src_h - 1) && (n > 0) && (n < src_w-1)) {
const gdFixed f_f = f_m - gd_itofx(m);
const gdFixed f_g = f_n - gd_itofx(n);
unsigned int src_offset_x[16], src_offset_y[16];
unsigned char red, green, blue, alpha;
gdFixed f_red=0, f_green=0, f_blue=0, f_alpha=0;
int k;
if ((m < 1) || (n < 1)) {
src_offset_x[0] = n;
src_offset_y[0] = m;
} else {
src_offset_x[0] = n - 1;
src_offset_y[0] = m;
}
if (m < 1) {
src_offset_x[1] = n;
src_offset_y[1] = m;
} else {
src_offset_x[1] = n;
src_offset_y[1] = m ;
}
if ((m < 1) || (n >= src_w-1)) {
src_offset_x[2] = - 1;
src_offset_y[2] = - 1;
} else {
src_offset_x[2] = n + 1;
src_offset_y[2] = m ;
}
if ((m < 1) || (n >= src_w-2)) {
src_offset_x[3] = - 1;
src_offset_y[3] = - 1;
} else {
src_offset_x[3] = n + 1 + 1;
src_offset_y[3] = m ;
}
if (n < 1) {
src_offset_x[4] = - 1;
src_offset_y[4] = - 1;
} else {
src_offset_x[4] = n - 1;
src_offset_y[4] = m;
}
src_offset_x[5] = n;
src_offset_y[5] = m;
if (n >= src_w-1) {
src_offset_x[6] = - 1;
src_offset_y[6] = - 1;
} else {
src_offset_x[6] = n + 1;
src_offset_y[6] = m;
}
if (n >= src_w-2) {
src_offset_x[7] = - 1;
src_offset_y[7] = - 1;
} else {
src_offset_x[7] = n + 1 + 1;
src_offset_y[7] = m;
}
if ((m >= src_h-1) || (n < 1)) {
src_offset_x[8] = - 1;
src_offset_y[8] = - 1;
} else {
src_offset_x[8] = n - 1;
src_offset_y[8] = m;
}
if (m >= src_h-1) {
src_offset_x[8] = - 1;
src_offset_y[8] = - 1;
} else {
src_offset_x[9] = n;
src_offset_y[9] = m;
}
if ((m >= src_h-1) || (n >= src_w-1)) {
src_offset_x[10] = - 1;
src_offset_y[10] = - 1;
} else {
src_offset_x[10] = n + 1;
src_offset_y[10] = m;
}
if ((m >= src_h-1) || (n >= src_w-2)) {
src_offset_x[11] = - 1;
src_offset_y[11] = - 1;
} else {
src_offset_x[11] = n + 1 + 1;
src_offset_y[11] = m;
}
if ((m >= src_h-2) || (n < 1)) {
src_offset_x[12] = - 1;
src_offset_y[12] = - 1;
} else {
src_offset_x[12] = n - 1;
src_offset_y[12] = m;
}
if (m >= src_h-2) {
src_offset_x[13] = - 1;
src_offset_y[13] = - 1;
} else {
src_offset_x[13] = n;
src_offset_y[13] = m;
}
if ((m >= src_h-2) || (n >= src_w - 1)) {
src_offset_x[14] = - 1;
src_offset_y[14] = - 1;
} else {
src_offset_x[14] = n + 1;
src_offset_y[14] = m;
}
if ((m >= src_h-2) || (n >= src_w-2)) {
src_offset_x[15] = - 1;
src_offset_y[15] = - 1;
} else {
src_offset_x[15] = n + 1 + 1;
src_offset_y[15] = m;
}
for (k=-1; k<3; k++) {
const gdFixed f = gd_itofx(k)-f_f;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
gdFixed f_a = 0, f_b = 0,f_c = 0, f_d = 0;
gdFixed f_RY;
int l;
if (f_fp2 > 0) {
f_a = gd_mulfx(f_fp2,gd_mulfx(f_fp2,f_fp2));
}
if (f_fp1 > 0) {
f_b = gd_mulfx(f_fp1,gd_mulfx(f_fp1,f_fp1));
}
if (f > 0) {
f_c = gd_mulfx(f,gd_mulfx(f,f));
}
if (f_fm1 > 0) {
f_d = gd_mulfx(f_fm1,gd_mulfx(f_fm1,f_fm1));
}
f_RY = gd_divfx((f_a-gd_mulfx(f_4,f_b)+gd_mulfx(f_6,f_c)-gd_mulfx(f_4,f_d)),f_6);
for (l=-1; l< 3; l++) {
const gdFixed f = gd_itofx(l) - f_g;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
gdFixed f_a = 0, f_b = 0, f_c = 0, f_d = 0;
gdFixed f_RX, f_R;
const int _k = ((k + 1) * 4) + (l + 1);
register gdFixed f_rs, f_gs, f_bs, f_as;
register int c;
if (f_fp2 > 0) {
f_a = gd_mulfx(f_fp2,gd_mulfx(f_fp2,f_fp2));
}
if (f_fp1 > 0) {
f_b = gd_mulfx(f_fp1,gd_mulfx(f_fp1,f_fp1));
}
if (f > 0) {
f_c = gd_mulfx(f,gd_mulfx(f,f));
}
if (f_fm1 > 0) {
f_d = gd_mulfx(f_fm1,gd_mulfx(f_fm1,f_fm1));
}
f_RX = gd_divfx((f_a - gd_mulfx(f_4, f_b) + gd_mulfx(f_6, f_c) - gd_mulfx(f_4, f_d)), f_6);
f_R = gd_mulfx(f_RY, f_RX);
if ((src_offset_x[_k] <= 0) || (src_offset_y[_k] <= 0) || (src_offset_y[_k] >= src_h) || (src_offset_x[_k] >= src_w)) {
c = bgColor;
} else if ((src_offset_x[_k] <= 1) || (src_offset_y[_k] <= 1) || (src_offset_y[_k] >= (int)src_h - 1) || (src_offset_x[_k] >= (int)src_w - 1)) {
gdFixed f_127 = gd_itofx(127);
c = src->tpixels[src_offset_y[_k]][src_offset_x[_k]];
c = c | (( (int) (gd_fxtof(gd_mulfx(f_R, f_127)) + 50.5f)) << 24);
c = _color_blend(bgColor, c);
} else {
c = src->tpixels[src_offset_y[_k]][src_offset_x[_k]];
}
f_rs = gd_itofx(gdTrueColorGetRed(c));
f_gs = gd_itofx(gdTrueColorGetGreen(c));
f_bs = gd_itofx(gdTrueColorGetBlue(c));
f_as = gd_itofx(gdTrueColorGetAlpha(c));
f_red += gd_mulfx(f_rs, f_R);
f_green += gd_mulfx(f_gs, f_R);
f_blue += gd_mulfx(f_bs, f_R);
f_alpha += gd_mulfx(f_as, f_R);
}
}
red = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_red, f_gama)), 0, 255);
green = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_green, f_gama)), 0, 255);
blue = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_blue, f_gama)), 0, 255);
alpha = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_alpha, f_gama)), 0, 127);
dst->tpixels[dst_offset_y][dst_offset_x] = gdTrueColorAlpha(red, green, blue, alpha);
} else {
dst->tpixels[dst_offset_y][dst_offset_x] = bgColor;
}
dst_offset_x++;
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageRotateInterpolated(const gdImagePtr src, const float angle, int bgcolor)
{
const int angle_rounded = (int)floor(angle * 100);
if (bgcolor < 0) {
return NULL;
}
/* impact perf a bit, but not that much. Implementation for palette
images can be done at a later point.
*/
if (src->trueColor == 0) {
if (bgcolor < gdMaxColors) {
bgcolor = gdTrueColorAlpha(src->red[bgcolor], src->green[bgcolor], src->blue[bgcolor], src->alpha[bgcolor]);
}
gdImagePaletteToTrueColor(src);
}
/* no interpolation needed here */
switch (angle_rounded) {
case 9000:
return gdImageRotate90(src, 0);
case 18000:
return gdImageRotate180(src, 0);
case 27000:
return gdImageRotate270(src, 0);
}
if (src == NULL || src->interpolation_id < 1 || src->interpolation_id > GD_METHOD_COUNT) {
return NULL;
}
switch (src->interpolation_id) {
case GD_NEAREST_NEIGHBOUR:
return gdImageRotateNearestNeighbour(src, angle, bgcolor);
break;
case GD_BILINEAR_FIXED:
return gdImageRotateBilinear(src, angle, bgcolor);
break;
case GD_BICUBIC_FIXED:
return gdImageRotateBicubicFixed(src, angle, bgcolor);
break;
default:
return gdImageRotateGeneric(src, angle, bgcolor);
}
return NULL;
}
/**
* Title: Affine transformation
**/
/**
* Group: Transform
**/
static void gdImageClipRectangle(gdImagePtr im, gdRectPtr r)
{
int c1x, c1y, c2x, c2y;
int x1,y1;
gdImageGetClip(im, &c1x, &c1y, &c2x, &c2y);
x1 = r->x + r->width - 1;
y1 = r->y + r->height - 1;
r->x = CLAMP(r->x, c1x, c2x);
r->y = CLAMP(r->y, c1y, c2y);
r->width = CLAMP(x1, c1x, c2x) - r->x + 1;
r->height = CLAMP(y1, c1y, c2y) - r->y + 1;
}
void gdDumpRect(const char *msg, gdRectPtr r)
{
printf("%s (%i, %i) (%i, %i)\n", msg, r->x, r->y, r->width, r->height);
}
/**
* Function: gdTransformAffineGetImage
* Applies an affine transformation to a region and return an image
* containing the complete transformation.
*
* Parameters:
* dst - Pointer to a gdImagePtr to store the created image, NULL when
* the creation or the transformation failed
* src - Source image
* src_area - rectangle defining the source region to transform
* dstY - Y position in the destination image
* affine - The desired affine transformation
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*/
int gdTransformAffineGetImage(gdImagePtr *dst,
const gdImagePtr src,
gdRectPtr src_area,
const double affine[6])
{
int res;
double m[6];
gdRect bbox;
gdRect area_full;
if (src_area == NULL) {
area_full.x = 0;
area_full.y = 0;
area_full.width = gdImageSX(src);
area_full.height = gdImageSY(src);
src_area = &area_full;
}
gdTransformAffineBoundingBox(src_area, affine, &bbox);
*dst = gdImageCreateTrueColor(bbox.width, bbox.height);
if (*dst == NULL) {
return GD_FALSE;
}
(*dst)->saveAlphaFlag = 1;
if (!src->trueColor) {
gdImagePaletteToTrueColor(src);
}
/* Translate to dst origin (0,0) */
gdAffineTranslate(m, -bbox.x, -bbox.y);
gdAffineConcat(m, affine, m);
gdImageAlphaBlending(*dst, 0);
res = gdTransformAffineCopy(*dst,
0,0,
src,
src_area,
m);
if (res != GD_TRUE) {
gdImageDestroy(*dst);
dst = NULL;
return GD_FALSE;
} else {
return GD_TRUE;
}
}
/**
* Function: gdTransformAffineCopy
* Applies an affine transformation to a region and copy the result
* in a destination to the given position.
*
* Parameters:
* dst - Image to draw the transformed image
* src - Source image
* dstX - X position in the destination image
* dstY - Y position in the destination image
* src_area - Rectangular region to rotate in the src image
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*/
int gdTransformAffineCopy(gdImagePtr dst,
int dst_x, int dst_y,
const gdImagePtr src,
gdRectPtr src_region,
const double affine[6])
{
int c1x,c1y,c2x,c2y;
int backclip = 0;
int backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2;
register int x, y, src_offset_x, src_offset_y;
double inv[6];
int *dst_p;
gdPointF pt, src_pt;
gdRect bbox;
int end_x, end_y;
gdInterpolationMethod interpolation_id_bak = GD_DEFAULT;
interpolation_method interpolation_bak;
/* These methods use special implementations */
if (src->interpolation_id == GD_BILINEAR_FIXED || src->interpolation_id == GD_BICUBIC_FIXED || src->interpolation_id == GD_NEAREST_NEIGHBOUR) {
interpolation_id_bak = src->interpolation_id;
interpolation_bak = src->interpolation;
gdImageSetInterpolationMethod(src, GD_BICUBIC);
}
gdImageClipRectangle(src, src_region);
if (src_region->x > 0 || src_region->y > 0
|| src_region->width < gdImageSX(src)
|| src_region->height < gdImageSY(src)) {
backclip = 1;
gdImageGetClip(src, &backup_clipx1, &backup_clipy1,
&backup_clipx2, &backup_clipy2);
gdImageSetClip(src, src_region->x, src_region->y,
src_region->x + src_region->width - 1,
src_region->y + src_region->height - 1);
}
if (!gdTransformAffineBoundingBox(src_region, affine, &bbox)) {
if (backclip) {
gdImageSetClip(src, backup_clipx1, backup_clipy1,
backup_clipx2, backup_clipy2);
}
gdImageSetInterpolationMethod(src, interpolation_id_bak);
return GD_FALSE;
}
gdImageGetClip(dst, &c1x, &c1y, &c2x, &c2y);
end_x = bbox.width + (int) fabs(bbox.x);
end_y = bbox.height + (int) fabs(bbox.y);
/* Get inverse affine to let us work with destination -> source */
gdAffineInvert(inv, affine);
src_offset_x = src_region->x;
src_offset_y = src_region->y;
if (dst->alphaBlendingFlag) {
for (y = bbox.y; y <= end_y; y++) {
pt.y = y + 0.5;
for (x = 0; x <= end_x; x++) {
pt.x = x + 0.5;
gdAffineApplyToPointF(&src_pt, &pt, inv);
gdImageSetPixel(dst, dst_x + x, dst_y + y, getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, 0));
}
}
} else {
for (y = 0; y <= end_y; y++) {
pt.y = y + 0.5 + bbox.y;
if ((dst_y + y) < 0 || ((dst_y + y) > gdImageSY(dst) -1)) {
continue;
}
dst_p = dst->tpixels[dst_y + y] + dst_x;
for (x = 0; x <= end_x; x++) {
pt.x = x + 0.5 + bbox.x;
gdAffineApplyToPointF(&src_pt, &pt, inv);
if ((dst_x + x) < 0 || (dst_x + x) > (gdImageSX(dst) - 1)) {
break;
}
*(dst_p++) = getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, -1);
}
}
}
/* Restore clip if required */
if (backclip) {
gdImageSetClip(src, backup_clipx1, backup_clipy1,
backup_clipx2, backup_clipy2);
}
gdImageSetInterpolationMethod(src, interpolation_id_bak);
return GD_TRUE;
}
/**
* Function: gdTransformAffineBoundingBox
* Returns the bounding box of an affine transformation applied to a
* rectangular area <gdRect>
*
* Parameters:
* src - Rectangular source area for the affine transformation
* affine - the affine transformation
* bbox - the resulting bounding box
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*/
int gdTransformAffineBoundingBox(gdRectPtr src, const double affine[6], gdRectPtr bbox)
{
gdPointF extent[4], min, max, point;
int i;
extent[0].x=0.0;
extent[0].y=0.0;
extent[1].x=(double) src->width;
extent[1].y=0.0;
extent[2].x=(double) src->width;
extent[2].y=(double) src->height;
extent[3].x=0.0;
extent[3].y=(double) src->height;
for (i=0; i < 4; i++) {
point=extent[i];
if (gdAffineApplyToPointF(&extent[i], &point, affine) != GD_TRUE) {
return GD_FALSE;
}
}
min=extent[0];
max=extent[0];
for (i=1; i < 4; i++) {
if (min.x > extent[i].x)
min.x=extent[i].x;
if (min.y > extent[i].y)
min.y=extent[i].y;
if (max.x < extent[i].x)
max.x=extent[i].x;
if (max.y < extent[i].y)
max.y=extent[i].y;
}
bbox->x = (int) min.x;
bbox->y = (int) min.y;
bbox->width = (int) floor(max.x - min.x) - 1;
bbox->height = (int) floor(max.y - min.y);
return GD_TRUE;
}
int gdImageSetInterpolationMethod(gdImagePtr im, gdInterpolationMethod id)
{
if (im == NULL || id < 0 || id > GD_METHOD_COUNT) {
return 0;
}
switch (id) {
case GD_DEFAULT:
id = GD_BILINEAR_FIXED;
/* Optimized versions */
case GD_BILINEAR_FIXED:
case GD_BICUBIC_FIXED:
case GD_NEAREST_NEIGHBOUR:
case GD_WEIGHTED4:
im->interpolation = NULL;
break;
/* generic versions*/
case GD_BELL:
im->interpolation = filter_bell;
break;
case GD_BESSEL:
im->interpolation = filter_bessel;
break;
case GD_BICUBIC:
im->interpolation = filter_bicubic;
break;
case GD_BLACKMAN:
im->interpolation = filter_blackman;
break;
case GD_BOX:
im->interpolation = filter_box;
break;
case GD_BSPLINE:
im->interpolation = filter_bspline;
break;
case GD_CATMULLROM:
im->interpolation = filter_catmullrom;
break;
case GD_GAUSSIAN:
im->interpolation = filter_gaussian;
break;
case GD_GENERALIZED_CUBIC:
im->interpolation = filter_generalized_cubic;
break;
case GD_HERMITE:
im->interpolation = filter_hermite;
break;
case GD_HAMMING:
im->interpolation = filter_hamming;
break;
case GD_HANNING:
im->interpolation = filter_hanning;
break;
case GD_MITCHELL:
im->interpolation = filter_mitchell;
break;
case GD_POWER:
im->interpolation = filter_power;
break;
case GD_QUADRATIC:
im->interpolation = filter_quadratic;
break;
case GD_SINC:
im->interpolation = filter_sinc;
break;
case GD_TRIANGLE:
im->interpolation = filter_triangle;
break;
default:
return 0;
break;
}
im->interpolation_id = id;
return 1;
}
#ifdef _MSC_VER
# pragma optimize("", on)
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5870_0 |
crossvul-cpp_data_good_351_16 | /*
* PKCS15 emulation layer for TCOS based preformatted cards
*
* Copyright (C) 2011, Peter Koch <pk@opensc-project.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "common/compat_strlcpy.h"
#include "common/compat_strlcat.h"
#include "internal.h"
#include "pkcs15.h"
#include "cardctl.h"
#include "log.h"
int sc_pkcs15emu_tcos_init_ex(
sc_pkcs15_card_t *p15card,
struct sc_aid *,
sc_pkcs15emu_opt_t *opts);
static int insert_cert(
sc_pkcs15_card_t *p15card,
const char *path,
unsigned char id,
int writable,
const char *label
){
sc_card_t *card=p15card->card;
sc_context_t *ctx=p15card->card->ctx;
struct sc_pkcs15_cert_info cert_info;
struct sc_pkcs15_object cert_obj;
unsigned char cert[20];
int r;
memset(&cert_info, 0, sizeof(cert_info));
cert_info.id.len = 1;
cert_info.id.value[0] = id;
cert_info.authority = 0;
sc_format_path(path, &cert_info.path);
memset(&cert_obj, 0, sizeof(cert_obj));
strlcpy(cert_obj.label, label, sizeof(cert_obj.label));
cert_obj.flags = writable ? SC_PKCS15_CO_FLAG_MODIFIABLE : 0;
if(sc_select_file(card, &cert_info.path, NULL)!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Select(%s) failed\n", path);
return 1;
}
if(sc_read_binary(card, 0, cert, sizeof(cert), 0)<0){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"ReadBinary(%s) failed\n", path);
return 2;
}
if(cert[0]!=0x30 || cert[1]!=0x82){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Invalid Cert: %02X:%02X:...\n", cert[0], cert[1]);
return 3;
}
/* some certificates are prefixed by an OID */
if(cert[4]==0x06 && cert[5]<10 && cert[6+cert[5]]==0x30 && cert[7+cert[5]]==0x82){
cert_info.path.index=6+cert[5];
cert_info.path.count=(cert[8+cert[5]]<<8) + cert[9+cert[5]] + 4;
} else {
cert_info.path.index=0;
cert_info.path.count=(cert[2]<<8) + cert[3] + 4;
}
r=sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
if(r!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "sc_pkcs15emu_add_x509_cert(%s) failed\n", path);
return 4;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: OK, Index=%d, Count=%d\n", path, cert_info.path.index, cert_info.path.count);
return 0;
}
static int insert_key(
sc_pkcs15_card_t *p15card,
const char *path,
unsigned char id,
unsigned char key_reference,
int key_length,
unsigned char auth_id,
const char *label
){
sc_card_t *card=p15card->card;
sc_context_t *ctx=p15card->card->ctx;
sc_file_t *f;
struct sc_pkcs15_prkey_info prkey_info;
struct sc_pkcs15_object prkey_obj;
int r, can_sign, can_crypt;
memset(&prkey_info, 0, sizeof(prkey_info));
prkey_info.id.len = 1;
prkey_info.id.value[0] = id;
prkey_info.native = 1;
prkey_info.key_reference = key_reference;
prkey_info.modulus_length = key_length;
sc_format_path(path, &prkey_info.path);
memset(&prkey_obj, 0, sizeof(prkey_obj));
strlcpy(prkey_obj.label, label, sizeof(prkey_obj.label));
prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
prkey_obj.auth_id.len = 1;
prkey_obj.auth_id.value[0] = auth_id;
can_sign=can_crypt=0;
if(card->type==SC_CARD_TYPE_TCOS_V3){
unsigned char buf[256];
int i, rec_no=0;
if(prkey_info.path.len>=2) prkey_info.path.len-=2;
sc_append_file_id(&prkey_info.path, 0x5349);
if(sc_select_file(card, &prkey_info.path, NULL)!=SC_SUCCESS || !f->prop_attr){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Select(%s) failed\n",
sc_print_path(&prkey_info.path));
return 1;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Searching for Key-Ref %02X\n", key_reference);
while((r=sc_read_record(card, ++rec_no, buf, sizeof(buf), SC_RECORD_BY_REC_NR))>0){
int found=0;
if(buf[0]!=0xA0) continue;
for(i=2;i<buf[1]+2;i+=2+buf[i+1]){
if(buf[i]==0x83 && buf[i+1]==1 && buf[i+2]==key_reference) ++found;
}
if(found) break;
}
if(r<=0){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"No EF_KEYD-Record found\n");
return 1;
}
for(i=0;i<r;i+=2+buf[i+1]){
if(buf[i]==0xB6) can_sign++;
if(buf[i]==0xB8) can_crypt++;
}
} else {
if(sc_select_file(card, &prkey_info.path, &f)!=SC_SUCCESS
|| !f->prop_attr || f->prop_attr_len < 2){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Select(%s) failed\n",
sc_print_path(&prkey_info.path));
return 1;
}
if (f->prop_attr[1] & 0x04) can_crypt=1;
if (f->prop_attr[1] & 0x08) can_sign=1;
sc_file_free(f);
}
prkey_info.usage= SC_PKCS15_PRKEY_USAGE_SIGN;
if(can_crypt) prkey_info.usage |= SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_DECRYPT;
if(can_sign) prkey_info.usage |= SC_PKCS15_PRKEY_USAGE_NONREPUDIATION;
r=sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info);
if(r!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "sc_pkcs15emu_add_rsa_prkey(%s) failed\n", path);
return 4;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: OK%s%s\n", path, can_sign ? ", Sign" : "", can_crypt ? ", Crypt" : "");
return 0;
}
static int insert_pin(
sc_pkcs15_card_t *p15card,
const char *path,
unsigned char id,
unsigned char auth_id,
unsigned char pin_reference,
int min_length,
const char *label,
int pin_flags
){
sc_card_t *card=p15card->card;
sc_context_t *ctx=p15card->card->ctx;
sc_file_t *f;
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
int r;
memset(&pin_info, 0, sizeof(pin_info));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = id;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = pin_reference;
pin_info.attrs.pin.flags = pin_flags;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = min_length;
pin_info.attrs.pin.stored_length = 16;
pin_info.attrs.pin.max_length = 16;
pin_info.attrs.pin.pad_char = '\0';
pin_info.logged_in = SC_PIN_STATE_UNKNOWN;
sc_format_path(path, &pin_info.path);
memset(&pin_obj, 0, sizeof(pin_obj));
strlcpy(pin_obj.label, label, sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE;
pin_obj.auth_id.len = auth_id ? 0 : 1;
pin_obj.auth_id.value[0] = auth_id;
if(card->type==SC_CARD_TYPE_TCOS_V3){
unsigned char buf[256];
int i, rec_no=0;
if(pin_info.path.len>=2) pin_info.path.len-=2;
sc_append_file_id(&pin_info.path, 0x5049);
if(sc_select_file(card, &pin_info.path, NULL)!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Select(%s) failed\n",
sc_print_path(&pin_info.path));
return 1;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Searching for PIN-Ref %02X\n", pin_reference);
while((r=sc_read_record(card, ++rec_no, buf, sizeof(buf), SC_RECORD_BY_REC_NR))>0){
int found=0, fbz=-1;
if(buf[0]!=0xA0) continue;
for(i=2;i<buf[1]+2;i+=2+buf[i+1]){
if(buf[i]==0x83 && buf[i+1]==1 && buf[i+2]==pin_reference) ++found;
if(buf[i]==0x90) fbz=buf[i+1+buf[i+1]];
}
if(found) pin_info.tries_left=fbz;
if(found) break;
}
if(r<=0){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"No EF_PWDD-Record found\n");
return 1;
}
} else {
if(sc_select_file(card, &pin_info.path, &f)!=SC_SUCCESS
|| !f->prop_attr || f->prop_attr_len < 4){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"Select(%s) failed\n", path);
return 1;
}
pin_info.tries_left=f->prop_attr[3];
sc_file_free(f);
}
r=sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if(r!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "sc_pkcs15emu_add_pin_obj(%s) failed\n", path);
return 4;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: OK, FBZ=%d\n", path, pin_info.tries_left);
return 0;
}
static char *dirpath(char *dir, const char *path){
static char buf[SC_MAX_PATH_STRING_SIZE];
strlcpy(buf,dir,sizeof buf);
strlcat(buf,path,sizeof buf);
return buf;
}
static int detect_netkey(
sc_pkcs15_card_t *p15card
){
sc_card_t *card=p15card->card;
sc_path_t p;
sc_file_t *f;
int keylen;
char dir[10];
const char *c_auth;
/* NKS-Applikation ? */
memset(&p, 0, sizeof(sc_path_t));
p.type=SC_PATH_TYPE_DF_NAME;
memcpy(p.value, "\xD2\x76\x00\x00\x03\x01\x02", p.len=7);
if (sc_select_file(card,&p,&f)!=SC_SUCCESS) return 1;
sprintf(dir,"%04X", f->id);
sc_file_free(f);
p15card->tokeninfo->manufacturer_id = strdup("TeleSec GmbH");
p15card->tokeninfo->label = strdup(card->type==SC_CARD_TYPE_TCOS_V3 ? "NetKey V3 Card" : "NetKey Card");
keylen= card->type==SC_CARD_TYPE_TCOS_V3 ? 2048 : 1024;
c_auth= card->type==SC_CARD_TYPE_TCOS_V3 ? "C500" : "C100";
insert_cert(p15card, dirpath(dir,"4331"), 0x45, 1, "Signatur Zertifikat 1");
insert_cert(p15card, dirpath(dir,"4332"), 0x45, 1, "Signatur Zertifikat 2");
insert_cert(p15card, dirpath(dir,"C000"), 0x45, 0, "Telesec Signatur Zertifikat");
insert_cert(p15card, dirpath(dir,"43B1"), 0x46, 1, "Verschluesselungs Zertifikat 1");
insert_cert(p15card, dirpath(dir,"43B2"), 0x46, 1, "Verschluesselungs Zertifikat 2");
insert_cert(p15card, dirpath(dir,"C200"), 0x46, 0, "Telesec Verschluesselungs Zertifikat");
insert_cert(p15card, dirpath(dir,"4371"), 0x47, 1, "Authentifizierungs Zertifikat 1");
insert_cert(p15card, dirpath(dir,"4372"), 0x47, 1, "Authentifizierungs Zertifikat 2");
insert_cert(p15card, dirpath(dir,c_auth), 0x47, 0, "Telesec Authentifizierungs Zertifikat");
insert_cert(p15card, dirpath(dir,"C201"), 0x48, 0, "Telesec 1024bit Zertifikat");
insert_key(p15card, dirpath(dir,"5331"), 0x45, 0x80, keylen, 4, "Signatur Schluessel");
insert_key(p15card, dirpath(dir,"53B1"), 0x46, 0x81, keylen, 3, "Verschluesselungs Schluessel");
insert_key(p15card, dirpath(dir,"5371"), 0x47, 0x82, keylen, 3, "Authentifizierungs Schluessel");
insert_key(p15card, dirpath(dir,"0000"), 0x48, 0x83, 1024, 3, "1024bit Schluessel");
insert_pin(p15card, "5000", 1, 2, 0x00, 6, "PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED
);
insert_pin(p15card, "5001", 2, 0, 0x01, 8, "PUK",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED |
SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN | SC_PKCS15_PIN_FLAG_SO_PIN
);
if(card->type==SC_CARD_TYPE_TCOS_V3){
insert_pin(p15card, dirpath(dir,"0000"), 3, 1, 0x83, 6, "NetKey PIN2",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
} else {
insert_pin(p15card, dirpath(dir,"5080"), 3, 1, 0x80, 6, "NetKey PIN0",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
}
insert_pin(p15card, dirpath(dir,"5081"), 4, 1, 0x81, 6, "NetKey PIN1",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
/* SigG-Applikation */
p.len=7; p.type=SC_PATH_TYPE_DF_NAME;
memcpy(p.value, "\xD2\x76\x00\x00\x66\x01", p.len=6);
if (sc_select_file(card,&p,&f)==SC_SUCCESS){
sprintf(dir,"%04X", f->id);
sc_file_free(f);
insert_cert(p15card, dirpath(dir,"C000"), 0x49, 1, "SigG Zertifikat 1");
insert_cert(p15card, dirpath(dir,"4331"), 0x49, 1, "SigG Zertifikat 2");
insert_cert(p15card, dirpath(dir,"4332"), 0x49, 1, "SigG Zertifikat 3");
if(card->type==SC_CARD_TYPE_TCOS_V3){
insert_key(p15card, dirpath(dir,"0000"), 0x49, 0x84, 2048, 5, "SigG Schluessel");
} else {
insert_key(p15card, dirpath(dir,"5331"), 0x49, 0x80, 1024, 5, "SigG Schluessel");
}
insert_pin(p15card, dirpath(dir,"5081"), 5, 0, 0x81, 6, "SigG PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
if(card->type==SC_CARD_TYPE_TCOS_V3){
insert_pin(p15card, dirpath(dir,"0000"), 6, 0, 0x83, 8, "SigG PIN2",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
}
}
return 0;
}
static int detect_idkey(
sc_pkcs15_card_t *p15card
){
sc_card_t *card=p15card->card;
sc_path_t p;
/* TCKEY-Applikation ? */
memset(&p, 0, sizeof(sc_path_t));
p.type=SC_PATH_TYPE_DF_NAME;
memcpy(p.value, "\xD2\x76\x00\x00\x03\x0C\x01", p.len=7);
if (sc_select_file(card,&p,NULL)!=SC_SUCCESS) return 1;
p15card->tokeninfo->manufacturer_id = strdup("TeleSec GmbH");
p15card->tokeninfo->label = strdup("IDKey Card");
insert_cert(p15card, "DF074331", 0x45, 1, "Signatur Zertifikat 1");
insert_cert(p15card, "DF074332", 0x45, 1, "Signatur Zertifikat 2");
insert_cert(p15card, "DF074333", 0x45, 1, "Signatur Zertifikat 3");
insert_key(p15card, "DF074E03", 0x45, 0x84, 2048, 1, "IDKey1");
insert_key(p15card, "DF074E04", 0x46, 0x85, 2048, 1, "IDKey2");
insert_key(p15card, "DF074E05", 0x47, 0x86, 2048, 1, "IDKey3");
insert_key(p15card, "DF074E06", 0x48, 0x87, 2048, 1, "IDKey4");
insert_key(p15card, "DF074E07", 0x49, 0x88, 2048, 1, "IDKey5");
insert_key(p15card, "DF074E08", 0x4A, 0x89, 2048, 1, "IDKey6");
insert_pin(p15card, "5000", 1, 2, 0x00, 6, "PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED
);
insert_pin(p15card, "5001", 2, 0, 0x01, 8, "PUK",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED |
SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN | SC_PKCS15_PIN_FLAG_SO_PIN
);
return 0;
}
static int detect_signtrust(
sc_pkcs15_card_t *p15card
){
if(insert_cert(p15card,"8000DF01C000", 0x45, 1, "Signatur Zertifikat")) return 1;
p15card->tokeninfo->manufacturer_id = strdup("Deutsche Post");
p15card->tokeninfo->label = strdup("SignTrust Card");
insert_cert(p15card,"800082008220", 0x46, 1, "Verschluesselungs Zertifikat");
insert_cert(p15card,"800083008320", 0x47, 1, "Authentifizierungs Zertifikat");
insert_key(p15card,"8000DF015331", 0x45, 0x80, 1024, 1, "Signatur Schluessel");
insert_key(p15card,"800082008210", 0x46, 0x80, 1024, 2, "Verschluesselungs Schluessel");
insert_key(p15card,"800083008310", 0x47, 0x80, 1024, 3, "Authentifizierungs Schluessel");
insert_pin(p15card,"8000DF010000", 1, 0, 0x81, 6, "Signatur PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
insert_pin(p15card,"800082000040", 2, 0, 0x81, 6, "Verschluesselungs PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
insert_pin(p15card,"800083000040", 3, 0, 0x81, 6, "Authentifizierungs PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
return 0;
}
static int detect_datev(
sc_pkcs15_card_t *p15card
){
if(insert_cert(p15card,"3000C500", 0x45, 0, "Signatur Zertifikat")) return 1;
p15card->tokeninfo->manufacturer_id = strdup("DATEV");
p15card->tokeninfo->label = strdup("DATEV Classic");
insert_cert(p15card,"DF02C200", 0x46, 0, "Verschluesselungs Zertifikat");
insert_cert(p15card,"DF02C500", 0x47, 0, "Authentifizierungs Zertifikat");
insert_key(p15card,"30005371", 0x45, 0x82, 1024, 1, "Signatur Schluessel");
insert_key(p15card,"DF0253B1", 0x46, 0x81, 1024, 1, "Verschluesselungs Schluessel");
insert_key(p15card,"DF025371", 0x47, 0x82, 1024, 1, "Authentifizierungs Schluessel");
insert_pin(p15card,"5001", 1, 0, 0x01, 6, "PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED
);
return 0;
}
static int detect_unicard(
sc_pkcs15_card_t *p15card
){
if(!insert_cert(p15card,"41004352", 0x45, 1, "Zertifikat 1")){
p15card->tokeninfo->manufacturer_id = strdup("JLU Giessen");
p15card->tokeninfo->label = strdup("JLU Giessen Card");
insert_cert(p15card,"41004353", 0x46, 1, "Zertifikat 2");
insert_cert(p15card,"41004354", 0x47, 1, "Zertifikat 3");
insert_key(p15card,"41005103", 0x45, 0x83, 1024, 1, "Schluessel 1");
insert_key(p15card,"41005104", 0x46, 0x84, 1024, 1, "Schluessel 2");
insert_key(p15card,"41005105", 0x47, 0x85, 1024, 1, "Schluessel 3");
} else if(!insert_cert(p15card,"41014352", 0x45, 1, "Zertifikat 1")){
p15card->tokeninfo->manufacturer_id = strdup("TU Darmstadt");
p15card->tokeninfo->label = strdup("TUD Card");
insert_cert(p15card,"41014353", 0x46, 1, "Zertifikat 2");
insert_cert(p15card,"41014354", 0x47, 1, "Zertifikat 3");
insert_key(p15card,"41015103", 0x45, 0x83, 1024, 1, "Schluessel 1");
insert_key(p15card,"41015104", 0x46, 0x84, 1024, 1, "Schluessel 2");
insert_key(p15card,"41015105", 0x47, 0x85, 1024, 1, "Schluessel 3");
} else return 1;
insert_pin(p15card,"5000", 1, 2, 0x00, 6, "PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED
);
insert_pin(p15card,"5008", 2, 0, 0x01, 8, "PUK",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED |
SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN | SC_PKCS15_PIN_FLAG_SO_PIN
);
return 0;
}
int sc_pkcs15emu_tcos_init_ex(
sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts
){
sc_card_t *card = p15card->card;
sc_context_t *ctx = p15card->card->ctx;
sc_serial_number_t serialnr;
char serial[30];
int i, r;
/* check if we have the correct card OS unless SC_PKCS15EMU_FLAGS_NO_CHECK */
i=(opts && (opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK));
if (!i && card->type!=SC_CARD_TYPE_TCOS_V2 && card->type!=SC_CARD_TYPE_TCOS_V3) return SC_ERROR_WRONG_CARD;
/* get the card serial number */
r = sc_card_ctl(card, SC_CARDCTL_GET_SERIALNR, &serialnr);
if (r < 0) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "unable to get ICCSN\n");
return SC_ERROR_WRONG_CARD;
}
sc_bin_to_hex(serialnr.value, serialnr.len , serial, sizeof(serial), 0);
serial[19] = '\0';
p15card->tokeninfo->serial_number = strdup(serial);
if(!detect_netkey(p15card)) return SC_SUCCESS;
if(!detect_idkey(p15card)) return SC_SUCCESS;
if(!detect_unicard(p15card)) return SC_SUCCESS;
if(!detect_signtrust(p15card)) return SC_SUCCESS;
if(!detect_datev(p15card)) return SC_SUCCESS;
return SC_ERROR_INTERNAL;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_351_16 |
crossvul-cpp_data_bad_5248_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% 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 ((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_5248_1 |
crossvul-cpp_data_good_1835_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT RRRR AAA N N SSSSS FFFFF OOO RRRR M M %
% T R R A A NN N SS F O O R R MM MM %
% T RRRR AAAAA N N N SSS FFF O O RRRR M M M %
% T R R A A N NN SS F O O R R M M %
% T R R A A N N SSSSS F OOO R R M M %
% %
% %
% MagickCore Image Transform Methods %
% %
% 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/cache.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/distort.h"
#include "MagickCore/draw.h"
#include "MagickCore/effect.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image.h"
#include "MagickCore/memory_.h"
#include "MagickCore/layer.h"
#include "MagickCore/list.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/resource_.h"
#include "MagickCore/resize.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/transform.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A u t o O r i e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AutoOrientImage() adjusts an image so that its orientation is suitable for
% viewing (i.e. top-left orientation).
%
% The format of the AutoOrientImage method is:
%
% Image *AutoOrientImage(const Image *image,
% const OrientationType orientation,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image.
%
% o orientation: Current image orientation.
%
% o exception: Return any errors or warnings in this structure.
%
*/
MagickExport Image *AutoOrientImage(const Image *image,
const OrientationType orientation,ExceptionInfo *exception)
{
Image
*orient_image;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
orient_image=(Image *) NULL;
switch(orientation)
{
case UndefinedOrientation:
case TopLeftOrientation:
default:
{
orient_image=CloneImage(image,0,0,MagickTrue,exception);
break;
}
case TopRightOrientation:
{
orient_image=FlopImage(image,exception);
break;
}
case BottomRightOrientation:
{
orient_image=RotateImage(image,180.0,exception);
break;
}
case BottomLeftOrientation:
{
orient_image=FlipImage(image,exception);
break;
}
case LeftTopOrientation:
{
orient_image=TransposeImage(image,exception);
break;
}
case RightTopOrientation:
{
orient_image=RotateImage(image,90.0,exception);
break;
}
case RightBottomOrientation:
{
orient_image=TransverseImage(image,exception);
break;
}
case LeftBottomOrientation:
{
orient_image=RotateImage(image,270.0,exception);
break;
}
}
if (orient_image != (Image *) NULL)
orient_image->orientation=TopLeftOrientation;
return(orient_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C h o p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ChopImage() removes a region of an image and collapses the image to occupy
% the removed portion.
%
% The format of the ChopImage method is:
%
% Image *ChopImage(const Image *image,const RectangleInfo *chop_info)
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o chop_info: Define the region of the image to chop.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ChopImage(const Image *image,const RectangleInfo *chop_info,
ExceptionInfo *exception)
{
#define ChopImageTag "Chop/Image"
CacheView
*chop_view,
*image_view;
Image
*chop_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
extent;
ssize_t
y;
/*
Check chop geometry.
*/
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);
assert(chop_info != (RectangleInfo *) NULL);
if (((chop_info->x+(ssize_t) chop_info->width) < 0) ||
((chop_info->y+(ssize_t) chop_info->height) < 0) ||
(chop_info->x > (ssize_t) image->columns) ||
(chop_info->y > (ssize_t) image->rows))
ThrowImageException(OptionWarning,"GeometryDoesNotContainImage");
extent=(*chop_info);
if ((extent.x+(ssize_t) extent.width) > (ssize_t) image->columns)
extent.width=(size_t) ((ssize_t) image->columns-extent.x);
if ((extent.y+(ssize_t) extent.height) > (ssize_t) image->rows)
extent.height=(size_t) ((ssize_t) image->rows-extent.y);
if (extent.x < 0)
{
extent.width-=(size_t) (-extent.x);
extent.x=0;
}
if (extent.y < 0)
{
extent.height-=(size_t) (-extent.y);
extent.y=0;
}
chop_image=CloneImage(image,image->columns-extent.width,image->rows-
extent.height,MagickTrue,exception);
if (chop_image == (Image *) NULL)
return((Image *) NULL);
/*
Extract chop image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
chop_view=AcquireAuthenticCacheView(chop_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,chop_image,1,1)
#endif
for (y=0; y < (ssize_t) extent.y; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(chop_view,0,y,chop_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((x < extent.x) || (x >= (ssize_t) (extent.x+extent.width)))
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait chop_traits=GetPixelChannelTraits(chop_image,channel);
if ((traits == UndefinedPixelTrait) ||
(chop_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(chop_image,channel,p[i],q);
}
q+=GetPixelChannels(chop_image);
}
p+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(chop_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ChopImage)
#endif
proceed=SetImageProgress(image,ChopImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
/*
Extract chop image.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,chop_image,1,1)
#endif
for (y=0; y < (ssize_t) (image->rows-(extent.y+extent.height)); y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,extent.y+extent.height+y,
image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(chop_view,0,extent.y+y,chop_image->columns,
1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((x < extent.x) || (x >= (ssize_t) (extent.x+extent.width)))
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait chop_traits=GetPixelChannelTraits(chop_image,channel);
if ((traits == UndefinedPixelTrait) ||
(chop_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(chop_image,channel,p[i],q);
}
q+=GetPixelChannels(chop_image);
}
p+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(chop_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ChopImage)
#endif
proceed=SetImageProgress(image,ChopImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
chop_view=DestroyCacheView(chop_view);
image_view=DestroyCacheView(image_view);
chop_image->type=image->type;
if (status == MagickFalse)
chop_image=DestroyImage(chop_image);
return(chop_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n s o l i d a t e C M Y K I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConsolidateCMYKImage() consolidates separate C, M, Y, and K planes into a
% single image.
%
% The format of the ConsolidateCMYKImage method is:
%
% Image *ConsolidateCMYKImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image sequence.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ConsolidateCMYKImages(const Image *images,
ExceptionInfo *exception)
{
CacheView
*cmyk_view,
*image_view;
Image
*cmyk_image,
*cmyk_images;
register ssize_t
j;
ssize_t
y;
/*
Consolidate separate C, M, Y, and K planes into a single image.
*/
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
cmyk_images=NewImageList();
for (j=0; j < (ssize_t) GetImageListLength(images); j+=4)
{
register ssize_t
i;
assert(images != (Image *) NULL);
cmyk_image=CloneImage(images,images->columns,images->rows,MagickTrue,
exception);
if (cmyk_image == (Image *) NULL)
break;
if (SetImageStorageClass(cmyk_image,DirectClass,exception) == MagickFalse)
break;
(void) SetImageColorspace(cmyk_image,CMYKColorspace,exception);
for (i=0; i < 4; i++)
{
image_view=AcquireVirtualCacheView(images,exception);
cmyk_view=AcquireAuthenticCacheView(cmyk_image,exception);
for (y=0; y < (ssize_t) images->rows; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
p=GetCacheViewVirtualPixels(image_view,0,y,images->columns,1,exception);
q=QueueCacheViewAuthenticPixels(cmyk_view,0,y,cmyk_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
for (x=0; x < (ssize_t) images->columns; x++)
{
Quantum
pixel;
pixel=QuantumRange-GetPixelIntensity(images,p);
switch (i)
{
case 0: SetPixelCyan(cmyk_image,pixel,q); break;
case 1: SetPixelMagenta(cmyk_image,pixel,q); break;
case 2: SetPixelYellow(cmyk_image,pixel,q); break;
case 3: SetPixelBlack(cmyk_image,pixel,q); break;
default: break;
}
p+=GetPixelChannels(images);
q+=GetPixelChannels(cmyk_image);
}
if (SyncCacheViewAuthenticPixels(cmyk_view,exception) == MagickFalse)
break;
}
cmyk_view=DestroyCacheView(cmyk_view);
image_view=DestroyCacheView(image_view);
images=GetNextImageInList(images);
if (images == (Image *) NULL)
break;
}
AppendImageToList(&cmyk_images,cmyk_image);
}
return(cmyk_images);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C r o p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CropImage() extracts a region of the image starting at the offset defined
% by geometry. Region must be fully defined, and no special handling of
% geometry flags is performed.
%
% The format of the CropImage method is:
%
% Image *CropImage(const Image *image,const RectangleInfo *geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o geometry: Define the region of the image to crop with members
% x, y, width, and height.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CropImage(const Image *image,const RectangleInfo *geometry,
ExceptionInfo *exception)
{
#define CropImageTag "Crop/Image"
CacheView
*crop_view,
*image_view;
Image
*crop_image;
MagickBooleanType
status;
MagickOffsetType
progress;
OffsetInfo
offset;
RectangleInfo
bounding_box,
page;
ssize_t
y;
/*
Check crop geometry.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
bounding_box=image->page;
if ((bounding_box.width == 0) || (bounding_box.height == 0))
{
bounding_box.width=image->columns;
bounding_box.height=image->rows;
}
page=(*geometry);
if (page.width == 0)
page.width=bounding_box.width;
if (page.height == 0)
page.height=bounding_box.height;
if (((bounding_box.x-page.x) >= (ssize_t) page.width) ||
((bounding_box.y-page.y) >= (ssize_t) page.height) ||
((page.x-bounding_box.x) > (ssize_t) image->columns) ||
((page.y-bounding_box.y) > (ssize_t) image->rows))
{
/*
Crop is not within virtual canvas, return 1 pixel transparent image.
*/
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"GeometryDoesNotContainImage","`%s'",image->filename);
crop_image=CloneImage(image,1,1,MagickTrue,exception);
if (crop_image == (Image *) NULL)
return((Image *) NULL);
crop_image->background_color.alpha=(Quantum) TransparentAlpha;
crop_image->alpha_trait=BlendPixelTrait;
(void) SetImageBackgroundColor(crop_image,exception);
crop_image->page=bounding_box;
crop_image->page.x=(-1);
crop_image->page.y=(-1);
if (crop_image->dispose == BackgroundDispose)
crop_image->dispose=NoneDispose;
return(crop_image);
}
if ((page.x < 0) && (bounding_box.x >= 0))
{
page.width+=page.x-bounding_box.x;
page.x=0;
}
else
{
page.width-=bounding_box.x-page.x;
page.x-=bounding_box.x;
if (page.x < 0)
page.x=0;
}
if ((page.y < 0) && (bounding_box.y >= 0))
{
page.height+=page.y-bounding_box.y;
page.y=0;
}
else
{
page.height-=bounding_box.y-page.y;
page.y-=bounding_box.y;
if (page.y < 0)
page.y=0;
}
if ((page.x+(ssize_t) page.width) > (ssize_t) image->columns)
page.width=image->columns-page.x;
if ((geometry->width != 0) && (page.width > geometry->width))
page.width=geometry->width;
if ((page.y+(ssize_t) page.height) > (ssize_t) image->rows)
page.height=image->rows-page.y;
if ((geometry->height != 0) && (page.height > geometry->height))
page.height=geometry->height;
bounding_box.x+=page.x;
bounding_box.y+=page.y;
if ((page.width == 0) || (page.height == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"GeometryDoesNotContainImage","`%s'",image->filename);
return((Image *) NULL);
}
/*
Initialize crop image attributes.
*/
crop_image=CloneImage(image,page.width,page.height,MagickTrue,exception);
if (crop_image == (Image *) NULL)
return((Image *) NULL);
crop_image->page.width=image->page.width;
crop_image->page.height=image->page.height;
offset.x=(ssize_t) (bounding_box.x+bounding_box.width);
offset.y=(ssize_t) (bounding_box.y+bounding_box.height);
if ((offset.x > (ssize_t) image->page.width) ||
(offset.y > (ssize_t) image->page.height))
{
crop_image->page.width=bounding_box.width;
crop_image->page.height=bounding_box.height;
}
crop_image->page.x=bounding_box.x;
crop_image->page.y=bounding_box.y;
/*
Crop image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
crop_view=AcquireAuthenticCacheView(crop_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,crop_image,1,1)
#endif
for (y=0; y < (ssize_t) crop_image->rows; y++)
{
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,page.x,page.y+y,crop_image->columns,
1,exception);
q=QueueCacheViewAuthenticPixels(crop_view,0,y,crop_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) crop_image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(crop_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(crop_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait crop_traits=GetPixelChannelTraits(crop_image,channel);
if ((traits == UndefinedPixelTrait) ||
(crop_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(crop_image,channel,p[i],q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(crop_image);
}
if (SyncCacheViewAuthenticPixels(crop_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_CropImage)
#endif
proceed=SetImageProgress(image,CropImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
crop_view=DestroyCacheView(crop_view);
image_view=DestroyCacheView(image_view);
crop_image->type=image->type;
if (status == MagickFalse)
crop_image=DestroyImage(crop_image);
return(crop_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C r o p I m a g e T o T i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CropImageToTiles() crops a single image, into a possible list of tiles.
% This may include a single sub-region of the image. This basically applies
% all the normal geometry flags for Crop.
%
% Image *CropImageToTiles(const Image *image,
% const RectangleInfo *crop_geometry, ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image The transformed image is returned as this parameter.
%
% o crop_geometry: A crop geometry string.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double MagickRound(double x)
{
/*
Round the fraction to nearest integer.
*/
if ((x-floor(x)) < (ceil(x)-x))
return(floor(x));
return(ceil(x));
}
MagickExport Image *CropImageToTiles(const Image *image,
const char *crop_geometry,ExceptionInfo *exception)
{
Image
*next,
*crop_image;
MagickStatusType
flags;
RectangleInfo
geometry;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
crop_image=NewImageList();
next=NewImageList();
flags=ParseGravityGeometry(image,crop_geometry,&geometry,exception);
if ((flags & AreaValue) != 0)
{
PointInfo
delta,
offset;
RectangleInfo
crop;
size_t
height,
width;
/*
Crop into NxM tiles (@ flag).
*/
width=image->columns;
height=image->rows;
if (geometry.width == 0)
geometry.width=1;
if (geometry.height == 0)
geometry.height=1;
if ((flags & AspectValue) == 0)
{
width-=(geometry.x < 0 ? -1 : 1)*geometry.x;
height-=(geometry.y < 0 ? -1 : 1)*geometry.y;
}
else
{
width+=(geometry.x < 0 ? -1 : 1)*geometry.x;
height+=(geometry.y < 0 ? -1 : 1)*geometry.y;
}
delta.x=(double) width/geometry.width;
delta.y=(double) height/geometry.height;
if (delta.x < 1.0)
delta.x=1.0;
if (delta.y < 1.0)
delta.y=1.0;
for (offset.y=0; offset.y < (double) height; )
{
if ((flags & AspectValue) == 0)
{
crop.y=(ssize_t) MagickRound((double) (offset.y-
(geometry.y > 0 ? 0 : geometry.y)));
offset.y+=delta.y; /* increment now to find width */
crop.height=(size_t) MagickRound((double) (offset.y+
(geometry.y < 0 ? 0 : geometry.y)));
}
else
{
crop.y=(ssize_t) MagickRound((double) (offset.y-
(geometry.y > 0 ? geometry.y : 0)));
offset.y+=delta.y; /* increment now to find width */
crop.height=(size_t) MagickRound((double)
(offset.y+(geometry.y < -1 ? geometry.y : 0)));
}
crop.height-=crop.y;
crop.y+=image->page.y;
for (offset.x=0; offset.x < (double) width; )
{
if ((flags & AspectValue) == 0)
{
crop.x=(ssize_t) MagickRound((double) (offset.x-
(geometry.x > 0 ? 0 : geometry.x)));
offset.x+=delta.x; /* increment now to find height */
crop.width=(size_t) MagickRound((double) (offset.x+
(geometry.x < 0 ? 0 : geometry.x)));
}
else
{
crop.x=(ssize_t) MagickRound((double) (offset.x-
(geometry.x > 0 ? geometry.x : 0)));
offset.x+=delta.x; /* increment now to find height */
crop.width=(size_t) MagickRound((double) (offset.x+
(geometry.x < 0 ? geometry.x : 0)));
}
crop.width-=crop.x;
crop.x+=image->page.x;
next=CropImage(image,&crop,exception);
if (next != (Image *) NULL)
AppendImageToList(&crop_image,next);
}
}
ClearMagickException(exception);
return(crop_image);
}
if (((geometry.width == 0) && (geometry.height == 0)) ||
((flags & XValue) != 0) || ((flags & YValue) != 0))
{
/*
Crop a single region at +X+Y.
*/
crop_image=CropImage(image,&geometry,exception);
if ((crop_image != (Image *) NULL) && ((flags & AspectValue) != 0))
{
crop_image->page.width=geometry.width;
crop_image->page.height=geometry.height;
crop_image->page.x-=geometry.x;
crop_image->page.y-=geometry.y;
}
return(crop_image);
}
if ((image->columns > geometry.width) || (image->rows > geometry.height))
{
RectangleInfo
page;
size_t
height,
width;
ssize_t
x,
y;
/*
Crop into tiles of fixed size WxH.
*/
page=image->page;
if (page.width == 0)
page.width=image->columns;
if (page.height == 0)
page.height=image->rows;
width=geometry.width;
if (width == 0)
width=page.width;
height=geometry.height;
if (height == 0)
height=page.height;
next=NewImageList();
for (y=0; y < (ssize_t) page.height; y+=(ssize_t) height)
{
for (x=0; x < (ssize_t) page.width; x+=(ssize_t) width)
{
geometry.width=width;
geometry.height=height;
geometry.x=x;
geometry.y=y;
next=CropImage(image,&geometry,exception);
if (next == (Image *) NULL)
break;
AppendImageToList(&crop_image,next);
}
if (next == (Image *) NULL)
break;
}
return(crop_image);
}
return(CloneImage(image,0,0,MagickTrue,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E x c e r p t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ExcerptImage() returns a excerpt of the image as defined by the geometry.
%
% The format of the ExcerptImage method is:
%
% Image *ExcerptImage(const Image *image,const RectangleInfo *geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o geometry: Define the region of the image to extend with members
% x, y, width, and height.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ExcerptImage(const Image *image,
const RectangleInfo *geometry,ExceptionInfo *exception)
{
#define ExcerptImageTag "Excerpt/Image"
CacheView
*excerpt_view,
*image_view;
Image
*excerpt_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Allocate excerpt image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
excerpt_image=CloneImage(image,geometry->width,geometry->height,MagickTrue,
exception);
if (excerpt_image == (Image *) NULL)
return((Image *) NULL);
/*
Excerpt each row.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
excerpt_view=AcquireAuthenticCacheView(excerpt_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,excerpt_image,excerpt_image->rows,1)
#endif
for (y=0; y < (ssize_t) excerpt_image->rows; y++)
{
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,geometry->x,geometry->y+y,
geometry->width,1,exception);
q=GetCacheViewAuthenticPixels(excerpt_view,0,y,excerpt_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) excerpt_image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(excerpt_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(excerpt_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait excerpt_traits=GetPixelChannelTraits(excerpt_image,channel);
if ((traits == UndefinedPixelTrait) ||
(excerpt_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(excerpt_image,channel,p[i],q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(excerpt_image);
}
if (SyncCacheViewAuthenticPixels(excerpt_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ExcerptImage)
#endif
proceed=SetImageProgress(image,ExcerptImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
excerpt_view=DestroyCacheView(excerpt_view);
image_view=DestroyCacheView(image_view);
excerpt_image->type=image->type;
if (status == MagickFalse)
excerpt_image=DestroyImage(excerpt_image);
return(excerpt_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E x t e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ExtentImage() extends the image as defined by the geometry, gravity, and
% image background color. Set the (x,y) offset of the geometry to move the
% original image relative to the extended image.
%
% The format of the ExtentImage method is:
%
% Image *ExtentImage(const Image *image,const RectangleInfo *geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o geometry: Define the region of the image to extend with members
% x, y, width, and height.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ExtentImage(const Image *image,
const RectangleInfo *geometry,ExceptionInfo *exception)
{
Image
*extent_image;
/*
Allocate extent image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if ((image->columns == geometry->width) &&
(image->rows == geometry->height) &&
(geometry->x == 0) && (geometry->y == 0))
return(CloneImage(image,0,0,MagickTrue,exception));
extent_image=CloneImage(image,geometry->width,geometry->height,MagickTrue,
exception);
if (extent_image == (Image *) NULL)
return((Image *) NULL);
(void) SetImageBackgroundColor(extent_image,exception);
(void) CompositeImage(extent_image,image,image->compose,MagickTrue,
-geometry->x,-geometry->y,exception);
return(extent_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F l i p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FlipImage() creates a vertical mirror image by reflecting the pixels
% around the central x-axis.
%
% The format of the FlipImage method is:
%
% Image *FlipImage(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 *FlipImage(const Image *image,ExceptionInfo *exception)
{
#define FlipImageTag "Flip/Image"
CacheView
*flip_view,
*image_view;
Image
*flip_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
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);
flip_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (flip_image == (Image *) NULL)
return((Image *) NULL);
/*
Flip image.
*/
status=MagickTrue;
progress=0;
page=image->page;
image_view=AcquireVirtualCacheView(image,exception);
flip_view=AcquireAuthenticCacheView(flip_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,flip_image,1,1)
#endif
for (y=0; y < (ssize_t) flip_image->rows; y++)
{
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(flip_view,0,(ssize_t) (flip_image->rows-y-
1),flip_image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) flip_image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(flip_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(flip_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait flip_traits=GetPixelChannelTraits(flip_image,channel);
if ((traits == UndefinedPixelTrait) ||
(flip_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(flip_image,channel,p[i],q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(flip_image);
}
if (SyncCacheViewAuthenticPixels(flip_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_FlipImage)
#endif
proceed=SetImageProgress(image,FlipImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
flip_view=DestroyCacheView(flip_view);
image_view=DestroyCacheView(image_view);
flip_image->type=image->type;
if (page.height != 0)
page.y=(ssize_t) (page.height-flip_image->rows-page.y);
flip_image->page=page;
if (status == MagickFalse)
flip_image=DestroyImage(flip_image);
return(flip_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F l o p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FlopImage() creates a horizontal mirror image by reflecting the pixels
% around the central y-axis.
%
% The format of the FlopImage method is:
%
% Image *FlopImage(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 *FlopImage(const Image *image,ExceptionInfo *exception)
{
#define FlopImageTag "Flop/Image"
CacheView
*flop_view,
*image_view;
Image
*flop_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
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);
flop_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (flop_image == (Image *) NULL)
return((Image *) NULL);
/*
Flop each row.
*/
status=MagickTrue;
progress=0;
page=image->page;
image_view=AcquireVirtualCacheView(image,exception);
flop_view=AcquireAuthenticCacheView(flop_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,flop_image,1,1)
#endif
for (y=0; y < (ssize_t) flop_image->rows; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(flop_view,0,y,flop_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
q+=GetPixelChannels(flop_image)*flop_image->columns;
for (x=0; x < (ssize_t) flop_image->columns; x++)
{
register ssize_t
i;
q-=GetPixelChannels(flop_image);
if (GetPixelReadMask(image,p) == 0)
{
p+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait flop_traits=GetPixelChannelTraits(flop_image,channel);
if ((traits == UndefinedPixelTrait) ||
(flop_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(flop_image,channel,p[i],q);
}
p+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(flop_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_FlopImage)
#endif
proceed=SetImageProgress(image,FlopImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
flop_view=DestroyCacheView(flop_view);
image_view=DestroyCacheView(image_view);
flop_image->type=image->type;
if (page.width != 0)
page.x=(ssize_t) (page.width-flop_image->columns-page.x);
flop_image->page=page;
if (status == MagickFalse)
flop_image=DestroyImage(flop_image);
return(flop_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R o l l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RollImage() offsets an image as defined by x_offset and y_offset.
%
% The format of the RollImage method is:
%
% Image *RollImage(const Image *image,const ssize_t x_offset,
% const ssize_t y_offset,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x_offset: the number of columns to roll in the horizontal direction.
%
% o y_offset: the number of rows to roll in the vertical direction.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType CopyImageRegion(Image *destination,const Image *source, const size_t columns,const size_t rows,const ssize_t sx,const ssize_t sy,
const ssize_t dx,const ssize_t dy,ExceptionInfo *exception)
{
CacheView
*source_view,
*destination_view;
MagickBooleanType
status;
ssize_t
y;
if (columns == 0)
return(MagickTrue);
status=MagickTrue;
source_view=AcquireVirtualCacheView(source,exception);
destination_view=AcquireAuthenticCacheView(destination,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(source,destination,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
MagickBooleanType
sync;
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
/*
Transfer scanline.
*/
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(source_view,sx,sy+y,columns,1,exception);
q=GetCacheViewAuthenticPixels(destination_view,dx,dy+y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(source,p) == 0)
{
SetPixelBackgoundColor(destination,q);
p+=GetPixelChannels(source);
q+=GetPixelChannels(destination);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(source); i++)
{
PixelChannel channel=GetPixelChannelChannel(source,i);
PixelTrait source_traits=GetPixelChannelTraits(source,channel);
PixelTrait destination_traits=GetPixelChannelTraits(destination,
channel);
if ((source_traits == UndefinedPixelTrait) ||
(destination_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(destination,channel,p[i],q);
}
p+=GetPixelChannels(source);
q+=GetPixelChannels(destination);
}
sync=SyncCacheViewAuthenticPixels(destination_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
destination_view=DestroyCacheView(destination_view);
source_view=DestroyCacheView(source_view);
return(status);
}
MagickExport Image *RollImage(const Image *image,const ssize_t x_offset,
const ssize_t y_offset,ExceptionInfo *exception)
{
#define RollImageTag "Roll/Image"
Image
*roll_image;
MagickStatusType
status;
RectangleInfo
offset;
/*
Initialize roll 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);
roll_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (roll_image == (Image *) NULL)
return((Image *) NULL);
offset.x=x_offset;
offset.y=y_offset;
while (offset.x < 0)
offset.x+=(ssize_t) image->columns;
while (offset.x >= (ssize_t) image->columns)
offset.x-=(ssize_t) image->columns;
while (offset.y < 0)
offset.y+=(ssize_t) image->rows;
while (offset.y >= (ssize_t) image->rows)
offset.y-=(ssize_t) image->rows;
/*
Roll image.
*/
status=CopyImageRegion(roll_image,image,(size_t) offset.x,
(size_t) offset.y,(ssize_t) image->columns-offset.x,(ssize_t) image->rows-
offset.y,0,0,exception);
(void) SetImageProgress(image,RollImageTag,0,3);
status&=CopyImageRegion(roll_image,image,image->columns-offset.x,
(size_t) offset.y,0,(ssize_t) image->rows-offset.y,offset.x,0,
exception);
(void) SetImageProgress(image,RollImageTag,1,3);
status&=CopyImageRegion(roll_image,image,(size_t) offset.x,image->rows-
offset.y,(ssize_t) image->columns-offset.x,0,0,offset.y,exception);
(void) SetImageProgress(image,RollImageTag,2,3);
status&=CopyImageRegion(roll_image,image,image->columns-offset.x,image->rows-
offset.y,0,0,offset.x,offset.y,exception);
(void) SetImageProgress(image,RollImageTag,3,3);
roll_image->type=image->type;
if (status == MagickFalse)
roll_image=DestroyImage(roll_image);
return(roll_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S h a v e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ShaveImage() shaves pixels from the image edges. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% The format of the ShaveImage method is:
%
% Image *ShaveImage(const Image *image,const RectangleInfo *shave_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o shave_image: Method ShaveImage returns a pointer to the shaved
% image. A null image is returned if there is a memory shortage or
% if the image width or height is zero.
%
% o image: the image.
%
% o shave_info: Specifies a pointer to a RectangleInfo which defines the
% region of the image to crop.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ShaveImage(const Image *image,
const RectangleInfo *shave_info,ExceptionInfo *exception)
{
Image
*shave_image;
RectangleInfo
geometry;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (((2*shave_info->width) >= image->columns) ||
((2*shave_info->height) >= image->rows))
ThrowImageException(OptionWarning,"GeometryDoesNotContainImage");
SetGeometry(image,&geometry);
geometry.width-=2*shave_info->width;
geometry.height-=2*shave_info->height;
geometry.x=(ssize_t) shave_info->width+image->page.x;
geometry.y=(ssize_t) shave_info->height+image->page.y;
shave_image=CropImage(image,&geometry,exception);
if (shave_image == (Image *) NULL)
return((Image *) NULL);
shave_image->page.width-=2*shave_info->width;
shave_image->page.height-=2*shave_info->height;
shave_image->page.x-=(ssize_t) shave_info->width;
shave_image->page.y-=(ssize_t) shave_info->height;
return(shave_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S p l i c e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SpliceImage() splices a solid color into the image as defined by the
% geometry.
%
% The format of the SpliceImage method is:
%
% Image *SpliceImage(const Image *image,const RectangleInfo *geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o geometry: Define the region of the image to splice with members
% x, y, width, and height.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SpliceImage(const Image *image,
const RectangleInfo *geometry,ExceptionInfo *exception)
{
#define SpliceImageTag "Splice/Image"
CacheView
*image_view,
*splice_view;
Image
*splice_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
splice_geometry;
ssize_t
columns,
y;
/*
Allocate splice image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
splice_geometry=(*geometry);
splice_image=CloneImage(image,image->columns+splice_geometry.width,
image->rows+splice_geometry.height,MagickTrue,exception);
if (splice_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(splice_image,DirectClass,exception) == MagickFalse)
{
splice_image=DestroyImage(splice_image);
return((Image *) NULL);
}
if ((IsPixelInfoGray(&splice_image->background_color) == MagickFalse) &&
(IsGrayColorspace(splice_image->colorspace) != MagickFalse))
(void) SetImageColorspace(splice_image,sRGBColorspace,exception);
if ((splice_image->background_color.alpha_trait != UndefinedPixelTrait) &&
(splice_image->alpha_trait == UndefinedPixelTrait))
(void) SetImageAlpha(splice_image,OpaqueAlpha,exception);
(void) SetImageBackgroundColor(splice_image,exception);
/*
Respect image geometry.
*/
switch (image->gravity)
{
default:
case UndefinedGravity:
case NorthWestGravity:
break;
case NorthGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
break;
}
case NorthEastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
break;
}
case WestGravity:
{
splice_geometry.y+=(ssize_t) splice_geometry.width/2;
break;
}
case CenterGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
splice_geometry.y+=(ssize_t) splice_geometry.height/2;
break;
}
case EastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
splice_geometry.y+=(ssize_t) splice_geometry.height/2;
break;
}
case SouthWestGravity:
{
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
case SouthGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
case SouthEastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
}
/*
Splice image.
*/
status=MagickTrue;
progress=0;
columns=MagickMin(splice_geometry.x,(ssize_t) splice_image->columns);
image_view=AcquireVirtualCacheView(image,exception);
splice_view=AcquireAuthenticCacheView(splice_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,splice_image,1,1)
#endif
for (y=0; y < (ssize_t) splice_geometry.y; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,splice_image->columns,1,
exception);
q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++)
q+=GetPixelChannels(splice_image);
for ( ; x < (ssize_t) splice_image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransposeImage)
#endif
proceed=SetImageProgress(image,SpliceImageTag,progress++,
splice_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,splice_image,1,1)
#endif
for (y=(ssize_t) (splice_geometry.y+splice_geometry.height);
y < (ssize_t) splice_image->rows; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
if ((y < 0) || (y >= (ssize_t)splice_image->rows))
continue;
p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height,
splice_image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++)
q+=GetPixelChannels(splice_image);
for ( ; x < (ssize_t) splice_image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransposeImage)
#endif
proceed=SetImageProgress(image,SpliceImageTag,progress++,
splice_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
splice_view=DestroyCacheView(splice_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
splice_image=DestroyImage(splice_image);
return(splice_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransformImage() is a convenience method that behaves like ResizeImage() or
% CropImage() but accepts scaling and/or cropping information as a region
% geometry specification. If the operation fails, the original image handle
% is left as is.
%
% This should only be used for single images.
%
% This function destroys what it assumes to be a single image list.
% If the input image is part of a larger list, all other images in that list
% will be simply 'lost', not destroyed.
%
% Also if the crop generates a list of images only the first image is resized.
% And finally if the crop succeeds and the resize failed, you will get a
% cropped image, as well as a 'false' or 'failed' report.
%
% This function and should probably be deprecated in favor of direct calls
% to CropImageToTiles() or ResizeImage(), as appropriate.
%
% The format of the TransformImage method is:
%
% MagickBooleanType TransformImage(Image **image,const char *crop_geometry,
% const char *image_geometry,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image The transformed image is returned as this parameter.
%
% o crop_geometry: A crop geometry string. This geometry defines a
% subregion of the image to crop.
%
% o image_geometry: An image geometry string. This geometry defines the
% final size of the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType TransformImage(Image **image,
const char *crop_geometry,const char *image_geometry,ExceptionInfo *exception)
{
Image
*resize_image,
*transform_image;
MagickStatusType
flags;
RectangleInfo
geometry;
assert(image != (Image **) NULL);
assert((*image)->signature == MagickCoreSignature);
if ((*image)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename);
transform_image=(*image);
if (crop_geometry != (const char *) NULL)
{
Image
*crop_image;
/*
Crop image to a user specified size.
*/
crop_image=CropImageToTiles(*image,crop_geometry,exception);
if (crop_image == (Image *) NULL)
transform_image=CloneImage(*image,0,0,MagickTrue,exception);
else
{
transform_image=DestroyImage(transform_image);
transform_image=GetFirstImageInList(crop_image);
}
*image=transform_image;
}
if (image_geometry == (const char *) NULL)
return(MagickTrue);
/*
Scale image to a user specified size.
*/
flags=ParseRegionGeometry(transform_image,image_geometry,&geometry,exception);
(void) flags;
if ((transform_image->columns == geometry.width) &&
(transform_image->rows == geometry.height))
return(MagickTrue);
resize_image=ResizeImage(transform_image,geometry.width,geometry.height,
transform_image->filter,exception);
if (resize_image == (Image *) NULL)
return(MagickFalse);
transform_image=DestroyImage(transform_image);
transform_image=resize_image;
*image=transform_image;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s f o r m I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransformImages() calls TransformImage() on each image of a sequence.
%
% The format of the TransformImage method is:
%
% MagickBooleanType TransformImages(Image **image,
% const char *crop_geometry,const char *image_geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image The transformed image is returned as this parameter.
%
% o crop_geometry: A crop geometry string. This geometry defines a
% subregion of the image to crop.
%
% o image_geometry: An image geometry string. This geometry defines the
% final size of the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType TransformImages(Image **images,
const char *crop_geometry,const char *image_geometry,ExceptionInfo *exception)
{
Image
*image,
**image_list,
*transform_images;
MagickStatusType
status;
register ssize_t
i;
assert(images != (Image **) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
(*images)->filename);
image_list=ImageListToArray(*images,exception);
if (image_list == (Image **) NULL)
return(MagickFalse);
status=MagickTrue;
transform_images=NewImageList();
for (i=0; image_list[i] != (Image *) NULL; i++)
{
image=image_list[i];
status&=TransformImage(&image,crop_geometry,image_geometry,exception);
AppendImageToList(&transform_images,image);
}
*images=transform_images;
image_list=(Image **) RelinquishMagickMemory(image_list);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s p o s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransposeImage() creates a horizontal mirror image by reflecting the pixels
% around the central y-axis while rotating them by 90 degrees.
%
% The format of the TransposeImage method is:
%
% Image *TransposeImage(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 *TransposeImage(const Image *image,ExceptionInfo *exception)
{
#define TransposeImageTag "Transpose/Image"
CacheView
*image_view,
*transpose_view;
Image
*transpose_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
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);
transpose_image=CloneImage(image,image->rows,image->columns,MagickTrue,
exception);
if (transpose_image == (Image *) NULL)
return((Image *) NULL);
/*
Transpose image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
transpose_view=AcquireAuthenticCacheView(transpose_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,transpose_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,(ssize_t) image->rows-y-1,
image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(transpose_view,(ssize_t) (image->rows-y-1),
0,1,transpose_image->rows,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
SetPixelBackgoundColor(transpose_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(transpose_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait transpose_traits=GetPixelChannelTraits(transpose_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(transpose_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(transpose_image,channel,p[i],q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(transpose_image);
}
if (SyncCacheViewAuthenticPixels(transpose_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransposeImage)
#endif
proceed=SetImageProgress(image,TransposeImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
transpose_view=DestroyCacheView(transpose_view);
image_view=DestroyCacheView(image_view);
transpose_image->type=image->type;
page=transpose_image->page;
Swap(page.width,page.height);
Swap(page.x,page.y);
transpose_image->page=page;
if (status == MagickFalse)
transpose_image=DestroyImage(transpose_image);
return(transpose_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s v e r s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransverseImage() creates a vertical mirror image by reflecting the pixels
% around the central x-axis while rotating them by 270 degrees.
%
% The format of the TransverseImage method is:
%
% Image *TransverseImage(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 *TransverseImage(const Image *image,ExceptionInfo *exception)
{
#define TransverseImageTag "Transverse/Image"
CacheView
*image_view,
*transverse_view;
Image
*transverse_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
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);
transverse_image=CloneImage(image,image->rows,image->columns,MagickTrue,
exception);
if (transverse_image == (Image *) NULL)
return((Image *) NULL);
/*
Transverse image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
transverse_view=AcquireAuthenticCacheView(transverse_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,transverse_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(transverse_view,(ssize_t) (image->rows-y-1),
0,1,transverse_image->rows,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
q+=GetPixelChannels(transverse_image)*image->columns;
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
q-=GetPixelChannels(transverse_image);
if (GetPixelReadMask(image,p) == 0)
{
p+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait transverse_traits=GetPixelChannelTraits(transverse_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(transverse_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(transverse_image,channel,p[i],q);
}
p+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(transverse_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransverseImage)
#endif
proceed=SetImageProgress(image,TransverseImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
transverse_view=DestroyCacheView(transverse_view);
image_view=DestroyCacheView(image_view);
transverse_image->type=image->type;
page=transverse_image->page;
Swap(page.width,page.height);
Swap(page.x,page.y);
if (page.width != 0)
page.x=(ssize_t) (page.width-transverse_image->columns-page.x);
if (page.height != 0)
page.y=(ssize_t) (page.height-transverse_image->rows-page.y);
transverse_image->page=page;
if (status == MagickFalse)
transverse_image=DestroyImage(transverse_image);
return(transverse_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r i m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TrimImage() trims pixels from the image edges. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% The format of the TrimImage method is:
%
% Image *TrimImage(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 *TrimImage(const Image *image,ExceptionInfo *exception)
{
RectangleInfo
geometry;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
geometry=GetImageBoundingBox(image,exception);
if ((geometry.width == 0) || (geometry.height == 0))
{
Image
*crop_image;
crop_image=CloneImage(image,1,1,MagickTrue,exception);
if (crop_image == (Image *) NULL)
return((Image *) NULL);
crop_image->background_color.alpha=(Quantum) TransparentAlpha;
crop_image->alpha_trait=BlendPixelTrait;
(void) SetImageBackgroundColor(crop_image,exception);
crop_image->page=image->page;
crop_image->page.x=(-1);
crop_image->page.y=(-1);
return(crop_image);
}
geometry.x+=image->page.x;
geometry.y+=image->page.y;
return(CropImage(image,&geometry,exception));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1835_0 |
crossvul-cpp_data_good_1280_0 | /*
* This file includes functions to transform a concrete syntax tree (CST) to
* an abstract syntax tree (AST). The main function is PyAST_FromNode().
*
*/
#include "Python.h"
#include "Python-ast.h"
#include "node.h"
#include "ast.h"
#include "token.h"
#include "pythonrun.h"
#include <assert.h>
#include <stdbool.h>
#define MAXLEVEL 200 /* Max parentheses level */
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);
static int
validate_comprehension(asdl_seq *gens)
{
Py_ssize_t 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: {
Py_ssize_t 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)
{
Py_ssize_t 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)
{
Py_ssize_t 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:
Py_UNREACHABLE();
}
}
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 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 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);
case NamedExpr_kind:
return validate_expr(exp->v.NamedExpr.value, Load);
/* This last case doesn't have any checking. */
case Name_kind:
return 1;
}
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)
{
Py_ssize_t 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)
{
Py_ssize_t 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)
{
Py_ssize_t 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
PyAST_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 minor 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,
const node *, const node *);
static PyObject *parsenumber(struct compiling *, const char *);
static expr_ty parsestrplus(struct compiling *, const node *n);
static void get_last_end_pos(asdl_seq *, int *, int *);
#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;
_Py_IDENTIFIER(NFKC);
if (!c->c_normalize && !init_normalization(c)) {
Py_DECREF(id);
return NULL;
}
PyObject *form = _PyUnicode_FromId(&PyId_NFKC);
if (form == NULL) {
Py_DECREF(id);
return NULL;
}
PyObject *args[2] = {form, 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 int
ast_error(struct compiling *c, const node *n, const char *errmsg, ...)
{
PyObject *value, *errstr, *loc, *tmp;
va_list va;
va_start(va, errmsg);
errstr = PyUnicode_FromFormatV(errmsg, va);
va_end(va);
if (!errstr) {
return 0;
}
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 + 1, loc);
if (!tmp) {
Py_DECREF(errstr);
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 string
new_type_comment(const char *s, struct compiling *c)
{
PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
if (res == NULL)
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
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:
case func_body_suite:
/* func_body_suite: simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] INDENT stmt+ DEDENT */
/* suite: simple_stmt | 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);
}
}
Py_UNREACHABLE();
}
/* Transform the CST rooted at node * to the appropriate AST
*/
mod_ty
PyAST_FromNodeObject(const node *n, PyCompilerFlags *flags,
PyObject *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;
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 = flags->cf_feature_version;
if (TYPE(n) == encoding_decl)
n = CHILD(n, 0);
k = 0;
switch (TYPE(n)) {
case file_input:
stmts = _Py_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 = _Py_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 = _Py_asdl_seq_new(1, arena);
if (!stmts)
goto out;
asdl_seq_SET(stmts, 0, Pass(n->n_lineno, n->n_col_offset,
n->n_end_lineno, n->n_end_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 = _Py_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 = _Py_asdl_seq_new(num, arena);
if (!argtypes)
goto out;
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 = _Py_asdl_seq_new(0, arena);
if (!argtypes)
goto out;
}
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 PyAST_FromNode", TYPE(n));
goto out;
}
out:
if (c.c_normalize) {
Py_DECREF(c.c_normalize);
}
return res;
}
mod_ty
PyAST_FromNode(const node *n, PyCompilerFlags *flags, const char *filename_str,
PyArena *arena)
{
mod_ty mod;
PyObject *filename;
filename = PyUnicode_DecodeFSDefault(filename_str);
if (filename == NULL)
return NULL;
mod = PyAST_FromNodeObject(n, flags, filename, 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",
"__debug__",
NULL,
};
static int
forbidden_name(struct compiling *c, identifier name, const node *n,
int full_checks)
{
assert(PyUnicode_Check(name));
const char * const *p = FORBIDDEN;
if (!full_checks) {
/* In most cases, the parser will protect True, False, and None
from being assign to. */
p += 3;
}
for (; *p; p++) {
if (_PyUnicode_EqualToASCIIString(name, *p)) {
ast_error(c, n, "cannot assign to %U", name);
return 1;
}
}
return 0;
}
static expr_ty
copy_location(expr_ty e, const node *n)
{
if (e) {
e->lineno = LINENO(n);
e->col_offset = n->n_col_offset;
e->end_lineno = n->n_end_lineno;
e->end_col_offset = n->n_end_col_offset;
}
return e;
}
static const char *
get_expr_name(expr_ty e)
{
switch (e->kind) {
case Attribute_kind:
return "attribute";
case Subscript_kind:
return "subscript";
case Starred_kind:
return "starred";
case Name_kind:
return "name";
case List_kind:
return "list";
case Tuple_kind:
return "tuple";
case Lambda_kind:
return "lambda";
case Call_kind:
return "function call";
case BoolOp_kind:
case BinOp_kind:
case UnaryOp_kind:
return "operator";
case GeneratorExp_kind:
return "generator expression";
case Yield_kind:
case YieldFrom_kind:
return "yield expression";
case Await_kind:
return "await expression";
case ListComp_kind:
return "list comprehension";
case SetComp_kind:
return "set comprehension";
case DictComp_kind:
return "dict comprehension";
case Dict_kind:
return "dict display";
case Set_kind:
return "set display";
case JoinedStr_kind:
case FormattedValue_kind:
return "f-string expression";
case Constant_kind: {
PyObject *value = e->v.Constant.value;
if (value == Py_None) {
return "None";
}
if (value == Py_False) {
return "False";
}
if (value == Py_True) {
return "True";
}
if (value == Py_Ellipsis) {
return "Ellipsis";
}
return "literal";
}
case Compare_kind:
return "comparison";
case IfExp_kind:
return "conditional expression";
case NamedExpr_kind:
return "named expression";
default:
PyErr_Format(PyExc_SystemError,
"unexpected expression in assignment %d (line %d)",
e->kind, e->lineno);
return NULL;
}
}
/* 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;
/* 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;
default: {
const char *expr_name = get_expr_name(e);
if (expr_name != NULL) {
ast_error(c, n, "cannot %s %s",
ctx == Store ? "assign to" : "delete",
expr_name);
}
return 0;
}
}
/* If the LHS is a list or tuple, we need to set the assignment
context for all the contained elements.
*/
if (s) {
Py_ssize_t 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 = _Py_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 || TYPE(ch) == namedexpr_test);
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,
n->n_end_lineno, n->n_end_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,
ch->n_end_lineno, ch->n_end_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 ? _Py_asdl_seq_new(nposargs, c->c_arena) : NULL);
if (!posargs && nposargs)
return NULL;
kwonlyargs = (nkwonlyargs ?
_Py_asdl_seq_new(nkwonlyargs, c->c_arena) : NULL);
if (!kwonlyargs && nkwonlyargs)
return NULL;
posdefaults = (nposdefaults ?
_Py_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 ?
_Py_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;
node *ch;
REQ(n, dotted_name);
lineno = LINENO(n);
col_offset = n->n_col_offset;
ch = CHILD(n, 0);
id = NEW_IDENTIFIER(ch);
if (!id)
return NULL;
e = Name(id, Load, lineno, col_offset,
ch->n_end_lineno, ch->n_end_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,
n->n_end_lineno, n->n_end_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, n->n_end_lineno, n->n_end_col_offset, c->c_arena);
if (!d)
return NULL;
name_expr = NULL;
}
else {
d = ast_for_call(c, CHILD(n, 3), name_expr, CHILD(n, 2), CHILD(n, 4));
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 = _Py_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;
int end_lineno, end_col_offset;
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;
get_last_end_pos(body, &end_lineno, &end_col_offset);
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, end_lineno, end_col_offset, c->c_arena);
else
return FunctionDef(name, args, body, decorator_seq, returns, type_comment,
LINENO(n), n->n_col_offset, end_lineno, end_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);
}
return thing;
}
static expr_ty
ast_for_namedexpr(struct compiling *c, const node *n)
{
/* if_stmt: 'if' namedexpr_test ':' suite ('elif' namedexpr_test ':' suite)*
['else' ':' suite]
namedexpr_test: test [':=' test]
argument: ( test [comp_for] |
test ':=' test |
test '=' test |
'**' test |
'*' test )
*/
expr_ty target, value;
target = ast_for_expr(c, CHILD(n, 0));
if (!target)
return NULL;
value = ast_for_expr(c, CHILD(n, 2));
if (!value)
return NULL;
if (target->kind != Name_kind) {
const char *expr_name = get_expr_name(target);
if (expr_name != NULL) {
ast_error(c, n, "cannot use named assignment with %s", expr_name);
}
return NULL;
}
if (!set_context(c, target, Store, n))
return NULL;
return NamedExpr(target, value, LINENO(n), n->n_col_offset, n->n_end_lineno,
n->n_end_col_offset, c->c_arena);
}
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,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_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 = _Py_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,
for_ch->n_end_lineno, for_ch->n_end_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 = _Py_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,
n->n_end_lineno, n->n_end_col_offset, c->c_arena);
else if (type == COMP_LISTCOMP)
return ListComp(elt, comps, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_col_offset, c->c_arena);
else if (type == COMP_SETCOMP)
return SetComp(elt, comps, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_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 = _Py_asdl_seq_new(size, c->c_arena);
if (!keys)
return NULL;
values = _Py_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,
n->n_end_lineno, n->n_end_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 = _Py_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,
n->n_end_lineno, n->n_end_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 Constant(Py_None, NULL, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_col_offset, c->c_arena);
if (!strcmp(s, "True"))
return Constant(Py_True, NULL, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_col_offset, c->c_arena);
if (!strcmp(s, "False"))
return Constant(Py_False, NULL, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_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) {
PyObject *type, *value, *tback, *errstr;
PyErr_Fetch(&type, &value, &tback);
errstr = PyObject_Str(value);
if (errstr) {
ast_error(c, n, "(%s) %U", errtype, errstr);
Py_DECREF(errstr);
}
else {
PyErr_Clear();
ast_error(c, n, "(%s) unknown error", errtype);
}
Py_DECREF(type);
Py_XDECREF(value);
Py_XDECREF(tback);
}
return NULL;
}
return str;
}
case NUMBER: {
PyObject *pynum;
/* 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(STR(ch), '_') != 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 Constant(pynum, NULL, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_col_offset, c->c_arena);
}
case ELLIPSIS: /* Ellipsis */
return Constant(Py_Ellipsis, NULL, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_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) {
return ast_for_testlist(c, ch);
}
if (TYPE(CHILD(ch, 1)) == comp_for) {
return copy_location(ast_for_genexp(c, ch), n);
}
else {
return copy_location(ast_for_testlist(c, ch), n);
}
case LSQB: /* list (or list comprehension) */
ch = CHILD(n, 1);
if (TYPE(ch) == RSQB)
return List(NULL, Load, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_col_offset, c->c_arena);
}
else {
return copy_location(ast_for_listcomp(c, ch), n);
}
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,
n->n_end_lineno, n->n_end_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);
}
return copy_location(res, n);
}
}
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,
CHILD(n, 2)->n_end_lineno, CHILD(n, 2)->n_end_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,
CHILD(n, i * 2 + 2)->n_end_lineno,
CHILD(n, i * 2 + 2)->n_end_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]
*/
const node *n_copy = n;
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,
n->n_end_lineno, n->n_end_col_offset, c->c_arena);
else
return ast_for_call(c, CHILD(n, 1), left_expr, CHILD(n, 0), CHILD(n, 2));
}
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,
n->n_end_lineno, n->n_end_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,
n_copy->n_end_lineno, n_copy->n_end_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.
*/
Py_ssize_t j;
slice_ty slc;
expr_ty e;
int simple = 1;
asdl_seq *slices, *elts;
slices = _Py_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,
n_copy->n_end_lineno, n_copy->n_end_col_offset, c->c_arena);
}
/* extract Index values and put them in a Tuple */
elts = _Py_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,
n->n_end_lineno, n->n_end_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,
n_copy->n_end_lineno, n_copy->n_end_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,
n->n_end_lineno, n->n_end_col_offset,
c->c_arena);
case MINUS:
return UnaryOp(USub, expression, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_col_offset,
c->c_arena);
case TILDE:
return UnaryOp(Invert, expression, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_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
namedexpr_test: test [':=' test]
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 namedexpr_test:
if (NCH(n) == 3)
return ast_for_namedexpr(c, n);
/* Fallthrough */
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 = _Py_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,
n->n_end_lineno, n->n_end_col_offset,
c->c_arena);
assert(!strcmp(STR(CHILD(n, 1)), "or"));
return BoolOp(Or, seq, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_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 = _Py_asdl_int_seq_new(NCH(n) / 2, c->c_arena);
if (!ops)
return NULL;
cmps = _Py_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,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_col_offset, c->c_arena);
return Yield(exp, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_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,
const node *maybegenbeg, const node *closepar)
{
/*
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 (!maybegenbeg) {
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 if (TYPE(CHILD(ch, 1)) == COLONEQUAL) {
nargs++;
}
else
/* TYPE(CHILD(ch, 0)) == DOUBLESTAR or keyword argument */
nkeywords++;
}
}
args = _Py_asdl_seq_new(nargs, c->c_arena);
if (!args)
return NULL;
keywords = _Py_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,
chch->n_end_lineno, chch->n_end_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 = copy_location(ast_for_genexp(c, ch), maybegenbeg);
if (!e)
return NULL;
asdl_seq_SET(args, nargs++, e);
}
else if (TYPE(CHILD(ch, 1)) == COLONEQUAL) {
/* treat colon equal as 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_namedexpr(c, ch);
if (!e)
return NULL;
asdl_seq_SET(args, nargs++, e);
}
else {
/* a keyword argument */
keyword_ty kw;
identifier key, tmp;
int k;
// To remain LL(1), the grammar accepts any test (basically, any
// expression) in the keyword slot of a call site. So, we need
// to manually enforce that the keyword is a NAME here.
static const int name_tree[] = {
test,
or_test,
and_test,
not_test,
comparison,
expr,
xor_expr,
and_expr,
shift_expr,
arith_expr,
term,
factor,
power,
atom_expr,
atom,
0,
};
node *expr_node = chch;
for (int i = 0; name_tree[i]; i++) {
if (TYPE(expr_node) != name_tree[i])
break;
if (NCH(expr_node) != 1)
break;
expr_node = CHILD(expr_node, 0);
}
if (TYPE(expr_node) != NAME) {
ast_error(c, chch,
"expression cannot contain assignment, "
"perhaps you meant \"==\"?");
return NULL;
}
key = new_identifier(STR(expr_node), c);
if (key == NULL) {
return NULL;
}
if (forbidden_name(c, key, chch, 1)) {
return NULL;
}
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,
closepar->n_end_lineno, closepar->n_end_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,
n->n_end_lineno, n->n_end_col_offset, c->c_arena);
}
}
static stmt_ty
ast_for_expr_stmt(struct compiling *c, const node *n)
{
REQ(n, expr_stmt);
/* expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |
[('=' (yield_expr|testlist_star_expr))+ [TYPE_COMMENT]] )
annassign: ':' test ['=' (yield_expr|testlist)]
testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']
augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
'<<=' | '>>=' | '**=' | '//=')
test: ... here starts the operator precedence dance
*/
int num = NCH(n);
if (num == 1) {
expr_ty e = ast_for_testlist(c, CHILD(n, 0));
if (!e)
return NULL;
return Expr(e, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_col_offset, c->c_arena);
}
else {
ch = CHILD(ann, 3);
if (TYPE(ch) == testlist) {
expr3 = ast_for_testlist(c, ch);
}
else {
expr3 = ast_for_expr(c, ch);
}
if (!expr3) {
return NULL;
}
return AnnAssign(expr1, expr2, expr3, simple,
LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_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 = _Py_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,
n->n_end_lineno, n->n_end_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 = _Py_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,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_col_offset, c->c_arena);
case continue_stmt:
return Continue(LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_col_offset, c->c_arena);
}
case return_stmt:
if (NCH(ch) == 1)
return Return(NULL, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_col_offset, c->c_arena);
}
case raise_stmt:
if (NCH(ch) == 1)
return Raise(NULL, NULL, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_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 = _Py_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);
}
// Even though n is modified above, the end position is not changed
return Import(aliases, lineno, col_offset,
n->n_end_lineno, n->n_end_col_offset, c->c_arena);
}
else if (TYPE(n) == import_from) {
int n_children;
int idx, ndots = 0;
const node *n_copy = n;
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 = _Py_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,
n_copy->n_end_lineno, n_copy->n_end_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 = _Py_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,
n->n_end_lineno, n->n_end_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 = _Py_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,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_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,
n->n_end_lineno, n->n_end_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;
if (TYPE(n) != func_body_suite) {
REQ(n, suite);
}
total = num_stmts(n);
seq = _Py_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;
REQ(CHILD(n, 2), NEWLINE);
}
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 void
get_last_end_pos(asdl_seq *s, int *end_lineno, int *end_col_offset)
{
Py_ssize_t tot = asdl_seq_LEN(s);
// There must be no empty suites.
assert(tot > 0);
stmt_ty last = asdl_seq_GET(s, tot - 1);
*end_lineno = last->end_lineno;
*end_col_offset = last->end_col_offset;
}
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;
int end_lineno, end_col_offset;
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;
get_last_end_pos(suite_seq, &end_lineno, &end_col_offset);
return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset,
end_lineno, end_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;
get_last_end_pos(seq2, &end_lineno, &end_col_offset);
return If(expression, seq1, seq2, LINENO(n), n->n_col_offset,
end_lineno, end_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 = _Py_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;
get_last_end_pos(suite_seq2, &end_lineno, &end_col_offset);
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,
end_lineno, end_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 = _Py_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;
if (orelse != NULL) {
get_last_end_pos(orelse, &end_lineno, &end_col_offset);
} else {
get_last_end_pos(suite_seq, &end_lineno, &end_col_offset);
}
asdl_seq_SET(newobj, 0,
If(expression, suite_seq, orelse,
LINENO(CHILD(n, off)),
CHILD(n, off)->n_col_offset,
end_lineno, end_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;
get_last_end_pos(orelse, &end_lineno, &end_col_offset);
return If(expression, suite_seq, orelse,
LINENO(n), n->n_col_offset,
end_lineno, end_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);
int end_lineno, end_col_offset;
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;
get_last_end_pos(suite_seq, &end_lineno, &end_col_offset);
return While(expression, suite_seq, NULL, LINENO(n), n->n_col_offset,
end_lineno, end_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;
get_last_end_pos(seq2, &end_lineno, &end_col_offset);
return While(expression, seq1, seq2, LINENO(n), n->n_col_offset,
end_lineno, end_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 end_lineno, end_col_offset;
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,
node_target->n_end_lineno, node_target->n_end_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 (seq != NULL) {
get_last_end_pos(seq, &end_lineno, &end_col_offset);
} else {
get_last_end_pos(suite_seq, &end_lineno, &end_col_offset);
}
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,
end_lineno, end_col_offset, c->c_arena);
else
return For(target, expression, suite_seq, seq, type_comment,
LINENO(n), n->n_col_offset,
end_lineno, end_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]] */
int end_lineno, end_col_offset;
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;
get_last_end_pos(suite_seq, &end_lineno, &end_col_offset);
return ExceptHandler(NULL, NULL, suite_seq, LINENO(exc),
exc->n_col_offset,
end_lineno, end_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;
get_last_end_pos(suite_seq, &end_lineno, &end_col_offset);
return ExceptHandler(expression, NULL, suite_seq, LINENO(exc),
exc->n_col_offset,
end_lineno, end_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;
get_last_end_pos(suite_seq, &end_lineno, &end_col_offset);
return ExceptHandler(expression, e, suite_seq, LINENO(exc),
exc->n_col_offset,
end_lineno, end_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 end_lineno, end_col_offset, n_except = (nch - 3)/3;
asdl_seq *body, *handlers = NULL, *orelse = NULL, *finally = NULL;
excepthandler_ty last_handler;
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 = _Py_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));
if (finally != NULL) {
// finally is always last
get_last_end_pos(finally, &end_lineno, &end_col_offset);
} else if (orelse != NULL) {
// otherwise else is last
get_last_end_pos(orelse, &end_lineno, &end_col_offset);
} else {
// inline the get_last_end_pos logic due to layout mismatch
last_handler = (excepthandler_ty) asdl_seq_GET(handlers, n_except - 1);
end_lineno = last_handler->end_lineno;
end_col_offset = last_handler->end_col_offset;
}
return Try(body, handlers, orelse, finally, LINENO(n), n->n_col_offset,
end_lineno, end_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, end_lineno, end_col_offset;
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 = _Py_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;
get_last_end_pos(body, &end_lineno, &end_col_offset);
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,
end_lineno, end_col_offset, c->c_arena);
else
return With(items, body, type_comment, LINENO(n), n->n_col_offset,
end_lineno, end_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;
int end_lineno, end_col_offset;
REQ(n, classdef);
if (NCH(n) == 4) { /* class NAME ':' suite */
s = ast_for_suite(c, CHILD(n, 3));
if (!s)
return NULL;
get_last_end_pos(s, &end_lineno, &end_col_offset);
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,
end_lineno, end_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;
get_last_end_pos(s, &end_lineno, &end_col_offset);
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,
end_lineno, end_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,
CHILD(n, 1)->n_end_lineno, CHILD(n, 1)->n_end_col_offset,
c->c_arena);
call = ast_for_call(c, CHILD(n, 3), dummy, NULL, CHILD(n, 4));
if (!call)
return NULL;
}
s = ast_for_suite(c, CHILD(n, 6));
if (!s)
return NULL;
get_last_end_pos(s, &end_lineno, &end_col_offset);
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,
end_lineno, end_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,
n->n_end_lineno, n->n_end_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 compound_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_SyntaxWarning, msg,
c->c_filename, LINENO(n),
NULL, NULL) < 0)
{
if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
/* Replace the SyntaxWarning exception with a SyntaxError
to get a more accurate error report */
PyErr_Clear();
ast_error(c, n, "%U", msg);
}
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;
/* 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;
const char *first_invalid_escape;
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)
{
n->n_col_offset = n->n_col_offset + col_offset;
n->n_end_col_offset = n->n_end_col_offset + col_offset;
for (int 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;
n->n_end_lineno = n->n_end_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 += (int)(substr - start);
/* adjust the start based on the number of newlines encountered
before the f-string expression */
for (char* p = parent->n_str; p < substr; p++) {
if (*p == '\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;
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;
cf.cf_feature_version = PY_MINOR_VERSION;
mod_n = PyParser_SimpleParseStringFlagsFilename(str, "<fstring>",
Py_eval_input, 0);
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 = PyAST_FromNode(mod_n, &cf, "<fstring>", c->c_arena);
PyMem_RawFree(str);
PyNode_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;
char parenstack[MAXLEVEL];
/* 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 == '(') {
if (nested_depth >= MAXLEVEL) {
ast_error(c, n, "f-string: too many nested parenthesis");
return -1;
}
parenstack[nested_depth] = 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 if (ch == ']' || ch == '}' || ch == ')') {
if (!nested_depth) {
ast_error(c, n, "f-string: unmatched '%c'", ch);
return -1;
}
nested_depth--;
int opening = parenstack[nested_depth];
if (!((opening == '(' && ch == ')') ||
(opening == '[' && ch == ']') ||
(opening == '{' && ch == '}')))
{
ast_error(c, n,
"f-string: closing parenthesis '%c' "
"does not match opening parenthesis '%c'",
ch, opening);
return -1;
}
} 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) {
int opening = parenstack[nested_depth - 1];
ast_error(c, n, "f-string: unmatched '%c'", opening);
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,
n->n_end_lineno, n->n_end_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
Constant 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 = _Py_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);
}
/* Constants for the following */
static PyObject *u_kind;
/* Compute 'kind' field for string Constant (either 'u' or None) */
static PyObject *
make_kind(struct compiling *c, const node *n)
{
char *s = NULL;
PyObject *kind = NULL;
/* Find the first string literal, if any */
while (TYPE(n) != STRING) {
if (NCH(n) == 0)
return NULL;
n = CHILD(n, 0);
}
REQ(n, STRING);
/* If it starts with 'u', return a PyUnicode "u" string */
s = STR(n);
if (s && *s == 'u') {
if (!u_kind) {
u_kind = PyUnicode_InternFromString("u");
if (!u_kind)
return NULL;
}
kind = u_kind;
if (PyArena_AddPyObject(c->c_arena, kind) < 0) {
return NULL;
}
Py_INCREF(kind);
}
return kind;
}
/* Make a Constant 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 = NULL;
*str = NULL;
assert(PyUnicode_CheckExact(s));
if (PyArena_AddPyObject(c->c_arena, s) < 0) {
Py_DECREF(s);
return NULL;
}
kind = make_kind(c, n);
if (kind == NULL && PyErr_Occurred())
return NULL;
return Constant(s, kind, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_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 Constant node. */
if (!state->last_str) {
/* Do nothing. No previous literal. */
} else {
/* Convert the existing last_str literal to a Constant 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 Constant, 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 Constant 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,
n->n_end_lineno, n->n_end_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 Constant node. For
normal strings and f-strings, concatenate them together. The result
will be a Constant 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) {
/* Just return the bytes object and we're done. */
if (PyArena_AddPyObject(c->c_arena, bytes_str) < 0)
goto error;
return Constant(bytes_str, NULL, LINENO(n), n->n_col_offset,
n->n_end_lineno, n->n_end_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;
}
PyObject *
_PyAST_GetDocString(asdl_seq *body)
{
if (!asdl_seq_LEN(body)) {
return NULL;
}
stmt_ty st = (stmt_ty)asdl_seq_GET(body, 0);
if (st->kind != Expr_kind) {
return NULL;
}
expr_ty e = st->v.Expr.value;
if (e->kind == Constant_kind && PyUnicode_CheckExact(e->v.Constant.value)) {
return e->v.Constant.value;
}
return NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1280_0 |
crossvul-cpp_data_good_2664_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;
ND_TCHECK2(tptr[0], 3);
tlen = len;
while (tlen >= 3) {
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length - 3);
switch (type) {
case BGP_AIGP_TLV:
ND_TCHECK2(tptr[3], 8);
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr+3)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr+3,"\n\t ", length-3);
}
}
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_2664_0 |
crossvul-cpp_data_bad_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/bad_5491_2 |
crossvul-cpp_data_bad_2673_0 | /*
* Copyright (c) 2009
* Siemens AG, All rights reserved.
* Dmitry Eremin-Solenikov (dbaryshkov@gmail.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IEEE 802.15.4 printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static const char *ftypes[] = {
"Beacon", /* 0 */
"Data", /* 1 */
"ACK", /* 2 */
"Command", /* 3 */
"Reserved (0x4)", /* 4 */
"Reserved (0x5)", /* 5 */
"Reserved (0x6)", /* 6 */
"Reserved (0x7)", /* 7 */
};
/*
* Frame Control subfields.
*/
#define FC_FRAME_TYPE(fc) ((fc) & 0x7)
#define FC_SECURITY_ENABLED 0x0008
#define FC_FRAME_PENDING 0x0010
#define FC_ACK_REQUEST 0x0020
#define FC_PAN_ID_COMPRESSION 0x0040
#define FC_DEST_ADDRESSING_MODE(fc) (((fc) >> 10) & 0x3)
#define FC_FRAME_VERSION(fc) (((fc) >> 12) & 0x3)
#define FC_SRC_ADDRESSING_MODE(fc) (((fc) >> 14) & 0x3)
#define FC_ADDRESSING_MODE_NONE 0x00
#define FC_ADDRESSING_MODE_RESERVED 0x01
#define FC_ADDRESSING_MODE_SHORT 0x02
#define FC_ADDRESSING_MODE_LONG 0x03
u_int
ieee802_15_4_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int hdrlen;
uint16_t fc;
uint8_t seq;
uint16_t panid = 0;
if (caplen < 3) {
ND_PRINT((ndo, "[|802.15.4]"));
return caplen;
}
hdrlen = 3;
fc = EXTRACT_LE_16BITS(p);
seq = EXTRACT_LE_8BITS(p + 2);
p += 3;
caplen -= 3;
ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)]));
if (ndo->ndo_vflag)
ND_PRINT((ndo,"seq %02x ", seq));
/*
* Destination address and PAN ID, if present.
*/
switch (FC_DEST_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (fc & FC_PAN_ID_COMPRESSION) {
/*
* PAN ID compression; this requires that both
* the source and destination addresses be present,
* but the destination address is missing.
*/
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved destination addressing mode"));
return hdrlen;
case FC_ADDRESSING_MODE_SHORT:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"< "));
/*
* Source address and PAN ID, if present.
*/
switch (FC_SRC_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved source addressing mode"));
return 0;
case FC_ADDRESSING_MODE_SHORT:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
return hdrlen;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2673_0 |
crossvul-cpp_data_bad_2666_0 | /* NetBSD: print-juniper.c,v 1.2 2007/07/24 11:53:45 drochner Exp */
/*
* 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: DLT_JUNIPER_* printers */
#ifndef lint
#else
__RCSID("NetBSD: print-juniper.c,v 1.3 2007/07/25 06:31:32 dogcow Exp ");
#endif
#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 "ppp.h"
#include "llc.h"
#include "nlpid.h"
#include "ethertype.h"
#include "atm.h"
#define JUNIPER_BPF_OUT 0 /* Outgoing packet */
#define JUNIPER_BPF_IN 1 /* Incoming packet */
#define JUNIPER_BPF_PKT_IN 0x1 /* Incoming packet */
#define JUNIPER_BPF_NO_L2 0x2 /* L2 header stripped */
#define JUNIPER_BPF_IIF 0x4 /* IIF is valid */
#define JUNIPER_BPF_FILTER 0x40 /* BPF filtering is supported */
#define JUNIPER_BPF_EXT 0x80 /* extensions present */
#define JUNIPER_MGC_NUMBER 0x4d4743 /* = "MGC" */
#define JUNIPER_LSQ_COOKIE_RE (1 << 3)
#define JUNIPER_LSQ_COOKIE_DIR (1 << 2)
#define JUNIPER_LSQ_L3_PROTO_SHIFT 4
#define JUNIPER_LSQ_L3_PROTO_MASK (0x17 << JUNIPER_LSQ_L3_PROTO_SHIFT)
#define JUNIPER_LSQ_L3_PROTO_IPV4 (0 << JUNIPER_LSQ_L3_PROTO_SHIFT)
#define JUNIPER_LSQ_L3_PROTO_IPV6 (1 << JUNIPER_LSQ_L3_PROTO_SHIFT)
#define JUNIPER_LSQ_L3_PROTO_MPLS (2 << JUNIPER_LSQ_L3_PROTO_SHIFT)
#define JUNIPER_LSQ_L3_PROTO_ISO (3 << JUNIPER_LSQ_L3_PROTO_SHIFT)
#define AS_PIC_COOKIE_LEN 8
#define JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE 1
#define JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE 2
#define JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE 3
#define JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE 4
#define JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE 5
static const struct tok juniper_ipsec_type_values[] = {
{ JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE, "ESP ENCR-AUTH" },
{ JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE, "ESP ENCR-AH AUTH" },
{ JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE, "ESP AUTH" },
{ JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE, "AH AUTH" },
{ JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE, "ESP ENCR" },
{ 0, NULL}
};
static const struct tok juniper_direction_values[] = {
{ JUNIPER_BPF_IN, "In"},
{ JUNIPER_BPF_OUT, "Out"},
{ 0, NULL}
};
/* codepoints for encoding extensions to a .pcap file */
enum {
JUNIPER_EXT_TLV_IFD_IDX = 1,
JUNIPER_EXT_TLV_IFD_NAME = 2,
JUNIPER_EXT_TLV_IFD_MEDIATYPE = 3,
JUNIPER_EXT_TLV_IFL_IDX = 4,
JUNIPER_EXT_TLV_IFL_UNIT = 5,
JUNIPER_EXT_TLV_IFL_ENCAPS = 6,
JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE = 7,
JUNIPER_EXT_TLV_TTP_IFL_ENCAPS = 8
};
/* 1 byte type and 1-byte length */
#define JUNIPER_EXT_TLV_OVERHEAD 2U
static const struct tok jnx_ext_tlv_values[] = {
{ JUNIPER_EXT_TLV_IFD_IDX, "Device Interface Index" },
{ JUNIPER_EXT_TLV_IFD_NAME,"Device Interface Name" },
{ JUNIPER_EXT_TLV_IFD_MEDIATYPE, "Device Media Type" },
{ JUNIPER_EXT_TLV_IFL_IDX, "Logical Interface Index" },
{ JUNIPER_EXT_TLV_IFL_UNIT,"Logical Unit Number" },
{ JUNIPER_EXT_TLV_IFL_ENCAPS, "Logical Interface Encapsulation" },
{ JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE, "TTP derived Device Media Type" },
{ JUNIPER_EXT_TLV_TTP_IFL_ENCAPS, "TTP derived Logical Interface Encapsulation" },
{ 0, NULL }
};
static const struct tok jnx_flag_values[] = {
{ JUNIPER_BPF_EXT, "Ext" },
{ JUNIPER_BPF_FILTER, "Filter" },
{ JUNIPER_BPF_IIF, "IIF" },
{ JUNIPER_BPF_NO_L2, "no-L2" },
{ JUNIPER_BPF_PKT_IN, "In" },
{ 0, NULL }
};
#define JUNIPER_IFML_ETHER 1
#define JUNIPER_IFML_FDDI 2
#define JUNIPER_IFML_TOKENRING 3
#define JUNIPER_IFML_PPP 4
#define JUNIPER_IFML_FRAMERELAY 5
#define JUNIPER_IFML_CISCOHDLC 6
#define JUNIPER_IFML_SMDSDXI 7
#define JUNIPER_IFML_ATMPVC 8
#define JUNIPER_IFML_PPP_CCC 9
#define JUNIPER_IFML_FRAMERELAY_CCC 10
#define JUNIPER_IFML_IPIP 11
#define JUNIPER_IFML_GRE 12
#define JUNIPER_IFML_PIM 13
#define JUNIPER_IFML_PIMD 14
#define JUNIPER_IFML_CISCOHDLC_CCC 15
#define JUNIPER_IFML_VLAN_CCC 16
#define JUNIPER_IFML_MLPPP 17
#define JUNIPER_IFML_MLFR 18
#define JUNIPER_IFML_ML 19
#define JUNIPER_IFML_LSI 20
#define JUNIPER_IFML_DFE 21
#define JUNIPER_IFML_ATM_CELLRELAY_CCC 22
#define JUNIPER_IFML_CRYPTO 23
#define JUNIPER_IFML_GGSN 24
#define JUNIPER_IFML_LSI_PPP 25
#define JUNIPER_IFML_LSI_CISCOHDLC 26
#define JUNIPER_IFML_PPP_TCC 27
#define JUNIPER_IFML_FRAMERELAY_TCC 28
#define JUNIPER_IFML_CISCOHDLC_TCC 29
#define JUNIPER_IFML_ETHERNET_CCC 30
#define JUNIPER_IFML_VT 31
#define JUNIPER_IFML_EXTENDED_VLAN_CCC 32
#define JUNIPER_IFML_ETHER_OVER_ATM 33
#define JUNIPER_IFML_MONITOR 34
#define JUNIPER_IFML_ETHERNET_TCC 35
#define JUNIPER_IFML_VLAN_TCC 36
#define JUNIPER_IFML_EXTENDED_VLAN_TCC 37
#define JUNIPER_IFML_CONTROLLER 38
#define JUNIPER_IFML_MFR 39
#define JUNIPER_IFML_LS 40
#define JUNIPER_IFML_ETHERNET_VPLS 41
#define JUNIPER_IFML_ETHERNET_VLAN_VPLS 42
#define JUNIPER_IFML_ETHERNET_EXTENDED_VLAN_VPLS 43
#define JUNIPER_IFML_LT 44
#define JUNIPER_IFML_SERVICES 45
#define JUNIPER_IFML_ETHER_VPLS_OVER_ATM 46
#define JUNIPER_IFML_FR_PORT_CCC 47
#define JUNIPER_IFML_FRAMERELAY_EXT_CCC 48
#define JUNIPER_IFML_FRAMERELAY_EXT_TCC 49
#define JUNIPER_IFML_FRAMERELAY_FLEX 50
#define JUNIPER_IFML_GGSNI 51
#define JUNIPER_IFML_ETHERNET_FLEX 52
#define JUNIPER_IFML_COLLECTOR 53
#define JUNIPER_IFML_AGGREGATOR 54
#define JUNIPER_IFML_LAPD 55
#define JUNIPER_IFML_PPPOE 56
#define JUNIPER_IFML_PPP_SUBORDINATE 57
#define JUNIPER_IFML_CISCOHDLC_SUBORDINATE 58
#define JUNIPER_IFML_DFC 59
#define JUNIPER_IFML_PICPEER 60
static const struct tok juniper_ifmt_values[] = {
{ JUNIPER_IFML_ETHER, "Ethernet" },
{ JUNIPER_IFML_FDDI, "FDDI" },
{ JUNIPER_IFML_TOKENRING, "Token-Ring" },
{ JUNIPER_IFML_PPP, "PPP" },
{ JUNIPER_IFML_PPP_SUBORDINATE, "PPP-Subordinate" },
{ JUNIPER_IFML_FRAMERELAY, "Frame-Relay" },
{ JUNIPER_IFML_CISCOHDLC, "Cisco-HDLC" },
{ JUNIPER_IFML_SMDSDXI, "SMDS-DXI" },
{ JUNIPER_IFML_ATMPVC, "ATM-PVC" },
{ JUNIPER_IFML_PPP_CCC, "PPP-CCC" },
{ JUNIPER_IFML_FRAMERELAY_CCC, "Frame-Relay-CCC" },
{ JUNIPER_IFML_FRAMERELAY_EXT_CCC, "Extended FR-CCC" },
{ JUNIPER_IFML_IPIP, "IP-over-IP" },
{ JUNIPER_IFML_GRE, "GRE" },
{ JUNIPER_IFML_PIM, "PIM-Encapsulator" },
{ JUNIPER_IFML_PIMD, "PIM-Decapsulator" },
{ JUNIPER_IFML_CISCOHDLC_CCC, "Cisco-HDLC-CCC" },
{ JUNIPER_IFML_VLAN_CCC, "VLAN-CCC" },
{ JUNIPER_IFML_EXTENDED_VLAN_CCC, "Extended-VLAN-CCC" },
{ JUNIPER_IFML_MLPPP, "Multilink-PPP" },
{ JUNIPER_IFML_MLFR, "Multilink-FR" },
{ JUNIPER_IFML_MFR, "Multilink-FR-UNI-NNI" },
{ JUNIPER_IFML_ML, "Multilink" },
{ JUNIPER_IFML_LS, "LinkService" },
{ JUNIPER_IFML_LSI, "LSI" },
{ JUNIPER_IFML_ATM_CELLRELAY_CCC, "ATM-CCC-Cell-Relay" },
{ JUNIPER_IFML_CRYPTO, "IPSEC-over-IP" },
{ JUNIPER_IFML_GGSN, "GGSN" },
{ JUNIPER_IFML_PPP_TCC, "PPP-TCC" },
{ JUNIPER_IFML_FRAMERELAY_TCC, "Frame-Relay-TCC" },
{ JUNIPER_IFML_FRAMERELAY_EXT_TCC, "Extended FR-TCC" },
{ JUNIPER_IFML_CISCOHDLC_TCC, "Cisco-HDLC-TCC" },
{ JUNIPER_IFML_ETHERNET_CCC, "Ethernet-CCC" },
{ JUNIPER_IFML_VT, "VPN-Loopback-tunnel" },
{ JUNIPER_IFML_ETHER_OVER_ATM, "Ethernet-over-ATM" },
{ JUNIPER_IFML_ETHER_VPLS_OVER_ATM, "Ethernet-VPLS-over-ATM" },
{ JUNIPER_IFML_MONITOR, "Monitor" },
{ JUNIPER_IFML_ETHERNET_TCC, "Ethernet-TCC" },
{ JUNIPER_IFML_VLAN_TCC, "VLAN-TCC" },
{ JUNIPER_IFML_EXTENDED_VLAN_TCC, "Extended-VLAN-TCC" },
{ JUNIPER_IFML_CONTROLLER, "Controller" },
{ JUNIPER_IFML_ETHERNET_VPLS, "VPLS" },
{ JUNIPER_IFML_ETHERNET_VLAN_VPLS, "VLAN-VPLS" },
{ JUNIPER_IFML_ETHERNET_EXTENDED_VLAN_VPLS, "Extended-VLAN-VPLS" },
{ JUNIPER_IFML_LT, "Logical-tunnel" },
{ JUNIPER_IFML_SERVICES, "General-Services" },
{ JUNIPER_IFML_PPPOE, "PPPoE" },
{ JUNIPER_IFML_ETHERNET_FLEX, "Flexible-Ethernet-Services" },
{ JUNIPER_IFML_FRAMERELAY_FLEX, "Flexible-FrameRelay" },
{ JUNIPER_IFML_COLLECTOR, "Flow-collection" },
{ JUNIPER_IFML_PICPEER, "PIC Peer" },
{ JUNIPER_IFML_DFC, "Dynamic-Flow-Capture" },
{0, NULL}
};
#define JUNIPER_IFLE_ATM_SNAP 2
#define JUNIPER_IFLE_ATM_NLPID 3
#define JUNIPER_IFLE_ATM_VCMUX 4
#define JUNIPER_IFLE_ATM_LLC 5
#define JUNIPER_IFLE_ATM_PPP_VCMUX 6
#define JUNIPER_IFLE_ATM_PPP_LLC 7
#define JUNIPER_IFLE_ATM_PPP_FUNI 8
#define JUNIPER_IFLE_ATM_CCC 9
#define JUNIPER_IFLE_FR_NLPID 10
#define JUNIPER_IFLE_FR_SNAP 11
#define JUNIPER_IFLE_FR_PPP 12
#define JUNIPER_IFLE_FR_CCC 13
#define JUNIPER_IFLE_ENET2 14
#define JUNIPER_IFLE_IEEE8023_SNAP 15
#define JUNIPER_IFLE_IEEE8023_LLC 16
#define JUNIPER_IFLE_PPP 17
#define JUNIPER_IFLE_CISCOHDLC 18
#define JUNIPER_IFLE_PPP_CCC 19
#define JUNIPER_IFLE_IPIP_NULL 20
#define JUNIPER_IFLE_PIM_NULL 21
#define JUNIPER_IFLE_GRE_NULL 22
#define JUNIPER_IFLE_GRE_PPP 23
#define JUNIPER_IFLE_PIMD_DECAPS 24
#define JUNIPER_IFLE_CISCOHDLC_CCC 25
#define JUNIPER_IFLE_ATM_CISCO_NLPID 26
#define JUNIPER_IFLE_VLAN_CCC 27
#define JUNIPER_IFLE_MLPPP 28
#define JUNIPER_IFLE_MLFR 29
#define JUNIPER_IFLE_LSI_NULL 30
#define JUNIPER_IFLE_AGGREGATE_UNUSED 31
#define JUNIPER_IFLE_ATM_CELLRELAY_CCC 32
#define JUNIPER_IFLE_CRYPTO 33
#define JUNIPER_IFLE_GGSN 34
#define JUNIPER_IFLE_ATM_TCC 35
#define JUNIPER_IFLE_FR_TCC 36
#define JUNIPER_IFLE_PPP_TCC 37
#define JUNIPER_IFLE_CISCOHDLC_TCC 38
#define JUNIPER_IFLE_ETHERNET_CCC 39
#define JUNIPER_IFLE_VT 40
#define JUNIPER_IFLE_ATM_EOA_LLC 41
#define JUNIPER_IFLE_EXTENDED_VLAN_CCC 42
#define JUNIPER_IFLE_ATM_SNAP_TCC 43
#define JUNIPER_IFLE_MONITOR 44
#define JUNIPER_IFLE_ETHERNET_TCC 45
#define JUNIPER_IFLE_VLAN_TCC 46
#define JUNIPER_IFLE_EXTENDED_VLAN_TCC 47
#define JUNIPER_IFLE_MFR 48
#define JUNIPER_IFLE_ETHERNET_VPLS 49
#define JUNIPER_IFLE_ETHERNET_VLAN_VPLS 50
#define JUNIPER_IFLE_ETHERNET_EXTENDED_VLAN_VPLS 51
#define JUNIPER_IFLE_SERVICES 52
#define JUNIPER_IFLE_ATM_ETHER_VPLS_ATM_LLC 53
#define JUNIPER_IFLE_FR_PORT_CCC 54
#define JUNIPER_IFLE_ATM_MLPPP_LLC 55
#define JUNIPER_IFLE_ATM_EOA_CCC 56
#define JUNIPER_IFLE_LT_VLAN 57
#define JUNIPER_IFLE_COLLECTOR 58
#define JUNIPER_IFLE_AGGREGATOR 59
#define JUNIPER_IFLE_LAPD 60
#define JUNIPER_IFLE_ATM_PPPOE_LLC 61
#define JUNIPER_IFLE_ETHERNET_PPPOE 62
#define JUNIPER_IFLE_PPPOE 63
#define JUNIPER_IFLE_PPP_SUBORDINATE 64
#define JUNIPER_IFLE_CISCOHDLC_SUBORDINATE 65
#define JUNIPER_IFLE_DFC 66
#define JUNIPER_IFLE_PICPEER 67
static const struct tok juniper_ifle_values[] = {
{ JUNIPER_IFLE_AGGREGATOR, "Aggregator" },
{ JUNIPER_IFLE_ATM_CCC, "CCC over ATM" },
{ JUNIPER_IFLE_ATM_CELLRELAY_CCC, "ATM CCC Cell Relay" },
{ JUNIPER_IFLE_ATM_CISCO_NLPID, "CISCO compatible NLPID" },
{ JUNIPER_IFLE_ATM_EOA_CCC, "Ethernet over ATM CCC" },
{ JUNIPER_IFLE_ATM_EOA_LLC, "Ethernet over ATM LLC" },
{ JUNIPER_IFLE_ATM_ETHER_VPLS_ATM_LLC, "Ethernet VPLS over ATM LLC" },
{ JUNIPER_IFLE_ATM_LLC, "ATM LLC" },
{ JUNIPER_IFLE_ATM_MLPPP_LLC, "MLPPP over ATM LLC" },
{ JUNIPER_IFLE_ATM_NLPID, "ATM NLPID" },
{ JUNIPER_IFLE_ATM_PPPOE_LLC, "PPPoE over ATM LLC" },
{ JUNIPER_IFLE_ATM_PPP_FUNI, "PPP over FUNI" },
{ JUNIPER_IFLE_ATM_PPP_LLC, "PPP over ATM LLC" },
{ JUNIPER_IFLE_ATM_PPP_VCMUX, "PPP over ATM VCMUX" },
{ JUNIPER_IFLE_ATM_SNAP, "ATM SNAP" },
{ JUNIPER_IFLE_ATM_SNAP_TCC, "ATM SNAP TCC" },
{ JUNIPER_IFLE_ATM_TCC, "ATM VCMUX TCC" },
{ JUNIPER_IFLE_ATM_VCMUX, "ATM VCMUX" },
{ JUNIPER_IFLE_CISCOHDLC, "C-HDLC" },
{ JUNIPER_IFLE_CISCOHDLC_CCC, "C-HDLC CCC" },
{ JUNIPER_IFLE_CISCOHDLC_SUBORDINATE, "C-HDLC via dialer" },
{ JUNIPER_IFLE_CISCOHDLC_TCC, "C-HDLC TCC" },
{ JUNIPER_IFLE_COLLECTOR, "Collector" },
{ JUNIPER_IFLE_CRYPTO, "Crypto" },
{ JUNIPER_IFLE_ENET2, "Ethernet" },
{ JUNIPER_IFLE_ETHERNET_CCC, "Ethernet CCC" },
{ JUNIPER_IFLE_ETHERNET_EXTENDED_VLAN_VPLS, "Extended VLAN VPLS" },
{ JUNIPER_IFLE_ETHERNET_PPPOE, "PPPoE over Ethernet" },
{ JUNIPER_IFLE_ETHERNET_TCC, "Ethernet TCC" },
{ JUNIPER_IFLE_ETHERNET_VLAN_VPLS, "VLAN VPLS" },
{ JUNIPER_IFLE_ETHERNET_VPLS, "VPLS" },
{ JUNIPER_IFLE_EXTENDED_VLAN_CCC, "Extended VLAN CCC" },
{ JUNIPER_IFLE_EXTENDED_VLAN_TCC, "Extended VLAN TCC" },
{ JUNIPER_IFLE_FR_CCC, "FR CCC" },
{ JUNIPER_IFLE_FR_NLPID, "FR NLPID" },
{ JUNIPER_IFLE_FR_PORT_CCC, "FR CCC" },
{ JUNIPER_IFLE_FR_PPP, "FR PPP" },
{ JUNIPER_IFLE_FR_SNAP, "FR SNAP" },
{ JUNIPER_IFLE_FR_TCC, "FR TCC" },
{ JUNIPER_IFLE_GGSN, "GGSN" },
{ JUNIPER_IFLE_GRE_NULL, "GRE NULL" },
{ JUNIPER_IFLE_GRE_PPP, "PPP over GRE" },
{ JUNIPER_IFLE_IPIP_NULL, "IPIP" },
{ JUNIPER_IFLE_LAPD, "LAPD" },
{ JUNIPER_IFLE_LSI_NULL, "LSI Null" },
{ JUNIPER_IFLE_LT_VLAN, "LT VLAN" },
{ JUNIPER_IFLE_MFR, "MFR" },
{ JUNIPER_IFLE_MLFR, "MLFR" },
{ JUNIPER_IFLE_MLPPP, "MLPPP" },
{ JUNIPER_IFLE_MONITOR, "Monitor" },
{ JUNIPER_IFLE_PIMD_DECAPS, "PIMd" },
{ JUNIPER_IFLE_PIM_NULL, "PIM Null" },
{ JUNIPER_IFLE_PPP, "PPP" },
{ JUNIPER_IFLE_PPPOE, "PPPoE" },
{ JUNIPER_IFLE_PPP_CCC, "PPP CCC" },
{ JUNIPER_IFLE_PPP_SUBORDINATE, "" },
{ JUNIPER_IFLE_PPP_TCC, "PPP TCC" },
{ JUNIPER_IFLE_SERVICES, "General Services" },
{ JUNIPER_IFLE_VLAN_CCC, "VLAN CCC" },
{ JUNIPER_IFLE_VLAN_TCC, "VLAN TCC" },
{ JUNIPER_IFLE_VT, "VT" },
{0, NULL}
};
struct juniper_cookie_table_t {
uint32_t pictype; /* pic type */
uint8_t cookie_len; /* cookie len */
const char *s; /* pic name */
};
static const struct juniper_cookie_table_t juniper_cookie_table[] = {
#ifdef DLT_JUNIPER_ATM1
{ DLT_JUNIPER_ATM1, 4, "ATM1"},
#endif
#ifdef DLT_JUNIPER_ATM2
{ DLT_JUNIPER_ATM2, 8, "ATM2"},
#endif
#ifdef DLT_JUNIPER_MLPPP
{ DLT_JUNIPER_MLPPP, 2, "MLPPP"},
#endif
#ifdef DLT_JUNIPER_MLFR
{ DLT_JUNIPER_MLFR, 2, "MLFR"},
#endif
#ifdef DLT_JUNIPER_MFR
{ DLT_JUNIPER_MFR, 4, "MFR"},
#endif
#ifdef DLT_JUNIPER_PPPOE
{ DLT_JUNIPER_PPPOE, 0, "PPPoE"},
#endif
#ifdef DLT_JUNIPER_PPPOE_ATM
{ DLT_JUNIPER_PPPOE_ATM, 0, "PPPoE ATM"},
#endif
#ifdef DLT_JUNIPER_GGSN
{ DLT_JUNIPER_GGSN, 8, "GGSN"},
#endif
#ifdef DLT_JUNIPER_MONITOR
{ DLT_JUNIPER_MONITOR, 8, "MONITOR"},
#endif
#ifdef DLT_JUNIPER_SERVICES
{ DLT_JUNIPER_SERVICES, 8, "AS"},
#endif
#ifdef DLT_JUNIPER_ES
{ DLT_JUNIPER_ES, 0, "ES"},
#endif
{ 0, 0, NULL }
};
struct juniper_l2info_t {
uint32_t length;
uint32_t caplen;
uint32_t pictype;
uint8_t direction;
uint8_t header_len;
uint8_t cookie_len;
uint8_t cookie_type;
uint8_t cookie[8];
uint8_t bundle;
uint16_t proto;
uint8_t flags;
};
#define LS_COOKIE_ID 0x54
#define AS_COOKIE_ID 0x47
#define LS_MLFR_COOKIE_LEN 4
#define ML_MLFR_COOKIE_LEN 2
#define LS_MFR_COOKIE_LEN 6
#define ATM1_COOKIE_LEN 4
#define ATM2_COOKIE_LEN 8
#define ATM2_PKT_TYPE_MASK 0x70
#define ATM2_GAP_COUNT_MASK 0x3F
#define JUNIPER_PROTO_NULL 1
#define JUNIPER_PROTO_IPV4 2
#define JUNIPER_PROTO_IPV6 6
#define MFR_BE_MASK 0xc0
static const struct tok juniper_protocol_values[] = {
{ JUNIPER_PROTO_NULL, "Null" },
{ JUNIPER_PROTO_IPV4, "IPv4" },
{ JUNIPER_PROTO_IPV6, "IPv6" },
{ 0, NULL}
};
static int ip_heuristic_guess(netdissect_options *, register const u_char *, u_int);
static int juniper_ppp_heuristic_guess(netdissect_options *, register const u_char *, u_int);
static int juniper_parse_header(netdissect_options *, const u_char *, const struct pcap_pkthdr *, struct juniper_l2info_t *);
#ifdef DLT_JUNIPER_GGSN
u_int
juniper_ggsn_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_ggsn_header {
uint8_t svc_id;
uint8_t flags_len;
uint8_t proto;
uint8_t flags;
uint8_t vlan_id[2];
uint8_t res[2];
};
const struct juniper_ggsn_header *gh;
l2info.pictype = DLT_JUNIPER_GGSN;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
gh = (struct juniper_ggsn_header *)&l2info.cookie;
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "proto %s (%u), vlan %u: ",
tok2str(juniper_protocol_values,"Unknown",gh->proto),
gh->proto,
EXTRACT_16BITS(&gh->vlan_id[0])));
}
switch (gh->proto) {
case JUNIPER_PROTO_IPV4:
ip_print(ndo, p, l2info.length);
break;
case JUNIPER_PROTO_IPV6:
ip6_print(ndo, p, l2info.length);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "unknown GGSN proto (%u)", gh->proto));
}
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_ES
u_int
juniper_es_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_ipsec_header {
uint8_t sa_index[2];
uint8_t ttl;
uint8_t type;
uint8_t spi[4];
uint8_t src_ip[4];
uint8_t dst_ip[4];
};
u_int rewrite_len,es_type_bundle;
const struct juniper_ipsec_header *ih;
l2info.pictype = DLT_JUNIPER_ES;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
ih = (const struct juniper_ipsec_header *)p;
switch (ih->type) {
case JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE:
case JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE:
rewrite_len = 0;
es_type_bundle = 1;
break;
case JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE:
case JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE:
case JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE:
rewrite_len = 16;
es_type_bundle = 0;
break;
default:
ND_PRINT((ndo, "ES Invalid type %u, length %u",
ih->type,
l2info.length));
return l2info.header_len;
}
l2info.length-=rewrite_len;
p+=rewrite_len;
if (ndo->ndo_eflag) {
if (!es_type_bundle) {
ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), spi %u, Tunnel %s > %s, length %u\n",
EXTRACT_16BITS(&ih->sa_index),
ih->ttl,
tok2str(juniper_ipsec_type_values,"Unknown",ih->type),
ih->type,
EXTRACT_32BITS(&ih->spi),
ipaddr_string(ndo, &ih->src_ip),
ipaddr_string(ndo, &ih->dst_ip),
l2info.length));
} else {
ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), length %u\n",
EXTRACT_16BITS(&ih->sa_index),
ih->ttl,
tok2str(juniper_ipsec_type_values,"Unknown",ih->type),
ih->type,
l2info.length));
}
}
ip_print(ndo, p, l2info.length);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_MONITOR
u_int
juniper_monitor_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_monitor_header {
uint8_t pkt_type;
uint8_t padding;
uint8_t iif[2];
uint8_t service_id[4];
};
const struct juniper_monitor_header *mh;
l2info.pictype = DLT_JUNIPER_MONITOR;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
mh = (const struct juniper_monitor_header *)p;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "service-id %u, iif %u, pkt-type %u: ",
EXTRACT_32BITS(&mh->service_id),
EXTRACT_16BITS(&mh->iif),
mh->pkt_type));
/* no proto field - lets guess by first byte of IP header*/
ip_heuristic_guess (ndo, p, l2info.length);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_SERVICES
u_int
juniper_services_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_services_header {
uint8_t svc_id;
uint8_t flags_len;
uint8_t svc_set_id[2];
uint8_t dir_iif[4];
};
const struct juniper_services_header *sh;
l2info.pictype = DLT_JUNIPER_SERVICES;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
sh = (const struct juniper_services_header *)p;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "service-id %u flags 0x%02x service-set-id 0x%04x iif %u: ",
sh->svc_id,
sh->flags_len,
EXTRACT_16BITS(&sh->svc_set_id),
EXTRACT_24BITS(&sh->dir_iif[1])));
/* no proto field - lets guess by first byte of IP header*/
ip_heuristic_guess (ndo, p, l2info.length);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_PPPOE
u_int
juniper_pppoe_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_PPPOE;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* this DLT contains nothing but raw ethernet frames */
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_ETHER
u_int
juniper_ether_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ETHER;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* this DLT contains nothing but raw Ethernet frames */
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_PPP
u_int
juniper_ppp_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_PPP;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* this DLT contains nothing but raw ppp frames */
ppp_print(ndo, p, l2info.length);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_FRELAY
u_int
juniper_frelay_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_FRELAY;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* this DLT contains nothing but raw frame-relay frames */
fr_print(ndo, p, l2info.length);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_CHDLC
u_int
juniper_chdlc_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_CHDLC;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* this DLT contains nothing but raw c-hdlc frames */
chdlc_print(ndo, p, l2info.length);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_PPPOE_ATM
u_int
juniper_pppoe_atm_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
uint16_t extracted_ethertype;
l2info.pictype = DLT_JUNIPER_PPPOE_ATM;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
extracted_ethertype = EXTRACT_16BITS(p);
/* this DLT contains nothing but raw PPPoE frames,
* prepended with a type field*/
if (ethertype_print(ndo, extracted_ethertype,
p+ETHERTYPE_LEN,
l2info.length-ETHERTYPE_LEN,
l2info.caplen-ETHERTYPE_LEN,
NULL, NULL) == 0)
/* ether_type not known, probably it wasn't one */
ND_PRINT((ndo, "unknown ethertype 0x%04x", extracted_ethertype));
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_MLPPP
u_int
juniper_mlppp_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_MLPPP;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
/* suppress Bundle-ID if frame was captured on a child-link
* best indicator if the cookie looks like a proto */
if (ndo->ndo_eflag &&
EXTRACT_16BITS(&l2info.cookie) != PPP_OSI &&
EXTRACT_16BITS(&l2info.cookie) != (PPP_ADDRESS << 8 | PPP_CONTROL))
ND_PRINT((ndo, "Bundle-ID %u: ", l2info.bundle));
p+=l2info.header_len;
/* first try the LSQ protos */
switch(l2info.proto) {
case JUNIPER_LSQ_L3_PROTO_IPV4:
/* IP traffic going to the RE would not have a cookie
* -> this must be incoming IS-IS over PPP
*/
if (l2info.cookie[4] == (JUNIPER_LSQ_COOKIE_RE|JUNIPER_LSQ_COOKIE_DIR))
ppp_print(ndo, p, l2info.length);
else
ip_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_IPV6:
ip6_print(ndo, p,l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_MPLS:
mpls_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_ISO:
isoclns_print(ndo, p, l2info.length);
return l2info.header_len;
default:
break;
}
/* zero length cookie ? */
switch (EXTRACT_16BITS(&l2info.cookie)) {
case PPP_OSI:
ppp_print(ndo, p - 2, l2info.length + 2);
break;
case (PPP_ADDRESS << 8 | PPP_CONTROL): /* fall through */
default:
ppp_print(ndo, p, l2info.length);
break;
}
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_MFR
u_int
juniper_mfr_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
memset(&l2info, 0, sizeof(l2info));
l2info.pictype = DLT_JUNIPER_MFR;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* child-link ? */
if (l2info.cookie_len == 0) {
mfr_print(ndo, p, l2info.length);
return l2info.header_len;
}
/* first try the LSQ protos */
if (l2info.cookie_len == AS_PIC_COOKIE_LEN) {
switch(l2info.proto) {
case JUNIPER_LSQ_L3_PROTO_IPV4:
ip_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_IPV6:
ip6_print(ndo, p,l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_MPLS:
mpls_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_ISO:
isoclns_print(ndo, p, l2info.length);
return l2info.header_len;
default:
break;
}
return l2info.header_len;
}
/* suppress Bundle-ID if frame was captured on a child-link */
if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1)
ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle));
switch (l2info.proto) {
case (LLCSAP_ISONS<<8 | LLCSAP_ISONS):
isoclns_print(ndo, p + 1, l2info.length - 1);
break;
case (LLC_UI<<8 | NLPID_Q933):
case (LLC_UI<<8 | NLPID_IP):
case (LLC_UI<<8 | NLPID_IP6):
/* pass IP{4,6} to the OSI layer for proper link-layer printing */
isoclns_print(ndo, p - 1, l2info.length + 1);
break;
default:
ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length));
}
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_MLFR
u_int
juniper_mlfr_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_MLFR;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* suppress Bundle-ID if frame was captured on a child-link */
if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1)
ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle));
switch (l2info.proto) {
case (LLC_UI):
case (LLC_UI<<8):
isoclns_print(ndo, p, l2info.length);
break;
case (LLC_UI<<8 | NLPID_Q933):
case (LLC_UI<<8 | NLPID_IP):
case (LLC_UI<<8 | NLPID_IP6):
/* pass IP{4,6} to the OSI layer for proper link-layer printing */
isoclns_print(ndo, p - 1, l2info.length + 1);
break;
default:
ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length));
}
return l2info.header_len;
}
#endif
/*
* ATM1 PIC cookie format
*
* +-----+-------------------------+-------------------------------+
* |fmtid| vc index | channel ID |
* +-----+-------------------------+-------------------------------+
*/
#ifdef DLT_JUNIPER_ATM1
u_int
juniper_atm1_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM1;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[0] == 0x80) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
#endif
/*
* ATM2 PIC cookie format
*
* +-------------------------------+---------+---+-----+-----------+
* | channel ID | reserv |AAL| CCRQ| gap cnt |
* +-------------------------------+---------+---+-----+-----------+
*/
#ifdef DLT_JUNIPER_ATM2
u_int
juniper_atm2_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM2;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */
(EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */
return l2info.header_len;
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
#endif
/* try to guess, based on all PPP protos that are supported in
* a juniper router if the payload data is encapsulated using PPP */
static int
juniper_ppp_heuristic_guess(netdissect_options *ndo,
register const u_char *p, u_int length)
{
switch(EXTRACT_16BITS(p)) {
case PPP_IP :
case PPP_OSI :
case PPP_MPLS_UCAST :
case PPP_MPLS_MCAST :
case PPP_IPCP :
case PPP_OSICP :
case PPP_MPLSCP :
case PPP_LCP :
case PPP_PAP :
case PPP_CHAP :
case PPP_ML :
case PPP_IPV6 :
case PPP_IPV6CP :
ppp_print(ndo, p, length);
break;
default:
return 0; /* did not find a ppp header */
break;
}
return 1; /* we printed a ppp packet */
}
static int
ip_heuristic_guess(netdissect_options *ndo,
register const u_char *p, u_int length)
{
switch(p[0]) {
case 0x45:
case 0x46:
case 0x47:
case 0x48:
case 0x49:
case 0x4a:
case 0x4b:
case 0x4c:
case 0x4d:
case 0x4e:
case 0x4f:
ip_print(ndo, p, length);
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:
ip6_print(ndo, p, length);
break;
default:
return 0; /* did not find a ip header */
break;
}
return 1; /* we printed an v4/v6 packet */
}
static int
juniper_read_tlv_value(const u_char *p, u_int tlv_type, u_int tlv_len)
{
int tlv_value;
/* TLVs < 128 are little endian encoded */
if (tlv_type < 128) {
switch (tlv_len) {
case 1:
tlv_value = *p;
break;
case 2:
tlv_value = EXTRACT_LE_16BITS(p);
break;
case 3:
tlv_value = EXTRACT_LE_24BITS(p);
break;
case 4:
tlv_value = EXTRACT_LE_32BITS(p);
break;
default:
tlv_value = -1;
break;
}
} else {
/* TLVs >= 128 are big endian encoded */
switch (tlv_len) {
case 1:
tlv_value = *p;
break;
case 2:
tlv_value = EXTRACT_16BITS(p);
break;
case 3:
tlv_value = EXTRACT_24BITS(p);
break;
case 4:
tlv_value = EXTRACT_32BITS(p);
break;
default:
tlv_value = -1;
break;
}
}
return tlv_value;
}
static int
juniper_parse_header(netdissect_options *ndo,
const u_char *p, const struct pcap_pkthdr *h, struct juniper_l2info_t *l2info)
{
const struct juniper_cookie_table_t *lp = juniper_cookie_table;
u_int idx, jnx_ext_len, jnx_header_len = 0;
uint8_t tlv_type,tlv_len;
uint32_t control_word;
int tlv_value;
const u_char *tptr;
l2info->header_len = 0;
l2info->cookie_len = 0;
l2info->proto = 0;
l2info->length = h->len;
l2info->caplen = h->caplen;
ND_TCHECK2(p[0], 4);
l2info->flags = p[3];
l2info->direction = p[3]&JUNIPER_BPF_PKT_IN;
if (EXTRACT_24BITS(p) != JUNIPER_MGC_NUMBER) { /* magic number found ? */
ND_PRINT((ndo, "no magic-number found!"));
return 0;
}
if (ndo->ndo_eflag) /* print direction */
ND_PRINT((ndo, "%3s ", tok2str(juniper_direction_values, "---", l2info->direction)));
/* magic number + flags */
jnx_header_len = 4;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\tJuniper PCAP Flags [%s]",
bittok2str(jnx_flag_values, "none", l2info->flags)));
/* extensions present ? - calculate how much bytes to skip */
if ((l2info->flags & JUNIPER_BPF_EXT ) == JUNIPER_BPF_EXT ) {
tptr = p+jnx_header_len;
/* ok to read extension length ? */
ND_TCHECK2(tptr[0], 2);
jnx_ext_len = EXTRACT_16BITS(tptr);
jnx_header_len += 2;
tptr +=2;
/* nail up the total length -
* just in case something goes wrong
* with TLV parsing */
jnx_header_len += jnx_ext_len;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, ", PCAP Extension(s) total length %u", jnx_ext_len));
ND_TCHECK2(tptr[0], jnx_ext_len);
while (jnx_ext_len > JUNIPER_EXT_TLV_OVERHEAD) {
tlv_type = *(tptr++);
tlv_len = *(tptr++);
tlv_value = 0;
/* sanity checks */
if (tlv_type == 0 || tlv_len == 0)
break;
if (tlv_len+JUNIPER_EXT_TLV_OVERHEAD > jnx_ext_len)
goto trunc;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t %s Extension TLV #%u, length %u, value ",
tok2str(jnx_ext_tlv_values,"Unknown",tlv_type),
tlv_type,
tlv_len));
tlv_value = juniper_read_tlv_value(tptr, tlv_type, tlv_len);
switch (tlv_type) {
case JUNIPER_EXT_TLV_IFD_NAME:
/* FIXME */
break;
case JUNIPER_EXT_TLV_IFD_MEDIATYPE:
case JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%s (%u)",
tok2str(juniper_ifmt_values, "Unknown", tlv_value),
tlv_value));
}
break;
case JUNIPER_EXT_TLV_IFL_ENCAPS:
case JUNIPER_EXT_TLV_TTP_IFL_ENCAPS:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%s (%u)",
tok2str(juniper_ifle_values, "Unknown", tlv_value),
tlv_value));
}
break;
case JUNIPER_EXT_TLV_IFL_IDX: /* fall through */
case JUNIPER_EXT_TLV_IFL_UNIT:
case JUNIPER_EXT_TLV_IFD_IDX:
default:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%u", tlv_value));
}
break;
}
tptr+=tlv_len;
jnx_ext_len -= tlv_len+JUNIPER_EXT_TLV_OVERHEAD;
}
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
}
if ((l2info->flags & JUNIPER_BPF_NO_L2 ) == JUNIPER_BPF_NO_L2 ) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "no-L2-hdr, "));
/* there is no link-layer present -
* perform the v4/v6 heuristics
* to figure out what it is
*/
ND_TCHECK2(p[jnx_header_len + 4], 1);
if (ip_heuristic_guess(ndo, p + jnx_header_len + 4,
l2info->length - (jnx_header_len + 4)) == 0)
ND_PRINT((ndo, "no IP-hdr found!"));
l2info->header_len=jnx_header_len+4;
return 0; /* stop parsing the output further */
}
l2info->header_len = jnx_header_len;
p+=l2info->header_len;
l2info->length -= l2info->header_len;
l2info->caplen -= l2info->header_len;
/* search through the cookie table and copy values matching for our PIC type */
while (lp->s != NULL) {
if (lp->pictype == l2info->pictype) {
l2info->cookie_len += lp->cookie_len;
switch (p[0]) {
case LS_COOKIE_ID:
l2info->cookie_type = LS_COOKIE_ID;
l2info->cookie_len += 2;
break;
case AS_COOKIE_ID:
l2info->cookie_type = AS_COOKIE_ID;
l2info->cookie_len = 8;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
#ifdef DLT_JUNIPER_MFR
/* MFR child links don't carry cookies */
if (l2info->pictype == DLT_JUNIPER_MFR &&
(p[0] & MFR_BE_MASK) == MFR_BE_MASK) {
l2info->cookie_len = 0;
}
#endif
l2info->header_len += l2info->cookie_len;
l2info->length -= l2info->cookie_len;
l2info->caplen -= l2info->cookie_len;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%s-PIC, cookie-len %u",
lp->s,
l2info->cookie_len));
if (l2info->cookie_len > 0) {
ND_TCHECK2(p[0], l2info->cookie_len);
if (ndo->ndo_eflag)
ND_PRINT((ndo, ", cookie 0x"));
for (idx = 0; idx < l2info->cookie_len; idx++) {
l2info->cookie[idx] = p[idx]; /* copy cookie data */
if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x", p[idx]));
}
}
if (ndo->ndo_eflag) ND_PRINT((ndo, ": ")); /* print demarc b/w L2/L3*/
l2info->proto = EXTRACT_16BITS(p+l2info->cookie_len);
break;
}
++lp;
}
p+=l2info->cookie_len;
/* DLT_ specific parsing */
switch(l2info->pictype) {
#ifdef DLT_JUNIPER_MLPPP
case DLT_JUNIPER_MLPPP:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
break;
#endif
#ifdef DLT_JUNIPER_MLFR
case DLT_JUNIPER_MLFR:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
l2info->proto = EXTRACT_16BITS(p);
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
}
break;
#endif
#ifdef DLT_JUNIPER_MFR
case DLT_JUNIPER_MFR:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
l2info->proto = EXTRACT_16BITS(p);
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
break;
#endif
#ifdef DLT_JUNIPER_ATM2
case DLT_JUNIPER_ATM2:
ND_TCHECK2(p[0], 4);
/* ATM cell relay control word present ? */
if (l2info->cookie[7] & ATM2_PKT_TYPE_MASK) {
control_word = EXTRACT_32BITS(p);
/* some control word heuristics */
switch(control_word) {
case 0: /* zero control word */
case 0x08000000: /* < JUNOS 7.4 control-word */
case 0x08380000: /* cntl word plus cell length (56) >= JUNOS 7.4*/
l2info->header_len += 4;
break;
default:
break;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "control-word 0x%08x ", control_word));
}
break;
#endif
#ifdef DLT_JUNIPER_GGSN
case DLT_JUNIPER_GGSN:
break;
#endif
#ifdef DLT_JUNIPER_ATM1
case DLT_JUNIPER_ATM1:
break;
#endif
#ifdef DLT_JUNIPER_PPP
case DLT_JUNIPER_PPP:
break;
#endif
#ifdef DLT_JUNIPER_CHDLC
case DLT_JUNIPER_CHDLC:
break;
#endif
#ifdef DLT_JUNIPER_ETHER
case DLT_JUNIPER_ETHER:
break;
#endif
#ifdef DLT_JUNIPER_FRELAY
case DLT_JUNIPER_FRELAY:
break;
#endif
default:
ND_PRINT((ndo, "Unknown Juniper DLT_ type %u: ", l2info->pictype));
break;
}
if (ndo->ndo_eflag > 1)
ND_PRINT((ndo, "hlen %u, proto 0x%04x, ", l2info->header_len, l2info->proto));
return 1; /* everything went ok so far. continue parsing */
trunc:
ND_PRINT((ndo, "[|juniper_hdr], length %u", h->len));
return 0;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2666_0 |
crossvul-cpp_data_bad_3946_2 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Input Virtual Channel Extension
*
* Copyright 2013 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2015 Thincast Technologies GmbH
* Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/crt.h>
#include <winpr/synch.h>
#include <winpr/thread.h>
#include <winpr/stream.h>
#include <winpr/sysinfo.h>
#include <winpr/cmdline.h>
#include <winpr/collections.h>
#include <freerdp/addin.h>
#include <freerdp/freerdp.h>
#include "rdpei_common.h"
#include "rdpei_main.h"
/**
* Touch Input
* http://msdn.microsoft.com/en-us/library/windows/desktop/dd562197/
*
* Windows Touch Input
* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317321/
*
* Input: Touch injection sample
* http://code.msdn.microsoft.com/windowsdesktop/Touch-Injection-Sample-444d9bf7
*
* Pointer Input Message Reference
* http://msdn.microsoft.com/en-us/library/hh454916/
*
* POINTER_INFO Structure
* http://msdn.microsoft.com/en-us/library/hh454907/
*
* POINTER_TOUCH_INFO Structure
* http://msdn.microsoft.com/en-us/library/hh454910/
*/
#define MAX_CONTACTS 512
struct _RDPEI_CHANNEL_CALLBACK
{
IWTSVirtualChannelCallback iface;
IWTSPlugin* plugin;
IWTSVirtualChannelManager* channel_mgr;
IWTSVirtualChannel* channel;
};
typedef struct _RDPEI_CHANNEL_CALLBACK RDPEI_CHANNEL_CALLBACK;
struct _RDPEI_LISTENER_CALLBACK
{
IWTSListenerCallback iface;
IWTSPlugin* plugin;
IWTSVirtualChannelManager* channel_mgr;
RDPEI_CHANNEL_CALLBACK* channel_callback;
};
typedef struct _RDPEI_LISTENER_CALLBACK RDPEI_LISTENER_CALLBACK;
struct _RDPEI_PLUGIN
{
IWTSPlugin iface;
IWTSListener* listener;
RDPEI_LISTENER_CALLBACK* listener_callback;
RdpeiClientContext* context;
int version;
UINT16 maxTouchContacts;
UINT64 currentFrameTime;
UINT64 previousFrameTime;
RDPINPUT_TOUCH_FRAME frame;
RDPINPUT_CONTACT_DATA contacts[MAX_CONTACTS];
RDPINPUT_CONTACT_POINT* contactPoints;
rdpContext* rdpcontext;
};
typedef struct _RDPEI_PLUGIN RDPEI_PLUGIN;
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_send_frame(RdpeiClientContext* context);
#ifdef WITH_DEBUG_RDPEI
static const char* rdpei_eventid_string(UINT16 event)
{
switch (event)
{
case EVENTID_SC_READY:
return "EVENTID_SC_READY";
case EVENTID_CS_READY:
return "EVENTID_CS_READY";
case EVENTID_TOUCH:
return "EVENTID_TOUCH";
case EVENTID_SUSPEND_TOUCH:
return "EVENTID_SUSPEND_TOUCH";
case EVENTID_RESUME_TOUCH:
return "EVENTID_RESUME_TOUCH";
case EVENTID_DISMISS_HOVERING_CONTACT:
return "EVENTID_DISMISS_HOVERING_CONTACT";
default:
return "EVENTID_UNKNOWN";
}
}
#endif
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_add_frame(RdpeiClientContext* context)
{
int i;
RDPINPUT_CONTACT_DATA* contact;
RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;
rdpei->frame.contactCount = 0;
for (i = 0; i < rdpei->maxTouchContacts; i++)
{
contact = (RDPINPUT_CONTACT_DATA*)&(rdpei->contactPoints[i].data);
if (rdpei->contactPoints[i].dirty)
{
CopyMemory(&(rdpei->contacts[rdpei->frame.contactCount]), contact,
sizeof(RDPINPUT_CONTACT_DATA));
rdpei->contactPoints[i].dirty = FALSE;
rdpei->frame.contactCount++;
}
else if (rdpei->contactPoints[i].active)
{
if (contact->contactFlags & CONTACT_FLAG_DOWN)
{
contact->contactFlags = CONTACT_FLAG_UPDATE;
contact->contactFlags |= CONTACT_FLAG_INRANGE;
contact->contactFlags |= CONTACT_FLAG_INCONTACT;
}
CopyMemory(&(rdpei->contacts[rdpei->frame.contactCount]), contact,
sizeof(RDPINPUT_CONTACT_DATA));
rdpei->frame.contactCount++;
}
}
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_send_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s, UINT16 eventId,
UINT32 pduLength)
{
UINT status;
Stream_SetPosition(s, 0);
Stream_Write_UINT16(s, eventId); /* eventId (2 bytes) */
Stream_Write_UINT32(s, pduLength); /* pduLength (4 bytes) */
Stream_SetPosition(s, Stream_Length(s));
status = callback->channel->Write(callback->channel, (UINT32)Stream_Length(s), Stream_Buffer(s),
NULL);
#ifdef WITH_DEBUG_RDPEI
WLog_DBG(TAG,
"rdpei_send_pdu: eventId: %" PRIu16 " (%s) length: %" PRIu32 " status: %" PRIu32 "",
eventId, rdpei_eventid_string(eventId), pduLength, status);
#endif
return status;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_send_cs_ready_pdu(RDPEI_CHANNEL_CALLBACK* callback)
{
UINT status;
wStream* s;
UINT32 flags;
UINT32 pduLength;
RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)callback->plugin;
flags = 0;
flags |= READY_FLAGS_SHOW_TOUCH_VISUALS;
// flags |= READY_FLAGS_DISABLE_TIMESTAMP_INJECTION;
pduLength = RDPINPUT_HEADER_LENGTH + 10;
s = Stream_New(NULL, pduLength);
if (!s)
{
WLog_ERR(TAG, "Stream_New failed!");
return CHANNEL_RC_NO_MEMORY;
}
Stream_Seek(s, RDPINPUT_HEADER_LENGTH);
Stream_Write_UINT32(s, flags); /* flags (4 bytes) */
Stream_Write_UINT32(s, RDPINPUT_PROTOCOL_V10); /* protocolVersion (4 bytes) */
Stream_Write_UINT16(s, rdpei->maxTouchContacts); /* maxTouchContacts (2 bytes) */
Stream_SealLength(s);
status = rdpei_send_pdu(callback, s, EVENTID_CS_READY, pduLength);
Stream_Free(s, TRUE);
return status;
}
static void rdpei_print_contact_flags(UINT32 contactFlags)
{
if (contactFlags & CONTACT_FLAG_DOWN)
WLog_DBG(TAG, " CONTACT_FLAG_DOWN");
if (contactFlags & CONTACT_FLAG_UPDATE)
WLog_DBG(TAG, " CONTACT_FLAG_UPDATE");
if (contactFlags & CONTACT_FLAG_UP)
WLog_DBG(TAG, " CONTACT_FLAG_UP");
if (contactFlags & CONTACT_FLAG_INRANGE)
WLog_DBG(TAG, " CONTACT_FLAG_INRANGE");
if (contactFlags & CONTACT_FLAG_INCONTACT)
WLog_DBG(TAG, " CONTACT_FLAG_INCONTACT");
if (contactFlags & CONTACT_FLAG_CANCELED)
WLog_DBG(TAG, " CONTACT_FLAG_CANCELED");
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_write_touch_frame(wStream* s, RDPINPUT_TOUCH_FRAME* frame)
{
UINT32 index;
int rectSize = 2;
RDPINPUT_CONTACT_DATA* contact;
#ifdef WITH_DEBUG_RDPEI
WLog_DBG(TAG, "contactCount: %" PRIu32 "", frame->contactCount);
WLog_DBG(TAG, "frameOffset: 0x%016" PRIX64 "", frame->frameOffset);
#endif
rdpei_write_2byte_unsigned(s,
frame->contactCount); /* contactCount (TWO_BYTE_UNSIGNED_INTEGER) */
/**
* the time offset from the previous frame (in microseconds).
* If this is the first frame being transmitted then this field MUST be set to zero.
*/
rdpei_write_8byte_unsigned(s, frame->frameOffset *
1000); /* frameOffset (EIGHT_BYTE_UNSIGNED_INTEGER) */
if (!Stream_EnsureRemainingCapacity(s, (size_t)frame->contactCount * 64))
{
WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!");
return CHANNEL_RC_NO_MEMORY;
}
for (index = 0; index < frame->contactCount; index++)
{
contact = &frame->contacts[index];
contact->fieldsPresent |= CONTACT_DATA_CONTACTRECT_PRESENT;
contact->contactRectLeft = contact->x - rectSize;
contact->contactRectTop = contact->y - rectSize;
contact->contactRectRight = contact->x + rectSize;
contact->contactRectBottom = contact->y + rectSize;
#ifdef WITH_DEBUG_RDPEI
WLog_DBG(TAG, "contact[%" PRIu32 "].contactId: %" PRIu32 "", index, contact->contactId);
WLog_DBG(TAG, "contact[%" PRIu32 "].fieldsPresent: %" PRIu32 "", index,
contact->fieldsPresent);
WLog_DBG(TAG, "contact[%" PRIu32 "].x: %" PRId32 "", index, contact->x);
WLog_DBG(TAG, "contact[%" PRIu32 "].y: %" PRId32 "", index, contact->y);
WLog_DBG(TAG, "contact[%" PRIu32 "].contactFlags: 0x%08" PRIX32 "", index,
contact->contactFlags);
rdpei_print_contact_flags(contact->contactFlags);
#endif
Stream_Write_UINT8(s, contact->contactId); /* contactId (1 byte) */
/* fieldsPresent (TWO_BYTE_UNSIGNED_INTEGER) */
rdpei_write_2byte_unsigned(s, contact->fieldsPresent);
rdpei_write_4byte_signed(s, contact->x); /* x (FOUR_BYTE_SIGNED_INTEGER) */
rdpei_write_4byte_signed(s, contact->y); /* y (FOUR_BYTE_SIGNED_INTEGER) */
/* contactFlags (FOUR_BYTE_UNSIGNED_INTEGER) */
rdpei_write_4byte_unsigned(s, contact->contactFlags);
if (contact->fieldsPresent & CONTACT_DATA_CONTACTRECT_PRESENT)
{
/* contactRectLeft (TWO_BYTE_SIGNED_INTEGER) */
rdpei_write_2byte_signed(s, contact->contactRectLeft);
/* contactRectTop (TWO_BYTE_SIGNED_INTEGER) */
rdpei_write_2byte_signed(s, contact->contactRectTop);
/* contactRectRight (TWO_BYTE_SIGNED_INTEGER) */
rdpei_write_2byte_signed(s, contact->contactRectRight);
/* contactRectBottom (TWO_BYTE_SIGNED_INTEGER) */
rdpei_write_2byte_signed(s, contact->contactRectBottom);
}
if (contact->fieldsPresent & CONTACT_DATA_ORIENTATION_PRESENT)
{
/* orientation (FOUR_BYTE_UNSIGNED_INTEGER) */
rdpei_write_4byte_unsigned(s, contact->orientation);
}
if (contact->fieldsPresent & CONTACT_DATA_PRESSURE_PRESENT)
{
/* pressure (FOUR_BYTE_UNSIGNED_INTEGER) */
rdpei_write_4byte_unsigned(s, contact->pressure);
}
}
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_send_touch_event_pdu(RDPEI_CHANNEL_CALLBACK* callback,
RDPINPUT_TOUCH_FRAME* frame)
{
UINT status;
wStream* s;
UINT32 pduLength;
pduLength = 64 + (frame->contactCount * 64);
s = Stream_New(NULL, pduLength);
if (!s)
{
WLog_ERR(TAG, "Stream_New failed!");
return CHANNEL_RC_NO_MEMORY;
}
Stream_Seek(s, RDPINPUT_HEADER_LENGTH);
/**
* the time that has elapsed (in milliseconds) from when the oldest touch frame
* was generated to when it was encoded for transmission by the client.
*/
rdpei_write_4byte_unsigned(
s, (UINT32)frame->frameOffset); /* encodeTime (FOUR_BYTE_UNSIGNED_INTEGER) */
rdpei_write_2byte_unsigned(s, 1); /* (frameCount) TWO_BYTE_UNSIGNED_INTEGER */
if ((status = rdpei_write_touch_frame(s, frame)))
{
WLog_ERR(TAG, "rdpei_write_touch_frame failed with error %" PRIu32 "!", status);
Stream_Free(s, TRUE);
return status;
}
Stream_SealLength(s);
pduLength = Stream_Length(s);
status = rdpei_send_pdu(callback, s, EVENTID_TOUCH, pduLength);
Stream_Free(s, TRUE);
return status;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_recv_sc_ready_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s)
{
UINT32 protocolVersion;
Stream_Read_UINT32(s, protocolVersion); /* protocolVersion (4 bytes) */
#if 0
if (protocolVersion != RDPINPUT_PROTOCOL_V10)
{
WLog_ERR(TAG, "Unknown [MS-RDPEI] protocolVersion: 0x%08"PRIX32"", protocolVersion);
return -1;
}
#endif
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_recv_suspend_touch_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s)
{
RdpeiClientContext* rdpei = (RdpeiClientContext*)callback->plugin->pInterface;
UINT error = CHANNEL_RC_OK;
IFCALLRET(rdpei->SuspendTouch, error, rdpei);
if (error)
WLog_ERR(TAG, "rdpei->SuspendTouch failed with error %" PRIu32 "!", error);
return error;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_recv_resume_touch_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s)
{
RdpeiClientContext* rdpei = (RdpeiClientContext*)callback->plugin->pInterface;
UINT error = CHANNEL_RC_OK;
IFCALLRET(rdpei->ResumeTouch, error, rdpei);
if (error)
WLog_ERR(TAG, "rdpei->ResumeTouch failed with error %" PRIu32 "!", error);
return error;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_recv_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s)
{
UINT16 eventId;
UINT32 pduLength;
UINT error;
Stream_Read_UINT16(s, eventId); /* eventId (2 bytes) */
Stream_Read_UINT32(s, pduLength); /* pduLength (4 bytes) */
#ifdef WITH_DEBUG_RDPEI
WLog_DBG(TAG, "rdpei_recv_pdu: eventId: %" PRIu16 " (%s) length: %" PRIu32 "", eventId,
rdpei_eventid_string(eventId), pduLength);
#endif
switch (eventId)
{
case EVENTID_SC_READY:
if ((error = rdpei_recv_sc_ready_pdu(callback, s)))
{
WLog_ERR(TAG, "rdpei_recv_sc_ready_pdu failed with error %" PRIu32 "!", error);
return error;
}
if ((error = rdpei_send_cs_ready_pdu(callback)))
{
WLog_ERR(TAG, "rdpei_send_cs_ready_pdu failed with error %" PRIu32 "!", error);
return error;
}
break;
case EVENTID_SUSPEND_TOUCH:
if ((error = rdpei_recv_suspend_touch_pdu(callback, s)))
{
WLog_ERR(TAG, "rdpei_recv_suspend_touch_pdu failed with error %" PRIu32 "!", error);
return error;
}
break;
case EVENTID_RESUME_TOUCH:
if ((error = rdpei_recv_resume_touch_pdu(callback, s)))
{
WLog_ERR(TAG, "rdpei_recv_resume_touch_pdu failed with error %" PRIu32 "!", error);
return error;
}
break;
default:
break;
}
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream* data)
{
RDPEI_CHANNEL_CALLBACK* callback = (RDPEI_CHANNEL_CALLBACK*)pChannelCallback;
return rdpei_recv_pdu(callback, data);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_on_close(IWTSVirtualChannelCallback* pChannelCallback)
{
RDPEI_CHANNEL_CALLBACK* callback = (RDPEI_CHANNEL_CALLBACK*)pChannelCallback;
free(callback);
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_on_new_channel_connection(IWTSListenerCallback* pListenerCallback,
IWTSVirtualChannel* pChannel, BYTE* Data,
BOOL* pbAccept, IWTSVirtualChannelCallback** ppCallback)
{
RDPEI_CHANNEL_CALLBACK* callback;
RDPEI_LISTENER_CALLBACK* listener_callback = (RDPEI_LISTENER_CALLBACK*)pListenerCallback;
callback = (RDPEI_CHANNEL_CALLBACK*)calloc(1, sizeof(RDPEI_CHANNEL_CALLBACK));
if (!callback)
{
WLog_ERR(TAG, "calloc failed!");
return CHANNEL_RC_NO_MEMORY;
}
callback->iface.OnDataReceived = rdpei_on_data_received;
callback->iface.OnClose = rdpei_on_close;
callback->plugin = listener_callback->plugin;
callback->channel_mgr = listener_callback->channel_mgr;
callback->channel = pChannel;
listener_callback->channel_callback = callback;
*ppCallback = (IWTSVirtualChannelCallback*)callback;
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_plugin_initialize(IWTSPlugin* pPlugin, IWTSVirtualChannelManager* pChannelMgr)
{
UINT error;
RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)pPlugin;
rdpei->listener_callback = (RDPEI_LISTENER_CALLBACK*)calloc(1, sizeof(RDPEI_LISTENER_CALLBACK));
if (!rdpei->listener_callback)
{
WLog_ERR(TAG, "calloc failed!");
return CHANNEL_RC_NO_MEMORY;
}
rdpei->listener_callback->iface.OnNewChannelConnection = rdpei_on_new_channel_connection;
rdpei->listener_callback->plugin = pPlugin;
rdpei->listener_callback->channel_mgr = pChannelMgr;
if ((error = pChannelMgr->CreateListener(pChannelMgr, RDPEI_DVC_CHANNEL_NAME, 0,
(IWTSListenerCallback*)rdpei->listener_callback,
&(rdpei->listener))))
{
WLog_ERR(TAG, "ChannelMgr->CreateListener failed with error %" PRIu32 "!", error);
goto error_out;
}
rdpei->listener->pInterface = rdpei->iface.pInterface;
return error;
error_out:
free(rdpei->listener_callback);
return error;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_plugin_terminated(IWTSPlugin* pPlugin)
{
RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)pPlugin;
if (!pPlugin)
return ERROR_INVALID_PARAMETER;
free(rdpei->listener_callback);
free(rdpei->context);
free(rdpei);
return CHANNEL_RC_OK;
}
/**
* Channel Client Interface
*/
static int rdpei_get_version(RdpeiClientContext* context)
{
RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;
return rdpei->version;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
UINT rdpei_send_frame(RdpeiClientContext* context)
{
UINT64 currentTime;
RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;
RDPEI_CHANNEL_CALLBACK* callback = rdpei->listener_callback->channel_callback;
UINT error;
currentTime = GetTickCount64();
if (!rdpei->previousFrameTime && !rdpei->currentFrameTime)
{
rdpei->currentFrameTime = currentTime;
rdpei->frame.frameOffset = 0;
}
else
{
rdpei->currentFrameTime = currentTime;
rdpei->frame.frameOffset = rdpei->currentFrameTime - rdpei->previousFrameTime;
}
if ((error = rdpei_send_touch_event_pdu(callback, &rdpei->frame)))
{
WLog_ERR(TAG, "rdpei_send_touch_event_pdu failed with error %" PRIu32 "!", error);
return error;
}
rdpei->previousFrameTime = rdpei->currentFrameTime;
rdpei->frame.contactCount = 0;
return error;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_add_contact(RdpeiClientContext* context, const RDPINPUT_CONTACT_DATA* contact)
{
UINT error;
RDPINPUT_CONTACT_POINT* contactPoint;
RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;
contactPoint = (RDPINPUT_CONTACT_POINT*)&rdpei->contactPoints[contact->contactId];
CopyMemory(&(contactPoint->data), contact, sizeof(RDPINPUT_CONTACT_DATA));
contactPoint->dirty = TRUE;
error = rdpei_add_frame(context);
if (error != CHANNEL_RC_OK)
{
WLog_ERR(TAG, "rdpei_add_frame failed with error %" PRIu32 "!", error);
return error;
}
if (rdpei->frame.contactCount > 0)
{
error = rdpei_send_frame(context);
if (error != CHANNEL_RC_OK)
{
WLog_ERR(TAG, "rdpei_send_frame failed with error %" PRIu32 "!", error);
return error;
}
}
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_touch_begin(RdpeiClientContext* context, int externalId, int x, int y,
int* contactId)
{
unsigned int i;
INT64 contactIdlocal = -1;
RDPINPUT_CONTACT_DATA contact;
RDPINPUT_CONTACT_POINT* contactPoint = NULL;
RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;
UINT error = CHANNEL_RC_OK;
/* Create a new contact point in an empty slot */
for (i = 0; i < rdpei->maxTouchContacts; i++)
{
contactPoint = (RDPINPUT_CONTACT_POINT*)&rdpei->contactPoints[i];
if (!contactPoint->active)
{
contactPoint->contactId = i;
contactIdlocal = contactPoint->contactId;
contactPoint->externalId = externalId;
contactPoint->active = TRUE;
contactPoint->state = RDPINPUT_CONTACT_STATE_ENGAGED;
break;
}
}
if (contactIdlocal >= 0)
{
ZeroMemory(&contact, sizeof(RDPINPUT_CONTACT_DATA));
contactPoint->lastX = x;
contactPoint->lastY = y;
contact.x = x;
contact.y = y;
contact.contactId = (UINT32)contactIdlocal;
contact.contactFlags |= CONTACT_FLAG_DOWN;
contact.contactFlags |= CONTACT_FLAG_INRANGE;
contact.contactFlags |= CONTACT_FLAG_INCONTACT;
error = context->AddContact(context, &contact);
}
*contactId = contactIdlocal;
return error;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_touch_update(RdpeiClientContext* context, int externalId, int x, int y,
int* contactId)
{
unsigned int i;
int contactIdlocal = -1;
RDPINPUT_CONTACT_DATA contact;
RDPINPUT_CONTACT_POINT* contactPoint = NULL;
RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;
UINT error = CHANNEL_RC_OK;
for (i = 0; i < rdpei->maxTouchContacts; i++)
{
contactPoint = (RDPINPUT_CONTACT_POINT*)&rdpei->contactPoints[i];
if (!contactPoint->active)
continue;
if (contactPoint->externalId == externalId)
{
contactIdlocal = contactPoint->contactId;
break;
}
}
if (contactIdlocal >= 0)
{
ZeroMemory(&contact, sizeof(RDPINPUT_CONTACT_DATA));
contactPoint->lastX = x;
contactPoint->lastY = y;
contact.x = x;
contact.y = y;
contact.contactId = (UINT32)contactIdlocal;
contact.contactFlags |= CONTACT_FLAG_UPDATE;
contact.contactFlags |= CONTACT_FLAG_INRANGE;
contact.contactFlags |= CONTACT_FLAG_INCONTACT;
error = context->AddContact(context, &contact);
}
*contactId = contactIdlocal;
return error;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT rdpei_touch_end(RdpeiClientContext* context, int externalId, int x, int y,
int* contactId)
{
unsigned int i;
int contactIdlocal = -1;
int tempvalue;
RDPINPUT_CONTACT_DATA contact;
RDPINPUT_CONTACT_POINT* contactPoint = NULL;
RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;
UINT error;
for (i = 0; i < rdpei->maxTouchContacts; i++)
{
contactPoint = (RDPINPUT_CONTACT_POINT*)&rdpei->contactPoints[i];
if (!contactPoint->active)
continue;
if (contactPoint->externalId == externalId)
{
contactIdlocal = contactPoint->contactId;
break;
}
}
if (contactIdlocal >= 0)
{
ZeroMemory(&contact, sizeof(RDPINPUT_CONTACT_DATA));
if ((contactPoint->lastX != x) && (contactPoint->lastY != y))
{
if ((error = context->TouchUpdate(context, externalId, x, y, &tempvalue)))
{
WLog_ERR(TAG, "context->TouchUpdate failed with error %" PRIu32 "!", error);
return error;
}
}
contact.x = x;
contact.y = y;
contact.contactId = (UINT32)contactIdlocal;
contact.contactFlags |= CONTACT_FLAG_UP;
if ((error = context->AddContact(context, &contact)))
{
WLog_ERR(TAG, "context->AddContact failed with error %" PRIu32 "!", error);
return error;
}
contactPoint->externalId = 0;
contactPoint->active = FALSE;
contactPoint->flags = 0;
contactPoint->contactId = 0;
contactPoint->state = RDPINPUT_CONTACT_STATE_OUT_OF_RANGE;
}
*contactId = contactIdlocal;
return CHANNEL_RC_OK;
}
#ifdef BUILTIN_CHANNELS
#define DVCPluginEntry rdpei_DVCPluginEntry
#else
#define DVCPluginEntry FREERDP_API DVCPluginEntry
#endif
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
UINT DVCPluginEntry(IDRDYNVC_ENTRY_POINTS* pEntryPoints)
{
UINT error;
RDPEI_PLUGIN* rdpei = NULL;
RdpeiClientContext* context = NULL;
rdpei = (RDPEI_PLUGIN*)pEntryPoints->GetPlugin(pEntryPoints, "rdpei");
if (!rdpei)
{
size_t size;
rdpei = (RDPEI_PLUGIN*)calloc(1, sizeof(RDPEI_PLUGIN));
if (!rdpei)
{
WLog_ERR(TAG, "calloc failed!");
return CHANNEL_RC_NO_MEMORY;
}
rdpei->iface.Initialize = rdpei_plugin_initialize;
rdpei->iface.Connected = NULL;
rdpei->iface.Disconnected = NULL;
rdpei->iface.Terminated = rdpei_plugin_terminated;
rdpei->version = 1;
rdpei->currentFrameTime = 0;
rdpei->previousFrameTime = 0;
rdpei->frame.contacts = (RDPINPUT_CONTACT_DATA*)rdpei->contacts;
rdpei->maxTouchContacts = 10;
size = rdpei->maxTouchContacts * sizeof(RDPINPUT_CONTACT_POINT);
rdpei->contactPoints = (RDPINPUT_CONTACT_POINT*)calloc(1, size);
rdpei->rdpcontext =
((freerdp*)((rdpSettings*)pEntryPoints->GetRdpSettings(pEntryPoints))->instance)
->context;
if (!rdpei->contactPoints)
{
WLog_ERR(TAG, "calloc failed!");
error = CHANNEL_RC_NO_MEMORY;
goto error_out;
}
context = (RdpeiClientContext*)calloc(1, sizeof(RdpeiClientContext));
if (!context)
{
WLog_ERR(TAG, "calloc failed!");
error = CHANNEL_RC_NO_MEMORY;
goto error_out;
}
context->handle = (void*)rdpei;
context->GetVersion = rdpei_get_version;
context->AddContact = rdpei_add_contact;
context->TouchBegin = rdpei_touch_begin;
context->TouchUpdate = rdpei_touch_update;
context->TouchEnd = rdpei_touch_end;
rdpei->iface.pInterface = (void*)context;
if ((error = pEntryPoints->RegisterPlugin(pEntryPoints, "rdpei", (IWTSPlugin*)rdpei)))
{
WLog_ERR(TAG, "EntryPoints->RegisterPlugin failed with error %" PRIu32 "!", error);
error = CHANNEL_RC_NO_MEMORY;
goto error_out;
}
rdpei->context = context;
}
return CHANNEL_RC_OK;
error_out:
free(context);
free(rdpei->contactPoints);
free(rdpei);
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3946_2 |
crossvul-cpp_data_bad_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) {
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);
nh = *cp;
return;
case IPPROTO_ROUTING:
advance = rt6_print(ndo, cp, (const u_char *)ip6);
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);
nh = *cp;
break;
case IPPROTO_ESP:
{
int enh, padlen;
advance = esp_print(ndo, cp, len, (const u_char *)ip6, &enh, &padlen);
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/bad_2657_0 |
crossvul-cpp_data_good_2644_10 | /*
* Copyright (c) 1991, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: BSD loopback device printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "af.h"
/*
* The DLT_NULL packet header is 4 bytes long. It contains a host-byte-order
* 32-bit integer that specifies the family, e.g. AF_INET.
*
* Note here that "host" refers to the host on which the packets were
* captured; that isn't necessarily *this* host.
*
* The OpenBSD DLT_LOOP packet header is the same, except that the integer
* is in network byte order.
*/
#define NULL_HDRLEN 4
/*
* Byte-swap a 32-bit number.
* ("htonl()" or "ntohl()" won't work - we want to byte-swap even on
* big-endian platforms.)
*/
#define SWAPLONG(y) \
((((y)&0xff)<<24) | (((y)&0xff00)<<8) | (((y)&0xff0000)>>8) | (((y)>>24)&0xff))
static inline void
null_hdr_print(netdissect_options *ndo, u_int family, u_int length)
{
if (!ndo->ndo_qflag) {
ND_PRINT((ndo, "AF %s (%u)",
tok2str(bsd_af_values,"Unknown",family),family));
} else {
ND_PRINT((ndo, "%s",
tok2str(bsd_af_values,"Unknown AF %u",family)));
}
ND_PRINT((ndo, ", length %u: ", length));
}
/*
* This is the top level routine of the printer. 'p' points
* to the ether header of the packet, 'h->ts' is the timestamp,
* 'h->len' is the length of the packet off the wire, and 'h->caplen'
* is the number of bytes actually captured.
*/
u_int
null_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p)
{
u_int length = h->len;
u_int caplen = h->caplen;
u_int family;
if (caplen < NULL_HDRLEN) {
ND_PRINT((ndo, "[|null]"));
return (NULL_HDRLEN);
}
memcpy((char *)&family, (const char *)p, sizeof(family));
/*
* This isn't necessarily in our host byte order; if this is
* a DLT_LOOP capture, it's in network byte order, and if
* this is a DLT_NULL capture from a machine with the opposite
* byte-order, it's in the opposite byte order from ours.
*
* If the upper 16 bits aren't all zero, assume it's byte-swapped.
*/
if ((family & 0xFFFF0000) != 0)
family = SWAPLONG(family);
if (ndo->ndo_eflag)
null_hdr_print(ndo, family, length);
length -= NULL_HDRLEN;
caplen -= NULL_HDRLEN;
p += NULL_HDRLEN;
switch (family) {
case BSD_AFNUM_INET:
ip_print(ndo, p, length);
break;
case BSD_AFNUM_INET6_BSD:
case BSD_AFNUM_INET6_FREEBSD:
case BSD_AFNUM_INET6_DARWIN:
ip6_print(ndo, p, length);
break;
case BSD_AFNUM_ISO:
isoclns_print(ndo, p, length);
break;
case BSD_AFNUM_APPLETALK:
atalk_print(ndo, p, length);
break;
case BSD_AFNUM_IPX:
ipx_print(ndo, p, length);
break;
default:
/* unknown AF_ value */
if (!ndo->ndo_eflag)
null_hdr_print(ndo, family, length + NULL_HDRLEN);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
}
return (NULL_HDRLEN);
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2644_10 |
crossvul-cpp_data_bad_5240_0 | /**
* File: TGA Input
*
* Read TGA images.
*/
#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"
/*
Function: gdImageCreateFromTga
Creates a gdImage from a TGA file
Parameters:
infile - Pointer to TGA binary file
*/
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;
}
/*
Function: gdImageCreateFromTgaPtr
*/
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;
}
/*
Function: gdImageCreateFromTgaCtx
Creates a gdImage from a gdIOCtx referencing a TGA binary file.
Parameters:
ctx - Pointer to a gdIOCtx structure
*/
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;
int* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int encoded_pixels;
int rle_size;
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 = (int*) gdMalloc(image_block_size * sizeof(int));
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;
}
rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx);
if (rle_size <= 0) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < rle_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 * sizeof(int));
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 * sizeof(int));
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/bad_5240_0 |
crossvul-cpp_data_bad_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 *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));
/*
* 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,
(ep < ep2) ? ep : ep2, map, nmap);
}
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, (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);
/*
* Our caller has ensured that the length is >= 4.
*/
ND_PRINT((ndo," len=%u method=%s", len-4,
STR_OR_ID(a.auth_method, v2_auth)));
if (len > 4) {
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " authdata=("));
if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))
goto trunc;
ND_PRINT((ndo, ") "));
} else if (ndo->ndo_vflag) {
if (!ike_show_somedata(ndo, authdata, ep))
goto trunc;
}
}
return (const u_char *)ext + len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_nonce_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, "nonce", e.critical);
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," nonce=("));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
ND_PRINT((ndo,") "));
} else if(ndo->ndo_vflag && 4 < ntohs(e.len)) {
if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
/* notify payloads */
static const u_char *
ikev2_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
const struct ikev2_n *p;
struct ikev2_n n;
const u_char *cp;
u_char showspi, showsomedata;
const char *notify_name;
uint32_t type;
p = (const struct ikev2_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical);
showspi = 1;
showsomedata=0;
notify_name=NULL;
ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id)));
type = ntohs(n.type);
/* notify space is annoying sparse */
switch(type) {
case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD:
notify_name = "unsupported_critical_payload";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_IKE_SPI:
notify_name = "invalid_ike_spi";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MAJOR_VERSION:
notify_name = "invalid_major_version";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SYNTAX:
notify_name = "invalid_syntax";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MESSAGE_ID:
notify_name = "invalid_message_id";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_SPI:
notify_name = "invalid_spi";
showspi = 1;
break;
case IV2_NOTIFY_NO_PROPOSAL_CHOSEN:
notify_name = "no_protocol_chosen";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_KE_PAYLOAD:
notify_name = "invalid_ke_payload";
showspi = 1;
break;
case IV2_NOTIFY_AUTHENTICATION_FAILED:
notify_name = "authentication_failed";
showspi = 1;
break;
case IV2_NOTIFY_SINGLE_PAIR_REQUIRED:
notify_name = "single_pair_required";
showspi = 1;
break;
case IV2_NOTIFY_NO_ADDITIONAL_SAS:
notify_name = "no_additional_sas";
showspi = 0;
break;
case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE:
notify_name = "internal_address_failure";
showspi = 0;
break;
case IV2_NOTIFY_FAILED_CP_REQUIRED:
notify_name = "failed:cp_required";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SELECTORS:
notify_name = "invalid_selectors";
showspi = 0;
break;
case IV2_NOTIFY_INITIAL_CONTACT:
notify_name = "initial_contact";
showspi = 0;
break;
case IV2_NOTIFY_SET_WINDOW_SIZE:
notify_name = "set_window_size";
showspi = 0;
break;
case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE:
notify_name = "additional_ts_possible";
showspi = 0;
break;
case IV2_NOTIFY_IPCOMP_SUPPORTED:
notify_name = "ipcomp_supported";
showspi = 0;
break;
case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP:
notify_name = "nat_detection_source_ip";
showspi = 1;
break;
case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP:
notify_name = "nat_detection_destination_ip";
showspi = 1;
break;
case IV2_NOTIFY_COOKIE:
notify_name = "cookie";
showspi = 1;
showsomedata= 1;
break;
case IV2_NOTIFY_USE_TRANSPORT_MODE:
notify_name = "use_transport_mode";
showspi = 0;
break;
case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED:
notify_name = "http_cert_lookup_supported";
showspi = 0;
break;
case IV2_NOTIFY_REKEY_SA:
notify_name = "rekey_sa";
showspi = 1;
break;
case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED:
notify_name = "tfc_padding_not_supported";
showspi = 0;
break;
case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO:
notify_name = "non_first_fragment_also";
showspi = 0;
break;
default:
if (type < 8192) {
notify_name="error";
} else if(type < 16384) {
notify_name="private-error";
} else if(type < 40960) {
notify_name="status";
} else {
notify_name="private-status";
}
}
if(notify_name) {
ND_PRINT((ndo," type=%u(%s)", type, notify_name));
}
if (showspi && n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
if (cp < ep) {
if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else if (showsomedata) {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
static const u_char *
ikev2_d_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_vid_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
const u_char *vid;
int i, len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4));
vid = (const u_char *)(ext+1);
len = ntohs(e.len) - 4;
ND_TCHECK2(*vid, len);
for(i=0; i<len; i++) {
if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i]));
else ND_PRINT((ndo, "."));
}
if (2 < ndo->ndo_vflag && 4 < len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_TS_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_e_print(netdissect_options *ndo,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
struct isakmp *base,
u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t phase,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t doi,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t proto,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
int depth)
{
struct isakmp_gen e;
const u_char *dat;
volatile int dlen;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
dlen = ntohs(e.len)-4;
ND_PRINT((ndo," len=%d", dlen));
if (2 < ndo->ndo_vflag && 4 < dlen) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen))
goto trunc;
}
dat = (const u_char *)(ext+1);
ND_TCHECK2(*dat, dlen);
#ifdef HAVE_LIBCRYPTO
/* try to decypt it! */
if(esp_print_decrypt_buffer_by_ikev2(ndo,
base->flags & ISAKMP_FLAG_I,
base->i_ck, base->r_ck,
dat, dat+dlen)) {
ext = (const struct isakmp_gen *)ndo->ndo_packetp;
/* got it decrypted, print stuff inside. */
ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend,
phase, doi, proto, depth+1);
}
#endif
/* always return NULL, because E must be at end, and NP refers
* to what was inside.
*/
return NULL;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_cp_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_eap_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ike_sub0_print(netdissect_options *ndo,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
struct isakmp_gen e;
u_int item_len;
cp = (const u_char *)ext;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
return NULL;
if (NPFUNC(np)) {
/*
* XXX - what if item_len is too short, or too long,
* for this payload type?
*/
cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth);
} else {
ND_PRINT((ndo,"%s", NPSTR(np)));
cp += item_len;
}
return cp;
trunc:
ND_PRINT((ndo," [|isakmp]"));
return NULL;
}
static const u_char *
ikev1_sub_print(netdissect_options *ndo,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
static char *
numstr(int x)
{
static char buf[20];
snprintf(buf, sizeof(buf), "#%d", x);
return buf;
}
static void
ikev1_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2, struct isakmp *base)
{
const struct isakmp *p;
const u_char *ep;
u_char np;
int i;
int phase;
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2;
if (phase == 1)
ND_PRINT((ndo," phase %d", phase));
else
ND_PRINT((ndo," phase %d/others", phase));
i = cookie_find(&base->i_ck);
if (i < 0) {
if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) {
/* the first packet */
ND_PRINT((ndo," I"));
if (bp2)
cookie_record(&base->i_ck, bp2);
} else
ND_PRINT((ndo," ?"));
} else {
if (bp2 && cookie_isinitiator(i, bp2))
ND_PRINT((ndo," I"));
else if (bp2 && cookie_isresponder(i, bp2))
ND_PRINT((ndo," R"));
else
ND_PRINT((ndo," ?"));
}
ND_PRINT((ndo," %s", ETYPESTR(base->etype)));
if (base->flags) {
ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "",
base->flags & ISAKMP_FLAG_C ? "C" : ""));
}
if (ndo->ndo_vflag) {
const struct isakmp_gen *ext;
ND_PRINT((ndo,":"));
/* regardless of phase... */
if (base->flags & ISAKMP_FLAG_E) {
/*
* encrypted, nothing we can do right now.
* we hope to decrypt the packet in the future...
*/
ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np)));
goto done;
}
CHECKLEN(p + 1, base->np);
np = base->np;
ext = (const struct isakmp_gen *)(p + 1);
ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0);
}
done:
if (ndo->ndo_vflag) {
if (ntohl(base->len) != length) {
ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)",
(uint32_t)ntohl(base->len), length));
}
}
}
static const u_char *
ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base,
u_char np,
const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
struct isakmp_gen e;
u_int item_len;
cp = (const u_char *)ext;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
return NULL;
if (np == ISAKMP_NPTYPE_v2E) {
cp = ikev2_e_print(ndo, base, np, ext, item_len,
ep, phase, doi, proto, depth);
} else if (NPFUNC(np)) {
/*
* XXX - what if item_len is too short, or too long,
* for this payload type?
*/
cp = (*npfunc[np])(ndo, np, ext, item_len,
ep, phase, doi, proto, depth);
} else {
ND_PRINT((ndo,"%s", NPSTR(np)));
cp += item_len;
}
return cp;
trunc:
ND_PRINT((ndo," [|isakmp]"));
return NULL;
}
static const u_char *
ikev2_sub_print(netdissect_options *ndo,
struct isakmp *base,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ikev2_sub0_print(ndo, base, np,
ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
static void
ikev2_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2 _U_, struct isakmp *base)
{
const struct isakmp *p;
const u_char *ep;
u_char np;
int phase;
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2;
if (phase == 1)
ND_PRINT((ndo, " parent_sa"));
else
ND_PRINT((ndo, " child_sa "));
ND_PRINT((ndo, " %s", ETYPESTR(base->etype)));
if (base->flags) {
ND_PRINT((ndo, "[%s%s%s]",
base->flags & ISAKMP_FLAG_I ? "I" : "",
base->flags & ISAKMP_FLAG_V ? "V" : "",
base->flags & ISAKMP_FLAG_R ? "R" : ""));
}
if (ndo->ndo_vflag) {
const struct isakmp_gen *ext;
ND_PRINT((ndo, ":"));
/* regardless of phase... */
if (base->flags & ISAKMP_FLAG_E) {
/*
* encrypted, nothing we can do right now.
* we hope to decrypt the packet in the future...
*/
ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np)));
goto done;
}
CHECKLEN(p + 1, base->np)
np = base->np;
ext = (const struct isakmp_gen *)(p + 1);
ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0);
}
done:
if (ndo->ndo_vflag) {
if (ntohl(base->len) != length) {
ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)",
(uint32_t)ntohl(base->len), length));
}
}
}
void
isakmp_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2)
{
const struct isakmp *p;
struct isakmp base;
const u_char *ep;
int major, minor;
#ifdef HAVE_LIBCRYPTO
/* initialize SAs */
if (ndo->ndo_sa_list_head == NULL) {
if (ndo->ndo_espsecret)
esp_print_decodesecret(ndo);
}
#endif
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
if ((const struct isakmp *)ep < p + 1) {
ND_PRINT((ndo,"[|isakmp]"));
return;
}
UNALIGNED_MEMCPY(&base, p, sizeof(base));
ND_PRINT((ndo,"isakmp"));
major = (base.vers & ISAKMP_VERS_MAJOR)
>> ISAKMP_VERS_MAJOR_SHIFT;
minor = (base.vers & ISAKMP_VERS_MINOR)
>> ISAKMP_VERS_MINOR_SHIFT;
if (ndo->ndo_vflag) {
ND_PRINT((ndo," %d.%d", major, minor));
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo," msgid "));
hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid));
}
if (1 < ndo->ndo_vflag) {
ND_PRINT((ndo," cookie "));
hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck));
ND_PRINT((ndo,"->"));
hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck));
}
ND_PRINT((ndo,":"));
switch(major) {
case IKEv1_MAJOR_VERSION:
ikev1_print(ndo, bp, length, bp2, &base);
break;
case IKEv2_MAJOR_VERSION:
ikev2_print(ndo, bp, length, bp2, &base);
break;
}
}
void
isakmp_rfc3948_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2)
{
ND_TCHECK(bp[0]);
if(length == 1 && bp[0]==0xff) {
ND_PRINT((ndo, "isakmp-nat-keep-alive"));
return;
}
if(length < 4) {
goto trunc;
}
ND_TCHECK(bp[3]);
/*
* see if this is an IKE packet
*/
if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) {
ND_PRINT((ndo, "NONESP-encap: "));
isakmp_print(ndo, bp+4, length-4, bp2);
return;
}
/* must be an ESP packet */
{
int nh, enh, padlen;
int advance;
ND_PRINT((ndo, "UDP-encap: "));
advance = esp_print(ndo, bp, length, bp2, &enh, &padlen);
if(advance <= 0)
return;
bp += advance;
length -= advance + padlen;
nh = enh & 0xff;
ip_print_inner(ndo, bp, length, nh, bp2);
return;
}
trunc:
ND_PRINT((ndo,"[|isakmp]"));
return;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2715_0 |
crossvul-cpp_data_bad_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:
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/bad_266_0 |
crossvul-cpp_data_good_2674_0 | /*
* Copyright (c) 2009
* Siemens AG, All rights reserved.
* Dmitry Eremin-Solenikov (dbaryshkov@gmail.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IEEE 802.15.4 printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static const char *ftypes[] = {
"Beacon", /* 0 */
"Data", /* 1 */
"ACK", /* 2 */
"Command", /* 3 */
"Reserved (0x4)", /* 4 */
"Reserved (0x5)", /* 5 */
"Reserved (0x6)", /* 6 */
"Reserved (0x7)", /* 7 */
};
/*
* Frame Control subfields.
*/
#define FC_FRAME_TYPE(fc) ((fc) & 0x7)
#define FC_SECURITY_ENABLED 0x0008
#define FC_FRAME_PENDING 0x0010
#define FC_ACK_REQUEST 0x0020
#define FC_PAN_ID_COMPRESSION 0x0040
#define FC_DEST_ADDRESSING_MODE(fc) (((fc) >> 10) & 0x3)
#define FC_FRAME_VERSION(fc) (((fc) >> 12) & 0x3)
#define FC_SRC_ADDRESSING_MODE(fc) (((fc) >> 14) & 0x3)
#define FC_ADDRESSING_MODE_NONE 0x00
#define FC_ADDRESSING_MODE_RESERVED 0x01
#define FC_ADDRESSING_MODE_SHORT 0x02
#define FC_ADDRESSING_MODE_LONG 0x03
u_int
ieee802_15_4_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int hdrlen;
uint16_t fc;
uint8_t seq;
uint16_t panid = 0;
if (caplen < 3) {
ND_PRINT((ndo, "[|802.15.4]"));
return caplen;
}
hdrlen = 3;
fc = EXTRACT_LE_16BITS(p);
seq = EXTRACT_LE_8BITS(p + 2);
p += 3;
caplen -= 3;
ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)]));
if (ndo->ndo_vflag)
ND_PRINT((ndo,"seq %02x ", seq));
/*
* Destination address and PAN ID, if present.
*/
switch (FC_DEST_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (fc & FC_PAN_ID_COMPRESSION) {
/*
* PAN ID compression; this requires that both
* the source and destination addresses be present,
* but the destination address is missing.
*/
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved destination addressing mode"));
return hdrlen;
case FC_ADDRESSING_MODE_SHORT:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p + 2)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"< "));
/*
* Source address and PAN ID, if present.
*/
switch (FC_SRC_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved source addressing mode"));
return 0;
case FC_ADDRESSING_MODE_SHORT:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
return hdrlen;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2674_0 |
crossvul-cpp_data_bad_629_0 | ////////////////////////////////////////////////////////////////////////////
// **** WAVPACK **** //
// Hybrid Lossless Wavefile Compressor //
// Copyright (c) 1998 - 2016 David Bryant. //
// All Rights Reserved. //
// Distributed under the BSD Software License (see license.txt) //
////////////////////////////////////////////////////////////////////////////
// caff.c
// This module is a helper to the WavPack command-line programs to support CAF files.
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <math.h>
#include <stdio.h>
#include <ctype.h>
#include "wavpack.h"
#include "utils.h"
#include "md5.h"
#ifdef _WIN32
#define strdup(x) _strdup(x)
#endif
#define WAVPACK_NO_ERROR 0
#define WAVPACK_SOFT_ERROR 1
#define WAVPACK_HARD_ERROR 2
extern int debug_logging_mode;
typedef struct
{
char mFileType [4];
uint16_t mFileVersion;
uint16_t mFileFlags;
} CAFFileHeader;
#define CAFFileHeaderFormat "4SS"
#pragma pack(push,4)
typedef struct
{
char mChunkType [4];
int64_t mChunkSize;
} CAFChunkHeader;
#pragma pack(pop)
#define CAFChunkHeaderFormat "4D"
typedef struct
{
double mSampleRate;
char mFormatID [4];
uint32_t mFormatFlags;
uint32_t mBytesPerPacket;
uint32_t mFramesPerPacket;
uint32_t mChannelsPerFrame;
uint32_t mBitsPerChannel;
} CAFAudioFormat;
#define CAFAudioFormatFormat "D4LLLLL"
#define CAF_FORMAT_FLOAT 0x1
#define CAF_FORMAT_LITTLE_ENDIAN 0x2
typedef struct
{
uint32_t mChannelLayoutTag;
uint32_t mChannelBitmap;
uint32_t mNumberChannelDescriptions;
} CAFChannelLayout;
#define CAFChannelLayoutFormat "LLL"
enum {
kCAFChannelLayoutTag_UseChannelDescriptions = (0<<16) | 0, // use the array of AudioChannelDescriptions to define the mapping.
kCAFChannelLayoutTag_UseChannelBitmap = (1<<16) | 0, // use the bitmap to define the mapping.
};
typedef struct
{
uint32_t mChannelLabel;
uint32_t mChannelFlags;
float mCoordinates [3];
} CAFChannelDescription;
#define CAFChannelDescriptionFormat "LLLLL"
static const char TMH_full [] = { 1,2,3,13,9,10,5,6,12,14,15,16,17,9,4,18,7,8,19,20,21 };
static const char TMH_std [] = { 1,2,3,11,8,9,5,6,10,12,13,14,15,7,4,16 };
static struct {
uint32_t mChannelLayoutTag; // Core Audio layout, 100 - 146 in high word, num channels in low word
uint32_t mChannelBitmap; // Microsoft standard mask (for those channels that appear)
const char *mChannelReorder; // reorder string if layout is NOT in Microsoft standard order
const char *mChannelIdentities; // identities of any channels NOT in Microsoft standard
} layouts [] = {
{ (100<<16) | 1, 0x004, NULL, NULL }, // FC
{ (101<<16) | 2, 0x003, NULL, NULL }, // FL, FR
{ (102<<16) | 2, 0x003, NULL, NULL }, // FL, FR (headphones)
{ (103<<16) | 2, 0x000, NULL, "\46\47" }, // [Lt, Rt] (matrix encoded)
{ (104<<16) | 2, 0x000, NULL, "\314\315" }, // [Mid, Side]
{ (105<<16) | 2, 0x000, NULL, "\316\317" }, // [X, Y]
{ (106<<16) | 2, 0x003, NULL, NULL }, // FL, FR (binaural)
{ (107<<16) | 4, 0x000, NULL, "\310\311\312\313" }, // [W, X, Y, Z] (ambisonics)
{ (108<<16) | 4, 0x033, NULL, NULL }, // FL, FR, BL, BR (quad)
{ (109<<16) | 5, 0x037, "12453", NULL }, // FL, FR, BL, BR, FC (pentagonal)
{ (110<<16) | 6, 0x137, "124536", NULL }, // FL, FR, BL, BR, FC, BC (hexagonal)
{ (111<<16) | 8, 0x737, "12453678", NULL }, // FL, FR, BL, BR, FC, BC, SL, SR (octagonal)
{ (112<<16) | 8, 0x2d033, NULL, NULL }, // FL, FR, BL, BR, TFL, TFR, TBL, TBR (cubic)
{ (113<<16) | 3, 0x007, NULL, NULL }, // FL, FR, FC
{ (114<<16) | 3, 0x007, "312", NULL }, // FC, FL, FR
{ (115<<16) | 4, 0x107, NULL, NULL }, // FL, FR, FC, BC
{ (116<<16) | 4, 0x107, "3124", NULL }, // FC, FL, FR, BC
{ (117<<16) | 5, 0x037, NULL, NULL }, // FL, FR, FC, BL, BR
{ (118<<16) | 5, 0x037, "12453", NULL }, // FL, FR, BL, BR, FC
{ (119<<16) | 5, 0x037, "13245", NULL }, // FL, FC, FR, BL, BR
{ (120<<16) | 5, 0x037, "31245", NULL }, // FC, FL, FR, BL, BR
{ (121<<16) | 6, 0x03f, NULL, NULL }, // FL, FR, FC, LFE, BL, BR
{ (122<<16) | 6, 0x03f, "125634", NULL }, // FL, FR, BL, BR, FC, LFE
{ (123<<16) | 6, 0x03f, "132564", NULL }, // FL, FC, FR, BL, BR, LFE
{ (124<<16) | 6, 0x03f, "312564", NULL }, // FC, FL, FR, BL, BR, LFE
{ (125<<16) | 7, 0x13f, NULL, NULL }, // FL, FR, FC, LFE, BL, BR, BC
{ (126<<16) | 8, 0x0ff, NULL, NULL }, // FL, FR, FC, LFE, BL, BR, FLC, FRC
{ (127<<16) | 8, 0x0ff, "37812564", NULL }, // FC, FLC, FRC, FL, FR, BL, BR, LFE
{ (128<<16) | 8, 0x03f, NULL, "\41\42" }, // FL, FR, FC, LFE, BL, BR, [Rls, Rrs]
{ (129<<16) | 8, 0x0ff, "12563478", NULL }, // FL, FR, BL, BR, FC, LFE, FLC, FRC
{ (130<<16) | 8, 0x03f, NULL, "\46\47" }, // FL, FR, FC, LFE, BL, BR, [Lt, Rt]
{ (131<<16) | 3, 0x103, NULL, NULL }, // FL, FR, BC
{ (132<<16) | 4, 0x033, NULL, NULL }, // FL, FR, BL, BR
{ (133<<16) | 3, 0x00B, NULL, NULL }, // FL, FR, LFE
{ (134<<16) | 4, 0x10B, NULL, NULL }, // FL, FR, LFE, BC
{ (135<<16) | 5, 0x03B, NULL, NULL }, // FL, FR, LFE, BL, BR
{ (136<<16) | 4, 0x00F, NULL, NULL }, // FL, FR, FC, LFE
{ (137<<16) | 5, 0x10f, NULL, NULL }, // FL, FR, FC, LFE, BC
{ (138<<16) | 5, 0x03b, "12453", NULL }, // FL, FR, BL, BR, LFE
{ (139<<16) | 6, 0x137, "124536", NULL }, // FL, FR, BL, BR, FC, BC
{ (140<<16) | 7, 0x037, "1245367", "\41\42" }, // FL, FR, BL, BR, FC, [Rls, Rrs]
{ (141<<16) | 6, 0x137, "312456", NULL }, // FC, FL, FR, BL, BR, BC
{ (142<<16) | 7, 0x13f, "3125674", NULL }, // FC, FL, FR, BL, BR, BC, LFE
{ (143<<16) | 7, 0x037, "3124567", "\41\42" }, // FC, FL, FR, BL, BR, [Rls, Rrs]
{ (144<<16) | 8, 0x137, "31245786", "\41\42" }, // FC, FL, FR, BL, BR, [Rls, Rrs], BC
{ (145<<16) | 16, 0x773f, TMH_std, "\43\44\54\45" }, // FL, FR, FC, TFC, SL, SR, BL, BR, TFL, TFR, [Lw, Rw, Csd], BC, LFE, [LFE2]
{ (146<<16) | 21, 0x77ff, TMH_full, "\43\44\54\45" }, // FL, FR, FC, TFC, SL, SR, BL, BR, TFL, TFR, [Lw, Rw, Csd], BC, LFE, [LFE2],
// FLC, FRC, [HI, VI, Haptic]
};
#define NUM_LAYOUTS (sizeof (layouts) / sizeof (layouts [0]))
int ParseCaffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
uint32_t chan_chunk = 0, channel_layout = 0, bcount;
unsigned char *channel_identities = NULL;
unsigned char *channel_reorder = NULL;
int64_t total_samples = 0, infilesize;
CAFFileHeader caf_file_header;
CAFChunkHeader caf_chunk_header;
CAFAudioFormat caf_audio_format;
int i;
infilesize = DoGetFileSize (infile);
memcpy (&caf_file_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &caf_file_header) + 4, sizeof (CAFFileHeader) - 4, &bcount) ||
bcount != sizeof (CAFFileHeader) - 4)) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &caf_file_header, sizeof (CAFFileHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&caf_file_header, CAFFileHeaderFormat);
if (caf_file_header.mFileVersion != 1) {
error_line ("%s: can't handle version %d .CAF files!", infilename, caf_file_header.mFileVersion);
return WAVPACK_SOFT_ERROR;
}
// loop through all elements of the RIFF wav header
// (until the data chuck) and copy them to the output file
while (1) {
if (!DoReadFile (infile, &caf_chunk_header, sizeof (CAFChunkHeader), &bcount) ||
bcount != sizeof (CAFChunkHeader)) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &caf_chunk_header, sizeof (CAFChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&caf_chunk_header, CAFChunkHeaderFormat);
// if it's the format chunk, we want to get some info out of there and
// make sure it's a .caf file we can handle
if (!strncmp (caf_chunk_header.mChunkType, "desc", 4)) {
int supported = TRUE;
if (caf_chunk_header.mChunkSize != sizeof (CAFAudioFormat) ||
!DoReadFile (infile, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize, &bcount) ||
bcount != caf_chunk_header.mChunkSize) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&caf_audio_format, CAFAudioFormatFormat);
if (debug_logging_mode) {
char formatstr [5];
memcpy (formatstr, caf_audio_format.mFormatID, 4);
formatstr [4] = 0;
error_line ("format = %s, flags = %x, sampling rate = %g",
formatstr, caf_audio_format.mFormatFlags, caf_audio_format.mSampleRate);
error_line ("packet = %d bytes and %d frames",
caf_audio_format.mBytesPerPacket, caf_audio_format.mFramesPerPacket);
error_line ("channels per frame = %d, bits per channel = %d",
caf_audio_format.mChannelsPerFrame, caf_audio_format.mBitsPerChannel);
}
if (strncmp (caf_audio_format.mFormatID, "lpcm", 4) || (caf_audio_format.mFormatFlags & ~3))
supported = FALSE;
else if (caf_audio_format.mSampleRate < 1.0 || caf_audio_format.mSampleRate > 16777215.0 ||
caf_audio_format.mSampleRate != floor (caf_audio_format.mSampleRate))
supported = FALSE;
else if (!caf_audio_format.mChannelsPerFrame || caf_audio_format.mChannelsPerFrame > 256)
supported = FALSE;
else if (caf_audio_format.mBitsPerChannel < 1 || caf_audio_format.mBitsPerChannel > 32 ||
((caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) && caf_audio_format.mBitsPerChannel != 32))
supported = FALSE;
else if (caf_audio_format.mFramesPerPacket != 1 ||
caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame < (caf_audio_format.mBitsPerChannel + 7) / 8 ||
caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame > 4 ||
caf_audio_format.mBytesPerPacket % caf_audio_format.mChannelsPerFrame)
supported = FALSE;
if (!supported) {
error_line ("%s is an unsupported .CAF format!", infilename);
return WAVPACK_SOFT_ERROR;
}
config->bytes_per_sample = caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame;
config->float_norm_exp = (caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) ? 127 : 0;
config->bits_per_sample = caf_audio_format.mBitsPerChannel;
config->num_channels = caf_audio_format.mChannelsPerFrame;
config->sample_rate = (int) caf_audio_format.mSampleRate;
if (!(caf_audio_format.mFormatFlags & CAF_FORMAT_LITTLE_ENDIAN) && config->bytes_per_sample > 1)
config->qmode |= QMODE_BIG_ENDIAN;
if (config->bytes_per_sample == 1)
config->qmode |= QMODE_SIGNED_BYTES;
if (debug_logging_mode) {
if (config->float_norm_exp == 127)
error_line ("data format: 32-bit %s-endian floating point", (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little");
else
error_line ("data format: %d-bit %s-endian integers stored in %d byte(s)",
config->bits_per_sample, (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little", config->bytes_per_sample);
}
}
else if (!strncmp (caf_chunk_header.mChunkType, "chan", 4)) {
CAFChannelLayout *caf_channel_layout = malloc ((size_t) caf_chunk_header.mChunkSize);
if (caf_chunk_header.mChunkSize < sizeof (CAFChannelLayout) ||
!DoReadFile (infile, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize, &bcount) ||
bcount != caf_chunk_header.mChunkSize) {
error_line ("%s is not a valid .CAF file!", infilename);
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (caf_channel_layout, CAFChannelLayoutFormat);
chan_chunk = 1;
if (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED)) {
error_line ("this CAF file already has channel order information!");
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
switch (caf_channel_layout->mChannelLayoutTag) {
case kCAFChannelLayoutTag_UseChannelDescriptions:
{
CAFChannelDescription *descriptions = (CAFChannelDescription *) (caf_channel_layout + 1);
int num_descriptions = caf_channel_layout->mNumberChannelDescriptions;
int label, cindex = 0, idents = 0;
if (caf_chunk_header.mChunkSize != sizeof (CAFChannelLayout) + sizeof (CAFChannelDescription) * num_descriptions ||
num_descriptions != config->num_channels) {
error_line ("channel descriptions in 'chan' chunk are the wrong size!");
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
if (num_descriptions >= 256) {
error_line ("%d channel descriptions is more than we can handle...ignoring!");
break;
}
// we allocate (and initialize to invalid values) a channel reorder array
// (even though we might not end up doing any reordering) and a string for
// any non-Microsoft channels we encounter
channel_reorder = malloc (num_descriptions);
memset (channel_reorder, -1, num_descriptions);
channel_identities = malloc (num_descriptions+1);
// convert the descriptions array to our native endian so it's easy to access
for (i = 0; i < num_descriptions; ++i) {
WavpackBigEndianToNative (descriptions + i, CAFChannelDescriptionFormat);
if (debug_logging_mode)
error_line ("chan %d --> %d", i + 1, descriptions [i].mChannelLabel);
}
// first, we go though and find any MS channels present, and move those to the beginning
for (label = 1; label <= 18; ++label)
for (i = 0; i < num_descriptions; ++i)
if (descriptions [i].mChannelLabel == label) {
config->channel_mask |= 1 << (label - 1);
channel_reorder [i] = cindex++;
break;
}
// next, we go though the channels again assigning any we haven't done
for (i = 0; i < num_descriptions; ++i)
if (channel_reorder [i] == (unsigned char) -1) {
uint32_t clabel = descriptions [i].mChannelLabel;
if (clabel == 0 || clabel == 0xffffffff || clabel == 100)
channel_identities [idents++] = 0xff;
else if ((clabel >= 33 && clabel <= 44) || (clabel >= 200 && clabel <= 207) || (clabel >= 301 && clabel <= 305))
channel_identities [idents++] = clabel >= 301 ? clabel - 80 : clabel;
else {
error_line ("warning: unknown channel descriptions label: %d", clabel);
channel_identities [idents++] = 0xff;
}
channel_reorder [i] = cindex++;
}
// then, go through the reordering array and see if we really have to reorder
for (i = 0; i < num_descriptions; ++i)
if (channel_reorder [i] != i)
break;
if (i == num_descriptions) {
free (channel_reorder); // no reordering required, so don't
channel_reorder = NULL;
}
else {
config->qmode |= QMODE_REORDERED_CHANS; // reordering required, put channel count into layout
channel_layout = num_descriptions;
}
if (!idents) { // if no non-MS channels, free the identities string
free (channel_identities);
channel_identities = NULL;
}
else
channel_identities [idents] = 0; // otherwise NULL terminate it
if (debug_logging_mode) {
error_line ("layout_tag = 0x%08x, so generated bitmap of 0x%08x from %d descriptions, %d non-MS",
caf_channel_layout->mChannelLayoutTag, config->channel_mask,
caf_channel_layout->mNumberChannelDescriptions, idents);
// if debugging, display the reordering as a string (but only little ones)
if (channel_reorder && num_descriptions <= 8) {
char reorder_string [] = "12345678";
for (i = 0; i < num_descriptions; ++i)
reorder_string [i] = channel_reorder [i] + '1';
reorder_string [i] = 0;
error_line ("reordering string = \"%s\"\n", reorder_string);
}
}
}
break;
case kCAFChannelLayoutTag_UseChannelBitmap:
config->channel_mask = caf_channel_layout->mChannelBitmap;
if (debug_logging_mode)
error_line ("layout_tag = 0x%08x, so using supplied bitmap of 0x%08x",
caf_channel_layout->mChannelLayoutTag, caf_channel_layout->mChannelBitmap);
break;
default:
for (i = 0; i < NUM_LAYOUTS; ++i)
if (caf_channel_layout->mChannelLayoutTag == layouts [i].mChannelLayoutTag) {
config->channel_mask = layouts [i].mChannelBitmap;
channel_layout = layouts [i].mChannelLayoutTag;
if (layouts [i].mChannelReorder) {
channel_reorder = (unsigned char *) strdup (layouts [i].mChannelReorder);
config->qmode |= QMODE_REORDERED_CHANS;
}
if (layouts [i].mChannelIdentities)
channel_identities = (unsigned char *) strdup (layouts [i].mChannelIdentities);
if (debug_logging_mode)
error_line ("layout_tag 0x%08x found in table, bitmap = 0x%08x, reorder = %s, identities = %s",
channel_layout, config->channel_mask, channel_reorder ? "yes" : "no", channel_identities ? "yes" : "no");
break;
}
if (i == NUM_LAYOUTS && debug_logging_mode)
error_line ("layout_tag 0x%08x not found in table...all channels unassigned",
caf_channel_layout->mChannelLayoutTag);
break;
}
free (caf_channel_layout);
}
else if (!strncmp (caf_chunk_header.mChunkType, "data", 4)) { // on the data chunk, get size and exit loop
uint32_t mEditCount;
if (!DoReadFile (infile, &mEditCount, sizeof (mEditCount), &bcount) ||
bcount != sizeof (mEditCount)) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &mEditCount, sizeof (mEditCount))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
if ((config->qmode & QMODE_IGNORE_LENGTH) || caf_chunk_header.mChunkSize == -1) {
config->qmode |= QMODE_IGNORE_LENGTH;
if (infilesize && DoGetFilePosition (infile) != -1)
total_samples = (infilesize - DoGetFilePosition (infile)) / caf_audio_format.mBytesPerPacket;
else
total_samples = -1;
}
else {
if (infilesize && infilesize - caf_chunk_header.mChunkSize > 16777216) {
error_line (".CAF file %s has over 16 MB of extra CAFF data, probably is corrupt!", infilename);
return WAVPACK_SOFT_ERROR;
}
if ((caf_chunk_header.mChunkSize - 4) % caf_audio_format.mBytesPerPacket) {
error_line (".CAF file %s has an invalid data chunk size, probably is corrupt!", infilename);
return WAVPACK_SOFT_ERROR;
}
total_samples = (caf_chunk_header.mChunkSize - 4) / caf_audio_format.mBytesPerPacket;
if (!total_samples) {
error_line ("this .CAF file has no audio samples, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (total_samples > MAX_WAVPACK_SAMPLES) {
error_line ("%s has too many samples for WavPack!", infilename);
return WAVPACK_SOFT_ERROR;
}
}
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (uint32_t) caf_chunk_header.mChunkSize;
char *buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
caf_chunk_header.mChunkType [0], caf_chunk_header.mChunkType [1], caf_chunk_header.mChunkType [2],
caf_chunk_header.mChunkType [3], caf_chunk_header.mChunkSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (!chan_chunk && !config->channel_mask && config->num_channels <= 2 && !(config->qmode & QMODE_CHANS_UNASSIGNED))
config->channel_mask = 0x5 - config->num_channels;
if (!WavpackSetConfiguration64 (wpc, config, total_samples, channel_identities)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
if (channel_identities)
free (channel_identities);
if (channel_layout || channel_reorder) {
if (!WavpackSetChannelLayout (wpc, channel_layout, channel_reorder)) {
error_line ("problem with setting channel layout (should not happen)");
return WAVPACK_SOFT_ERROR;
}
if (channel_reorder)
free (channel_reorder);
}
return WAVPACK_NO_ERROR;
}
int WriteCaffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode)
{
CAFChunkHeader caf_desc_chunk_header, caf_chan_chunk_header, caf_data_chunk_header;
CAFChannelLayout caf_channel_layout;
CAFAudioFormat caf_audio_format;
CAFFileHeader caf_file_header;
uint32_t mEditCount, bcount;
int num_channels = WavpackGetNumChannels (wpc);
int32_t channel_mask = WavpackGetChannelMask (wpc);
int32_t sample_rate = WavpackGetSampleRate (wpc);
int bytes_per_sample = WavpackGetBytesPerSample (wpc);
int bits_per_sample = WavpackGetBitsPerSample (wpc);
int float_norm_exp = WavpackGetFloatNormExp (wpc);
uint32_t channel_layout_tag = WavpackGetChannelLayout (wpc, NULL);
unsigned char *channel_identities = malloc (num_channels + 1);
int num_identified_chans, i;
if (float_norm_exp && float_norm_exp != 127) {
error_line ("can't create valid CAFF header for non-normalized floating data!");
free (channel_identities);
return FALSE;
}
// get the channel identities (including Microsoft) and count up the defined ones
WavpackGetChannelIdentities (wpc, channel_identities);
for (num_identified_chans = i = 0; i < num_channels; ++i)
if (channel_identities [i] != 0xff)
num_identified_chans++;
// format and write the CAF File Header
strncpy (caf_file_header.mFileType, "caff", sizeof (caf_file_header.mFileType));
caf_file_header.mFileVersion = 1;
caf_file_header.mFileFlags = 0;
WavpackNativeToBigEndian (&caf_file_header, CAFFileHeaderFormat);
if (!DoWriteFile (outfile, &caf_file_header, sizeof (caf_file_header), &bcount) ||
bcount != sizeof (caf_file_header))
return FALSE;
// format and write the Audio Description Chunk
strncpy (caf_desc_chunk_header.mChunkType, "desc", sizeof (caf_desc_chunk_header.mChunkType));
caf_desc_chunk_header.mChunkSize = sizeof (caf_audio_format);
WavpackNativeToBigEndian (&caf_desc_chunk_header, CAFChunkHeaderFormat);
if (!DoWriteFile (outfile, &caf_desc_chunk_header, sizeof (caf_desc_chunk_header), &bcount) ||
bcount != sizeof (caf_desc_chunk_header))
return FALSE;
caf_audio_format.mSampleRate = (double) sample_rate;
strncpy (caf_audio_format.mFormatID, "lpcm", sizeof (caf_audio_format.mFormatID));
caf_audio_format.mFormatFlags = float_norm_exp ? CAF_FORMAT_FLOAT : 0;
if (!(qmode & QMODE_BIG_ENDIAN))
caf_audio_format.mFormatFlags |= CAF_FORMAT_LITTLE_ENDIAN;
caf_audio_format.mBytesPerPacket = bytes_per_sample * num_channels;
caf_audio_format.mFramesPerPacket = 1;
caf_audio_format.mChannelsPerFrame = num_channels;
caf_audio_format.mBitsPerChannel = bits_per_sample;
WavpackNativeToBigEndian (&caf_audio_format, CAFAudioFormatFormat);
if (!DoWriteFile (outfile, &caf_audio_format, sizeof (caf_audio_format), &bcount) ||
bcount != sizeof (caf_audio_format))
return FALSE;
// we write the Channel Layout Chunk if any of these are true:
// 1. a specific CAF layout was specified (100 - 147)
// 2. there are more than 2 channels and ANY are defined
// 3. there are 1 or 2 channels and NOT regular mono/stereo
if (channel_layout_tag || (num_channels > 2 ? num_identified_chans : channel_mask != 5 - num_channels)) {
int bits = 0, bmask;
for (bmask = 1; bmask; bmask <<= 1) // count the set bits in the channel mask
if (bmask & channel_mask)
++bits;
// we use a layout tag if there is a specific CAF layout (100 - 147) or
// all the channels are MS defined and in MS order...otherwise we have to
// write a full channel description array
if ((channel_layout_tag & 0xff0000) || (bits == num_channels && !(qmode & QMODE_REORDERED_CHANS))) {
strncpy (caf_chan_chunk_header.mChunkType, "chan", sizeof (caf_chan_chunk_header.mChunkType));
caf_chan_chunk_header.mChunkSize = sizeof (caf_channel_layout);
WavpackNativeToBigEndian (&caf_chan_chunk_header, CAFChunkHeaderFormat);
if (!DoWriteFile (outfile, &caf_chan_chunk_header, sizeof (caf_chan_chunk_header), &bcount) ||
bcount != sizeof (caf_chan_chunk_header))
return FALSE;
if (channel_layout_tag) {
if (debug_logging_mode)
error_line ("writing \"chan\" chunk with layout tag 0x%08x", channel_layout_tag);
caf_channel_layout.mChannelLayoutTag = channel_layout_tag;
caf_channel_layout.mChannelBitmap = 0;
}
else {
if (debug_logging_mode)
error_line ("writing \"chan\" chunk with UseChannelBitmap tag, bitmap = 0x%08x", channel_mask);
caf_channel_layout.mChannelLayoutTag = kCAFChannelLayoutTag_UseChannelBitmap;
caf_channel_layout.mChannelBitmap = channel_mask;
}
caf_channel_layout.mNumberChannelDescriptions = 0;
WavpackNativeToBigEndian (&caf_channel_layout, CAFChannelLayoutFormat);
if (!DoWriteFile (outfile, &caf_channel_layout, sizeof (caf_channel_layout), &bcount) ||
bcount != sizeof (caf_channel_layout))
return FALSE;
}
else { // write a channel description array because a single layout or bitmap won't do it...
CAFChannelDescription caf_channel_description;
unsigned char *new_channel_order = NULL;
int i;
if (debug_logging_mode)
error_line ("writing \"chan\" chunk with UseChannelDescriptions tag, bitmap = 0x%08x, reordered = %s",
channel_mask, (qmode & QMODE_REORDERED_CHANS) ? "yes" : "no");
if (qmode & QMODE_REORDERED_CHANS) {
if ((int)(channel_layout_tag & 0xff) <= num_channels) {
new_channel_order = malloc (num_channels);
for (i = 0; i < num_channels; ++i)
new_channel_order [i] = i;
WavpackGetChannelLayout (wpc, new_channel_order);
}
}
strncpy (caf_chan_chunk_header.mChunkType, "chan", sizeof (caf_chan_chunk_header.mChunkType));
caf_chan_chunk_header.mChunkSize = sizeof (caf_channel_layout) + sizeof (caf_channel_description) * num_channels;
WavpackNativeToBigEndian (&caf_chan_chunk_header, CAFChunkHeaderFormat);
if (!DoWriteFile (outfile, &caf_chan_chunk_header, sizeof (caf_chan_chunk_header), &bcount) ||
bcount != sizeof (caf_chan_chunk_header))
return FALSE;
caf_channel_layout.mChannelLayoutTag = kCAFChannelLayoutTag_UseChannelDescriptions;
caf_channel_layout.mChannelBitmap = 0;
caf_channel_layout.mNumberChannelDescriptions = num_channels;
WavpackNativeToBigEndian (&caf_channel_layout, CAFChannelLayoutFormat);
if (!DoWriteFile (outfile, &caf_channel_layout, sizeof (caf_channel_layout), &bcount) ||
bcount != sizeof (caf_channel_layout))
return FALSE;
for (i = 0; i < num_channels; ++i) {
unsigned char chan_id = new_channel_order ? channel_identities [new_channel_order [i]] : channel_identities [i];
CLEAR (caf_channel_description);
if ((chan_id >= 1 && chan_id <= 18) || (chan_id >= 33 && chan_id <= 44) || (chan_id >= 200 && chan_id <= 207))
caf_channel_description.mChannelLabel = chan_id;
else if (chan_id >= 221 && chan_id <= 225)
caf_channel_description.mChannelLabel = chan_id + 80;
if (debug_logging_mode)
error_line ("chan %d --> %d", i + 1, caf_channel_description.mChannelLabel);
WavpackNativeToBigEndian (&caf_channel_description, CAFChannelDescriptionFormat);
if (!DoWriteFile (outfile, &caf_channel_description, sizeof (caf_channel_description), &bcount) ||
bcount != sizeof (caf_channel_description))
return FALSE;
}
if (new_channel_order)
free (new_channel_order);
}
}
// format and write the Audio Data Chunk
strncpy (caf_data_chunk_header.mChunkType, "data", sizeof (caf_data_chunk_header.mChunkType));
if (total_samples == -1)
caf_data_chunk_header.mChunkSize = -1;
else
caf_data_chunk_header.mChunkSize = (total_samples * bytes_per_sample * num_channels) + sizeof (mEditCount);
WavpackNativeToBigEndian (&caf_data_chunk_header, CAFChunkHeaderFormat);
if (!DoWriteFile (outfile, &caf_data_chunk_header, sizeof (caf_data_chunk_header), &bcount) ||
bcount != sizeof (caf_data_chunk_header))
return FALSE;
mEditCount = 0;
WavpackNativeToBigEndian (&mEditCount, "L");
if (!DoWriteFile (outfile, &mEditCount, sizeof (mEditCount), &bcount) ||
bcount != sizeof (mEditCount))
return FALSE;
free (channel_identities);
return TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_629_0 |
crossvul-cpp_data_good_163_1 | /*
* 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/.
*
* ----------------------------------------------------------------------------
* Recursive descent parser for code execution
* ----------------------------------------------------------------------------
*/
#include "jsparse.h"
#include "jsinteractive.h"
#include "jswrapper.h"
#include "jsnative.h"
#include "jswrap_object.h" // for function_replacewith
#include "jswrap_functions.h" // insane check for eval in jspeFunctionCall
#include "jswrap_json.h" // for jsfPrintJSON
#include "jswrap_espruino.h" // for jswrap_espruino_memoryArea
#ifndef SAVE_ON_FLASH
#include "jswrap_regexp.h" // for jswrap_regexp_constructor
#endif
/* Info about execution when Parsing - this saves passing it on the stack
* for each call */
JsExecInfo execInfo;
// ----------------------------------------------- Forward decls
JsVar *jspeAssignmentExpression();
JsVar *jspeExpression();
JsVar *jspeUnaryExpression();
void jspeBlock();
void jspeBlockNoBrackets();
JsVar *jspeStatement();
JsVar *jspeFactor();
void jspEnsureIsPrototype(JsVar *instanceOf, JsVar *prototypeName);
#ifndef SAVE_ON_FLASH
JsVar *jspeArrowFunction(JsVar *funcVar, JsVar *a);
#endif
// ----------------------------------------------- Utils
#define JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, CLEANUP_CODE, RETURN_VAL) { if (!jslMatch((TOKEN))) { CLEANUP_CODE; return RETURN_VAL; } }
#define JSP_MATCH_WITH_RETURN(TOKEN, RETURN_VAL) JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, , RETURN_VAL)
#define JSP_MATCH(TOKEN) JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, , 0) // Match where the user could have given us the wrong token
#define JSP_ASSERT_MATCH(TOKEN) { assert(lex->tk==(TOKEN));jslGetNextToken(); } // Match where if we have the wrong token, it's an internal error
#define JSP_SHOULD_EXECUTE (((execInfo.execute)&EXEC_RUN_MASK)==EXEC_YES)
#define JSP_SAVE_EXECUTE() JsExecFlags oldExecute = execInfo.execute
#define JSP_RESTORE_EXECUTE() execInfo.execute = (execInfo.execute&(JsExecFlags)(~EXEC_SAVE_RESTORE_MASK)) | (oldExecute&EXEC_SAVE_RESTORE_MASK);
#define JSP_HAS_ERROR (((execInfo.execute)&EXEC_ERROR_MASK)!=0)
#define JSP_SHOULDNT_PARSE (((execInfo.execute)&EXEC_NO_PARSE_MASK)!=0)
ALWAYS_INLINE void jspDebuggerLoopIfCtrlC() {
#ifdef USE_DEBUGGER
if (execInfo.execute & EXEC_CTRL_C_WAIT && JSP_SHOULD_EXECUTE)
jsiDebuggerLoop();
#endif
}
/// if interrupting execution, this is set
bool jspIsInterrupted() {
return (execInfo.execute & EXEC_INTERRUPTED)!=0;
}
/// if interrupting execution, this is set
void jspSetInterrupted(bool interrupt) {
if (interrupt)
execInfo.execute = execInfo.execute | EXEC_INTERRUPTED;
else
execInfo.execute = execInfo.execute & (JsExecFlags)~EXEC_INTERRUPTED;
}
/// Set the error flag - set lineReported if we've already output the line number
void jspSetError(bool lineReported) {
execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_YES) | EXEC_ERROR;
if (lineReported)
execInfo.execute |= EXEC_ERROR_LINE_REPORTED;
}
bool jspHasError() {
return JSP_HAS_ERROR;
}
void jspReplaceWith(JsVar *dst, JsVar *src) {
// If this is an index in an array buffer, write directly into the array buffer
if (jsvIsArrayBufferName(dst)) {
size_t idx = (size_t)jsvGetInteger(dst);
JsVar *arrayBuffer = jsvLock(jsvGetFirstChild(dst));
jsvArrayBufferSet(arrayBuffer, idx, src);
jsvUnLock(arrayBuffer);
return;
}
// if destination isn't there, isn't a 'name', or is used, give an error
if (!jsvIsName(dst)) {
jsExceptionHere(JSET_ERROR, "Unable to assign value to non-reference %t", dst);
return;
}
jsvSetValueOfName(dst, src);
/* If dst is flagged as a new child, it means that
* it was previously undefined, and we need to add it to
* the given object when it is set.
*/
if (jsvIsNewChild(dst)) {
// Get what it should have been a child of
JsVar *parent = jsvLock(jsvGetNextSibling(dst));
if (!jsvIsString(parent)) {
// if we can't find a char in a string we still return a NewChild,
// but we can't add character back in
if (!jsvHasChildren(parent)) {
jsExceptionHere(JSET_ERROR, "Field or method \"%s\" does not already exist, and can't create it on %t", dst, parent);
} else {
// Remove the 'new child' flagging
jsvUnRef(parent);
jsvSetNextSibling(dst, 0);
jsvUnRef(parent);
jsvSetPrevSibling(dst, 0);
// Add to the parent
jsvAddName(parent, dst);
}
}
jsvUnLock(parent);
}
}
void jspReplaceWithOrAddToRoot(JsVar *dst, JsVar *src) {
/* If we're assigning to this and we don't have a parent,
* add it to the symbol table root */
if (!jsvGetRefs(dst) && jsvIsName(dst)) {
if (!jsvIsArrayBufferName(dst) && !jsvIsNewChild(dst))
jsvAddName(execInfo.root, dst);
}
jspReplaceWith(dst, src);
}
bool jspeiAddScope(JsVar *scope) {
if (execInfo.scopeCount >= JSPARSE_MAX_SCOPES) {
jsExceptionHere(JSET_ERROR, "Maximum number of scopes exceeded");
jspSetError(false);
return false;
}
execInfo.scopes[execInfo.scopeCount++] = jsvLockAgain(scope);
return true;
}
void jspeiRemoveScope() {
if (execInfo.scopeCount <= 0) {
jsExceptionHere(JSET_INTERNALERROR, "Too many scopes removed");
jspSetError(false);
return;
}
jsvUnLock(execInfo.scopes[--execInfo.scopeCount]);
}
JsVar *jspeiFindInScopes(const char *name) {
int i;
for (i=execInfo.scopeCount-1;i>=0;i--) {
JsVar *ref = jsvFindChildFromString(execInfo.scopes[i], name, false);
if (ref) return ref;
}
return jsvFindChildFromString(execInfo.root, name, false);
}
// TODO: get rid of these, use jspeiGetTopScope instead
JsVar *jspeiFindOnTop(const char *name, bool createIfNotFound) {
if (execInfo.scopeCount>0)
return jsvFindChildFromString(execInfo.scopes[execInfo.scopeCount-1], name, createIfNotFound);
return jsvFindChildFromString(execInfo.root, name, createIfNotFound);
}
JsVar *jspeiFindNameOnTop(JsVar *childName, bool createIfNotFound) {
if (execInfo.scopeCount>0)
return jsvFindChildFromVar(execInfo.scopes[execInfo.scopeCount-1], childName, createIfNotFound);
return jsvFindChildFromVar(execInfo.root, childName, createIfNotFound);
}
/** Here we assume that we have already looked in the parent itself -
* and are now going down looking at the stuff it inherited */
JsVar *jspeiFindChildFromStringInParents(JsVar *parent, const char *name) {
if (jsvIsObject(parent)) {
// If an object, look for an 'inherits' var
JsVar *inheritsFrom = jsvObjectGetChild(parent, JSPARSE_INHERITS_VAR, 0);
// if there's no inheritsFrom, just default to 'Object.prototype'
if (!inheritsFrom) {
JsVar *obj = jsvObjectGetChild(execInfo.root, "Object", 0);
if (obj) {
inheritsFrom = jsvObjectGetChild(obj, JSPARSE_PROTOTYPE_VAR, 0);
jsvUnLock(obj);
}
}
if (inheritsFrom && inheritsFrom!=parent) {
// we have what it inherits from (this is ACTUALLY the prototype var)
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/proto
JsVar *child = jsvFindChildFromString(inheritsFrom, name, false);
if (!child)
child = jspeiFindChildFromStringInParents(inheritsFrom, name);
jsvUnLock(inheritsFrom);
if (child) return child;
} else
jsvUnLock(inheritsFrom);
} else { // Not actually an object - but might be an array/string/etc
const char *objectName = jswGetBasicObjectName(parent);
while (objectName) {
JsVar *objName = jsvFindChildFromString(execInfo.root, objectName, false);
if (objName) {
JsVar *result = 0;
JsVar *obj = jsvSkipNameAndUnLock(objName);
// could be something the user has made - eg. 'Array=1'
if (jsvHasChildren(obj)) {
// We have found an object with this name - search for the prototype var
JsVar *proto = jsvObjectGetChild(obj, JSPARSE_PROTOTYPE_VAR, 0);
if (proto) {
result = jsvFindChildFromString(proto, name, false);
jsvUnLock(proto);
}
}
jsvUnLock(obj);
if (result) return result;
}
/* We haven't found anything in the actual object, we should check the 'Object' itself
eg, we tried 'String', so now we should try 'Object'. Built-in types don't have room for
a prototype field, so we hard-code it */
objectName = jswGetBasicObjectPrototypeName(objectName);
}
}
// no luck!
return 0;
}
JsVar *jspeiGetScopesAsVar() {
if (execInfo.scopeCount==0)
return 0;
if (execInfo.scopeCount==1)
return jsvLockAgain(execInfo.scopes[0]);
JsVar *arr = jsvNewEmptyArray();
int i;
for (i=0;i<execInfo.scopeCount;i++) {
JsVar *idx = jsvMakeIntoVariableName(jsvNewFromInteger(i), execInfo.scopes[i]);
if (!idx) { // out of memory
jspSetError(false);
return arr;
}
jsvAddName(arr, idx);
jsvUnLock(idx);
}
return arr;
}
void jspeiLoadScopesFromVar(JsVar *arr) {
execInfo.scopeCount = 0;
if (jsvIsArray(arr)) {
JsvObjectIterator it;
jsvObjectIteratorNew(&it, arr);
while (jsvObjectIteratorHasValue(&it)) {
execInfo.scopes[execInfo.scopeCount++] = jsvObjectIteratorGetValue(&it);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
} else
execInfo.scopes[execInfo.scopeCount++] = jsvLockAgain(arr);
}
// -----------------------------------------------
bool jspCheckStackPosition() {
if (jsuGetFreeStack() < 512) { // giving us 512 bytes leeway
jsExceptionHere(JSET_ERROR, "Too much recursion - the stack is about to overflow");
jspSetInterrupted(true);
return false;
}
return true;
}
// Set execFlags such that we are not executing
void jspSetNoExecute() {
execInfo.execute = (execInfo.execute & (JsExecFlags)(int)~EXEC_RUN_MASK) | EXEC_NO;
}
void jspAppendStackTrace(JsVar *stackTrace) {
JsvStringIterator it;
jsvStringIteratorNew(&it, stackTrace, 0);
jsvStringIteratorGotoEnd(&it);
jslPrintPosition((vcbprintf_callback)jsvStringIteratorPrintfCallback, &it, lex->tokenLastStart);
jslPrintTokenLineMarker((vcbprintf_callback)jsvStringIteratorPrintfCallback, &it, lex->tokenLastStart, 0);
jsvStringIteratorFree(&it);
}
/// We had an exception (argument is the exception's value)
void jspSetException(JsVar *value) {
// Add the exception itself to a variable in root scope
JsVar *exception = jsvFindChildFromString(execInfo.hiddenRoot, JSPARSE_EXCEPTION_VAR, true);
if (exception) {
jsvSetValueOfName(exception, value);
jsvUnLock(exception);
}
// Set the exception flag
execInfo.execute = execInfo.execute | EXEC_EXCEPTION;
// Try and do a stack trace
if (lex) {
JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0);
if (stackTrace) {
jsvAppendPrintf(stackTrace, " at ");
jspAppendStackTrace(stackTrace);
jsvUnLock(stackTrace);
// stop us from printing the trace in the same block
execInfo.execute = execInfo.execute | EXEC_ERROR_LINE_REPORTED;
}
}
}
/** Return the reported exception if there was one (and clear it) */
JsVar *jspGetException() {
JsVar *exceptionName = jsvFindChildFromString(execInfo.hiddenRoot, JSPARSE_EXCEPTION_VAR, false);
if (exceptionName) {
JsVar *exception = jsvSkipName(exceptionName);
jsvRemoveChild(execInfo.hiddenRoot, exceptionName);
jsvUnLock(exceptionName);
JsVar *stack = jspGetStackTrace();
if (stack && jsvHasChildren(exception)) {
jsvObjectSetChild(exception, "stack", stack);
}
jsvUnLock(stack);
return exception;
}
return 0;
}
/** Return a stack trace string if there was one (and clear it) */
JsVar *jspGetStackTrace() {
JsVar *stackTraceName = jsvFindChildFromString(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, false);
if (stackTraceName) {
JsVar *stackTrace = jsvSkipName(stackTraceName);
jsvRemoveChild(execInfo.hiddenRoot, stackTraceName);
jsvUnLock(stackTraceName);
return stackTrace;
}
return 0;
}
// ----------------------------------------------
// we return a value so that JSP_MATCH can return 0 if it fails (if we pass 0, we just parse all args)
NO_INLINE bool jspeFunctionArguments(JsVar *funcVar) {
JSP_MATCH('(');
while (lex->tk!=')') {
if (funcVar) {
char buf[JSLEX_MAX_TOKEN_LENGTH+1];
buf[0] = '\xFF';
strcpy(&buf[1], jslGetTokenValueAsString(lex));
JsVar *param = jsvAddNamedChild(funcVar, 0, buf);
if (!param) { // out of memory
jspSetError(false);
return false;
}
jsvMakeFunctionParameter(param); // force this to be called a function parameter
jsvUnLock(param);
}
JSP_MATCH(LEX_ID);
if (lex->tk!=')') JSP_MATCH(',');
}
JSP_MATCH(')');
return true;
}
// Parse function, assuming we're on '{'. funcVar can be 0
NO_INLINE bool jspeFunctionDefinitionInternal(JsVar *funcVar, bool expressionOnly) {
if (expressionOnly) {
if (funcVar)
funcVar->flags = (funcVar->flags & ~JSV_VARTYPEMASK) | JSV_FUNCTION_RETURN;
} else {
JSP_MATCH('{');
#ifndef SAVE_ON_FLASH
if (lex->tk==LEX_STR && !strcmp(jslGetTokenValueAsString(lex), "compiled")) {
jsWarn("Function marked with \"compiled\" uploaded in source form");
}
#endif
/* If the function starts with return, treat it specially -
* we don't want to store the 'return' part of it
*/
if (funcVar && lex->tk==LEX_R_RETURN) {
funcVar->flags = (funcVar->flags & ~JSV_VARTYPEMASK) | JSV_FUNCTION_RETURN;
JSP_ASSERT_MATCH(LEX_R_RETURN);
}
}
// Get the line number (if needed)
JsVarInt lineNumber = 0;
if (funcVar && lex->lineNumberOffset) {
// jslGetLineNumber is slow, so we only do it if we have debug info
lineNumber = (JsVarInt)jslGetLineNumber(lex) + (JsVarInt)lex->lineNumberOffset - 1;
}
// Get the code - parse it and figure out where it stops
JslCharPos funcBegin = jslCharPosClone(&lex->tokenStart);
int lastTokenEnd = -1;
if (!expressionOnly) {
int brackets = 0;
while (lex->tk && (brackets || lex->tk != '}')) {
if (lex->tk == '{') brackets++;
if (lex->tk == '}') brackets--;
lastTokenEnd = (int)jsvStringIteratorGetIndex(&lex->it)-1;
JSP_ASSERT_MATCH(lex->tk);
}
} else {
JsExecFlags oldExec = execInfo.execute;
execInfo.execute = EXEC_NO;
jsvUnLock(jspeAssignmentExpression());
execInfo.execute = oldExec;
lastTokenEnd = (int)jsvStringIteratorGetIndex(&lex->tokenStart.it)-1;
}
// Then create var and set (if there was any code!)
if (funcVar && lastTokenEnd>0) {
// code var
JsVar *funcCodeVar;
if (jsvIsNativeString(lex->sourceVar)) {
/* If we're parsing from a Native String (eg. E.memoryArea, E.setBootCode) then
use another Native String to load function code straight from flash */
int s = (int)jsvStringIteratorGetIndex(&funcBegin.it) - 1;
funcCodeVar = jsvNewNativeString(lex->sourceVar->varData.nativeStr.ptr + s, (unsigned int)(lastTokenEnd - s));
} else {
if (jsfGetFlag(JSF_PRETOKENISE)) {
funcCodeVar = jslNewTokenisedStringFromLexer(&funcBegin, (size_t)lastTokenEnd);
} else {
funcCodeVar = jslNewStringFromLexer(&funcBegin, (size_t)lastTokenEnd);
}
}
jsvUnLock2(jsvAddNamedChild(funcVar, funcCodeVar, JSPARSE_FUNCTION_CODE_NAME), funcCodeVar);
// scope var
JsVar *funcScopeVar = jspeiGetScopesAsVar();
if (funcScopeVar) {
jsvUnLock2(jsvAddNamedChild(funcVar, funcScopeVar, JSPARSE_FUNCTION_SCOPE_NAME), funcScopeVar);
}
// If we've got a line number, add a var for it
if (lineNumber) {
JsVar *funcLineNumber = jsvNewFromInteger(lineNumber);
if (funcLineNumber) {
jsvUnLock2(jsvAddNamedChild(funcVar, funcLineNumber, JSPARSE_FUNCTION_LINENUMBER_NAME), funcLineNumber);
}
}
}
jslCharPosFree(&funcBegin);
if (!expressionOnly) JSP_MATCH('}');
return 0;
}
// Parse function (after 'function' has occurred
NO_INLINE JsVar *jspeFunctionDefinition(bool parseNamedFunction) {
// actually parse a function... We assume that the LEX_FUNCTION and name
// have already been parsed
JsVar *funcVar = 0;
bool actuallyCreateFunction = JSP_SHOULD_EXECUTE;
if (actuallyCreateFunction)
funcVar = jsvNewWithFlags(JSV_FUNCTION);
JsVar *functionInternalName = 0;
if (parseNamedFunction && lex->tk==LEX_ID) {
// you can do `var a = function foo() { foo(); };` - so cope with this
if (funcVar) functionInternalName = jslGetTokenValueAsVar(lex);
// note that we don't add it to the beginning, because it would mess up our function call code
JSP_ASSERT_MATCH(LEX_ID);
}
// Get arguments save them to the structure
if (!jspeFunctionArguments(funcVar)) {
jsvUnLock2(functionInternalName, funcVar);
// parse failed
return 0;
}
// Parse the actual function block
jspeFunctionDefinitionInternal(funcVar, false);
// if we had a function name, add it to the end (if we don't it gets confused with arguments)
if (funcVar && functionInternalName)
jsvObjectSetChildAndUnLock(funcVar, JSPARSE_FUNCTION_NAME_NAME, functionInternalName);
return funcVar;
}
/* Parse just the brackets of a function - and throw
* everything away */
NO_INLINE bool jspeParseFunctionCallBrackets() {
assert(!JSP_SHOULD_EXECUTE);
JSP_MATCH('(');
while (!JSP_SHOULDNT_PARSE && lex->tk != ')') {
jsvUnLock(jspeAssignmentExpression());
#ifndef SAVE_ON_FLASH
if (lex->tk==LEX_ARROW_FUNCTION) {
jsvUnLock(jspeArrowFunction(0, 0));
}
#endif
if (lex->tk!=')') JSP_MATCH(',');
}
if (!JSP_SHOULDNT_PARSE) JSP_MATCH(')');
return 0;
}
/** Handle a function call (assumes we've parsed the function name and we're
* on the start bracket). 'thisArg' is the value of the 'this' variable when the
* function is executed (it's usually the parent object)
*
*
* NOTE: this does not set the execInfo flags - so if execInfo==EXEC_NO, it won't execute
*
* If !isParsing and arg0!=0, argument 0 is set to what is supplied (same with arg1)
*
* functionName is used only for error reporting - and can be 0
*/
NO_INLINE JsVar *jspeFunctionCall(JsVar *function, JsVar *functionName, JsVar *thisArg, bool isParsing, int argCount, JsVar **argPtr) {
if (JSP_SHOULD_EXECUTE && !function) {
if (functionName)
jsExceptionHere(JSET_ERROR, "Function %q not found!", functionName);
else
jsExceptionHere(JSET_ERROR, "Function not found!", functionName);
return 0;
}
if (JSP_SHOULD_EXECUTE) if (!jspCheckStackPosition()) return 0; // try and ensure that we won't overflow our stack
if (JSP_SHOULD_EXECUTE && function) {
JsVar *returnVar = 0;
if (!jsvIsFunction(function)) {
jsExceptionHere(JSET_ERROR, "Expecting a function to call, got %t", function);
return 0;
}
JsVar *thisVar = jsvLockAgainSafe(thisArg);
if (isParsing) JSP_MATCH('(');
/* Ok, so we have 4 options here.
*
* 1: we're native.
* a) args have been pre-parsed, which is awesome
* b) we have to parse our own args into an array
* 2: we're not native
* a) args were pre-parsed and we have to populate the function
* b) we parse our own args, which is possibly better
*/
if (jsvIsNative(function)) { // ------------------------------------- NATIVE
unsigned int argPtrSize = 0;
int boundArgs = 0;
// Add 'bound' parameters if there were any
JsvObjectIterator it;
jsvObjectIteratorNew(&it, function);
JsVar *param = jsvObjectIteratorGetKey(&it);
while (jsvIsFunctionParameter(param)) {
if ((unsigned)argCount>=argPtrSize) {
// allocate more space on stack if needed
unsigned int newArgPtrSize = argPtrSize?argPtrSize*4:16;
JsVar **newArgPtr = (JsVar**)alloca(sizeof(JsVar*)*newArgPtrSize);
memcpy(newArgPtr, argPtr, (unsigned)argCount*sizeof(JsVar*));
argPtr = newArgPtr;
argPtrSize = newArgPtrSize;
}
// if we already had arguments - shift them up...
int i;
for (i=argCount-1;i>=boundArgs;i--)
argPtr[i+1] = argPtr[i];
// add bound argument
argPtr[boundArgs] = jsvSkipName(param);
argCount++;
boundArgs++;
jsvUnLock(param);
jsvObjectIteratorNext(&it);
param = jsvObjectIteratorGetKey(&it);
}
// check if 'this' was defined
while (param) {
if (jsvIsStringEqual(param, JSPARSE_FUNCTION_THIS_NAME)) {
jsvUnLock(thisVar);
thisVar = jsvSkipName(param);
break;
}
jsvUnLock(param);
jsvObjectIteratorNext(&it);
param = jsvObjectIteratorGetKey(&it);
}
jsvUnLock(param);
jsvObjectIteratorFree(&it);
// Now, if we're parsing add the rest of the arguments
int allocatedArgCount = boundArgs;
if (isParsing) {
while (!JSP_HAS_ERROR && lex->tk!=')' && lex->tk!=LEX_EOF) {
if ((unsigned)argCount>=argPtrSize) {
// allocate more space on stack
unsigned int newArgPtrSize = argPtrSize?argPtrSize*4:16;
JsVar **newArgPtr = (JsVar**)alloca(sizeof(JsVar*)*newArgPtrSize);
memcpy(newArgPtr, argPtr, (unsigned)argCount*sizeof(JsVar*));
argPtr = newArgPtr;
argPtrSize = newArgPtrSize;
}
argPtr[argCount++] = jsvSkipNameAndUnLock(jspeAssignmentExpression());
if (lex->tk!=')') JSP_MATCH_WITH_CLEANUP_AND_RETURN(',',jsvUnLockMany((unsigned)argCount, argPtr);jsvUnLock(thisVar);, 0);
}
JSP_MATCH(')');
allocatedArgCount = argCount;
}
void *nativePtr = jsvGetNativeFunctionPtr(function);
JsVar *oldThisVar = execInfo.thisVar;
if (thisVar)
execInfo.thisVar = jsvRef(thisVar);
else {
if (nativePtr==jswrap_eval) { // eval gets to use the current scope
/* Note: proper JS has some utterly insane code that depends on whether
* eval is an lvalue or not:
*
* http://stackoverflow.com/questions/9107240/1-evalthis-vs-evalthis-in-javascript
*
* Doing this in Espruino is quite an upheaval for that one
* slightly insane case - so it's not implemented. */
if (execInfo.thisVar) execInfo.thisVar = jsvRef(execInfo.thisVar);
} else {
execInfo.thisVar = jsvRef(execInfo.root); // 'this' should always default to root
}
}
if (nativePtr && !JSP_HAS_ERROR) {
returnVar = jsnCallFunction(nativePtr, function->varData.native.argTypes, thisVar, argPtr, argCount);
} else {
returnVar = 0;
}
// unlock values if we locked them
jsvUnLockMany((unsigned)allocatedArgCount, argPtr);
/* Return to old 'this' var. No need to unlock as we never locked before */
if (execInfo.thisVar) jsvUnRef(execInfo.thisVar);
execInfo.thisVar = oldThisVar;
} else { // ----------------------------------------------------- NOT NATIVE
// create a new symbol table entry for execution of this function
// OPT: can we cache this function execution environment + param variables?
// OPT: Probably when calling a function ONCE, use it, otherwise when recursing, make new?
JsVar *functionRoot = jsvNewWithFlags(JSV_FUNCTION);
if (!functionRoot) { // out of memory
jspSetError(false);
jsvUnLock(thisVar);
return 0;
}
JsVar *functionScope = 0;
JsVar *functionCode = 0;
JsVar *functionInternalName = 0;
uint16_t functionLineNumber = 0;
/** NOTE: We expect that the function object will have:
*
* * Parameters
* * Code/Scope/Name
*
* IN THAT ORDER.
*/
JsvObjectIterator it;
jsvObjectIteratorNew(&it, function);
JsVar *param = jsvObjectIteratorGetKey(&it);
JsVar *value = jsvObjectIteratorGetValue(&it);
while (jsvIsFunctionParameter(param) && value) {
JsVar *paramName = jsvNewFromStringVar(param,1,JSVAPPENDSTRINGVAR_MAXLENGTH);
if (paramName) { // could be out of memory
jsvMakeFunctionParameter(paramName); // force this to be called a function parameter
jsvSetValueOfName(paramName, value);
jsvAddName(functionRoot, paramName);
jsvUnLock(paramName);
} else
jspSetError(false);
jsvUnLock2(value, param);
jsvObjectIteratorNext(&it);
param = jsvObjectIteratorGetKey(&it);
value = jsvObjectIteratorGetValue(&it);
}
jsvUnLock2(value, param);
if (isParsing) {
int hadParams = 0;
// grab in all parameters. We go around this loop until we've run out
// of named parameters AND we've parsed all the supplied arguments
while (!JSP_SHOULDNT_PARSE && lex->tk!=')') {
JsVar *param = jsvObjectIteratorGetKey(&it);
bool paramDefined = jsvIsFunctionParameter(param);
if (lex->tk!=')' || paramDefined) {
hadParams++;
JsVar *value = 0;
// ONLY parse this if it was supplied, otherwise leave 0 (undefined)
if (lex->tk!=')')
value = jspeAssignmentExpression();
// and if execute, copy it over
value = jsvSkipNameAndUnLock(value);
JsVar *paramName = paramDefined ? jsvNewFromStringVar(param,1,JSVAPPENDSTRINGVAR_MAXLENGTH) : jsvNewFromEmptyString();
if (paramName) { // could be out of memory
jsvMakeFunctionParameter(paramName); // force this to be called a function parameter
jsvSetValueOfName(paramName, value);
jsvAddName(functionRoot, paramName);
jsvUnLock(paramName);
} else
jspSetError(false);
jsvUnLock(value);
if (lex->tk!=')') JSP_MATCH(',');
}
jsvUnLock(param);
if (paramDefined) jsvObjectIteratorNext(&it);
}
JSP_MATCH(')');
} else { // and NOT isParsing
int args = 0;
while (args<argCount) {
JsVar *param = jsvObjectIteratorGetKey(&it);
bool paramDefined = jsvIsFunctionParameter(param);
JsVar *paramName = paramDefined ? jsvNewFromStringVar(param,1,JSVAPPENDSTRINGVAR_MAXLENGTH) : jsvNewFromEmptyString();
if (paramName) {
jsvMakeFunctionParameter(paramName); // force this to be called a function parameter
jsvSetValueOfName(paramName, argPtr[args]);
jsvAddName(functionRoot, paramName);
jsvUnLock(paramName);
} else
jspSetError(false);
args++;
jsvUnLock(param);
if (paramDefined) jsvObjectIteratorNext(&it);
}
}
// Now go through what's left
while (jsvObjectIteratorHasValue(&it)) {
JsVar *param = jsvObjectIteratorGetKey(&it);
if (jsvIsString(param)) {
if (jsvIsStringEqual(param, JSPARSE_FUNCTION_SCOPE_NAME)) functionScope = jsvSkipName(param);
else if (jsvIsStringEqual(param, JSPARSE_FUNCTION_CODE_NAME)) functionCode = jsvSkipName(param);
else if (jsvIsStringEqual(param, JSPARSE_FUNCTION_NAME_NAME)) functionInternalName = jsvSkipName(param);
else if (jsvIsStringEqual(param, JSPARSE_FUNCTION_THIS_NAME)) {
jsvUnLock(thisVar);
thisVar = jsvSkipName(param);
} else if (jsvIsStringEqual(param, JSPARSE_FUNCTION_LINENUMBER_NAME)) functionLineNumber = (uint16_t)jsvGetIntegerAndUnLock(jsvSkipName(param));
else if (jsvIsFunctionParameter(param)) {
JsVar *paramName = jsvNewFromStringVar(param,1,JSVAPPENDSTRINGVAR_MAXLENGTH);
// paramName is already a name (it's a function parameter)
if (paramName) {// could be out of memory - or maybe just not supplied!
jsvMakeFunctionParameter(paramName);
JsVar *defaultVal = jsvSkipName(param);
if (defaultVal) jsvUnLock(jsvSetValueOfName(paramName, defaultVal));
jsvAddName(functionRoot, paramName);
jsvUnLock(paramName);
}
}
}
jsvUnLock(param);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
// setup a the function's name (if a named function)
if (functionInternalName) {
JsVar *name = jsvMakeIntoVariableName(jsvNewFromStringVar(functionInternalName,0,JSVAPPENDSTRINGVAR_MAXLENGTH), function);
jsvAddName(functionRoot, name);
jsvUnLock2(name, functionInternalName);
}
if (!JSP_HAS_ERROR) {
// save old scopes
JsVar *oldScopes[JSPARSE_MAX_SCOPES];
int oldScopeCount;
int i;
oldScopeCount = execInfo.scopeCount;
for (i=0;i<execInfo.scopeCount;i++)
oldScopes[i] = execInfo.scopes[i];
// if we have a scope var, load it up. We may not have one if there were no scopes apart from root
if (functionScope) {
jspeiLoadScopesFromVar(functionScope);
jsvUnLock(functionScope);
} else {
// no scope var defined? We have no scopes at all!
execInfo.scopeCount = 0;
}
// add the function's execute space to the symbol table so we can recurse
if (jspeiAddScope(functionRoot)) {
/* Adding scope may have failed - we may have descended too deep - so be sure
* not to pull somebody else's scope off
*/
JsVar *oldThisVar = execInfo.thisVar;
if (thisVar)
execInfo.thisVar = jsvRef(thisVar);
else
execInfo.thisVar = jsvRef(execInfo.root); // 'this' should always default to root
/* we just want to execute the block, but something could
* have messed up and left us with the wrong Lexer, so
* we want to be careful here... */
if (functionCode) {
#ifdef USE_DEBUGGER
bool hadDebuggerNextLineOnly = false;
if (execInfo.execute&EXEC_DEBUGGER_STEP_INTO) {
if (functionName)
jsiConsolePrintf("Stepping into %v\n", functionName);
else
jsiConsolePrintf("Stepping into function\n", functionName);
} else {
hadDebuggerNextLineOnly = execInfo.execute&EXEC_DEBUGGER_NEXT_LINE;
if (hadDebuggerNextLineOnly)
execInfo.execute &= (JsExecFlags)~EXEC_DEBUGGER_NEXT_LINE;
}
#endif
JsLex newLex;
JsLex *oldLex = jslSetLex(&newLex);
jslInit(functionCode);
newLex.lineNumberOffset = functionLineNumber;
JSP_SAVE_EXECUTE();
// force execute without any previous state
#ifdef USE_DEBUGGER
execInfo.execute = EXEC_YES | (execInfo.execute&(EXEC_CTRL_C_MASK|EXEC_ERROR_MASK|EXEC_DEBUGGER_NEXT_LINE));
#else
execInfo.execute = EXEC_YES | (execInfo.execute&(EXEC_CTRL_C_MASK|EXEC_ERROR_MASK));
#endif
if (jsvIsFunctionReturn(function)) {
#ifdef USE_DEBUGGER
// we didn't parse a statement so wouldn't trigger the debugger otherwise
if (execInfo.execute&EXEC_DEBUGGER_NEXT_LINE && JSP_SHOULD_EXECUTE) {
lex->tokenLastStart = jsvStringIteratorGetIndex(&lex->tokenStart.it)-1;
jsiDebuggerLoop();
}
#endif
// implicit return - we just need an expression (optional)
if (lex->tk != ';' && lex->tk != '}')
returnVar = jsvSkipNameAndUnLock(jspeExpression());
} else {
// setup a return variable
JsVar *returnVarName = jsvAddNamedChild(functionRoot, 0, JSPARSE_RETURN_VAR);
// parse the whole block
jspeBlockNoBrackets();
/* get the real return var before we remove it from our function.
* We can unlock below because returnVarName is still part of
* functionRoot, so won't get freed. */
returnVar = jsvSkipNameAndUnLock(returnVarName);
if (returnVarName) // could have failed with out of memory
jsvSetValueOfName(returnVarName, 0); // remove return value (which helps stops circular references)
}
// Store a stack trace if we had an error
JsExecFlags hasError = execInfo.execute&EXEC_ERROR_MASK;
JSP_RESTORE_EXECUTE(); // because return will probably have set execute to false
#ifdef USE_DEBUGGER
bool calledDebugger = false;
if (execInfo.execute & EXEC_DEBUGGER_MASK) {
jsiConsolePrint("Value returned is =");
jsfPrintJSON(returnVar, JSON_LIMIT | JSON_SOME_NEWLINES | JSON_PRETTY | JSON_SHOW_DEVICES);
jsiConsolePrintChar('\n');
if (execInfo.execute & EXEC_DEBUGGER_FINISH_FUNCTION) {
calledDebugger = true;
jsiDebuggerLoop();
}
}
if (hadDebuggerNextLineOnly && !calledDebugger)
execInfo.execute |= EXEC_DEBUGGER_NEXT_LINE;
#endif
jslKill();
jslSetLex(oldLex);
if (hasError) {
execInfo.execute |= hasError; // propogate error
JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0);
if (stackTrace) {
jsvAppendPrintf(stackTrace, jsvIsString(functionName)?"in function %q called from ":
"in function called from ", functionName);
if (lex) {
jspAppendStackTrace(stackTrace);
} else
jsvAppendPrintf(stackTrace, "system\n");
jsvUnLock(stackTrace);
}
}
}
/* Return to old 'this' var. No need to unlock as we never locked before */
if (execInfo.thisVar) jsvUnRef(execInfo.thisVar);
execInfo.thisVar = oldThisVar;
jspeiRemoveScope();
}
// Unref old scopes
for (i=0;i<execInfo.scopeCount;i++)
jsvUnLock(execInfo.scopes[i]);
// restore function scopes
for (i=0;i<oldScopeCount;i++)
execInfo.scopes[i] = oldScopes[i];
execInfo.scopeCount = oldScopeCount;
}
jsvUnLock(functionCode);
jsvUnLock(functionRoot);
}
jsvUnLock(thisVar);
return returnVar;
} else if (isParsing) { // ---------------------------------- function, but not executing - just parse args and be done
jspeParseFunctionCallBrackets();
/* Do not return function, as it will be unlocked! */
return 0;
} else return 0;
}
// Find a variable (or built-in function) based on the current scopes
JsVar *jspGetNamedVariable(const char *tokenName) {
JsVar *a = JSP_SHOULD_EXECUTE ? jspeiFindInScopes(tokenName) : 0;
if (JSP_SHOULD_EXECUTE && !a) {
/* Special case! We haven't found the variable, so check out
* and see if it's one of our builtins... */
if (jswIsBuiltInObject(tokenName)) {
// Check if we have a built-in function for it
// OPT: Could we instead have jswIsBuiltInObjectWithoutConstructor?
JsVar *obj = jswFindBuiltInFunction(0, tokenName);
// If not, make one
if (!obj)
obj = jspNewBuiltin(tokenName);
if (obj) { // not out of memory
a = jsvAddNamedChild(execInfo.root, obj, tokenName);
jsvUnLock(obj);
}
} else {
a = jswFindBuiltInFunction(0, tokenName);
if (!a) {
/* Variable doesn't exist! JavaScript says we should create it
* (we won't add it here. This is done in the assignment operator)*/
a = jsvMakeIntoVariableName(jsvNewFromString(tokenName), 0);
}
}
}
return a;
}
/// Used by jspGetNamedField / jspGetVarNamedField
static NO_INLINE JsVar *jspGetNamedFieldInParents(JsVar *object, const char* name, bool returnName) {
// Now look in prototypes
JsVar * child = jspeiFindChildFromStringInParents(object, name);
/* Check for builtins via separate function
* This way we save on RAM for built-ins because everything comes out of program code */
if (!child) {
child = jswFindBuiltInFunction(object, name);
}
/* We didn't get here if we found a child in the object itself, so
* if we're here then we probably have the wrong name - so for example
* with `a.b = c;` could end up setting `a.prototype.b` (bug #360)
*
* Also we might have got a built-in, which wouldn't have a name on it
* anyway - so in both cases, strip the name if it is there, and create
* a new name.
*/
if (child && returnName) {
// Get rid of existing name
child = jsvSkipNameAndUnLock(child);
// create a new name
JsVar *nameVar = jsvNewFromString(name);
JsVar *newChild = jsvCreateNewChild(object, nameVar, child);
jsvUnLock2(nameVar, child);
child = newChild;
}
// If not found and is the prototype, create it
if (!child) {
if (jsvIsFunction(object) && strcmp(name, JSPARSE_PROTOTYPE_VAR)==0) {
// prototype is supposed to be an object
JsVar *proto = jsvNewObject();
// make sure it has a 'constructor' variable that points to the object it was part of
jsvObjectSetChild(proto, JSPARSE_CONSTRUCTOR_VAR, object);
child = jsvAddNamedChild(object, proto, JSPARSE_PROTOTYPE_VAR);
jspEnsureIsPrototype(object, child);
jsvUnLock(proto);
} else if (strcmp(name, JSPARSE_INHERITS_VAR)==0) {
const char *objName = jswGetBasicObjectName(object);
if (objName) {
child = jspNewPrototype(objName);
}
}
}
return child;
}
/** Get the named function/variable on the object - whether it's built in, or predefined.
* If !returnName, returns the function/variable itself or undefined, but
* if returnName, return a name (could be fake) referencing the parent.
*
* NOTE: ArrayBuffer/Strings are not handled here. We assume that if we're
* passing a char* rather than a JsVar it's because we're looking up via
* a symbol rather than a variable. To handle these use jspGetVarNamedField */
JsVar *jspGetNamedField(JsVar *object, const char* name, bool returnName) {
JsVar *child = 0;
// if we're an object (or pretending to be one)
if (jsvHasChildren(object))
child = jsvFindChildFromString(object, name, false);
if (!child) {
child = jspGetNamedFieldInParents(object, name, returnName);
// If not found and is the prototype, create it
if (!child && jsvIsFunction(object) && strcmp(name, JSPARSE_PROTOTYPE_VAR)==0) {
JsVar *value = jsvNewObject(); // prototype is supposed to be an object
child = jsvAddNamedChild(object, value, JSPARSE_PROTOTYPE_VAR);
jsvUnLock(value);
}
}
if (returnName) return child;
else return jsvSkipNameAndUnLock(child);
}
/// see jspGetNamedField - note that nameVar should have had jsvAsArrayIndex called on it first
JsVar *jspGetVarNamedField(JsVar *object, JsVar *nameVar, bool returnName) {
JsVar *child = 0;
// if we're an object (or pretending to be one)
if (jsvHasChildren(object))
child = jsvFindChildFromVar(object, nameVar, false);
if (!child) {
if (jsvIsArrayBuffer(object) && jsvIsInt(nameVar)) {
// for array buffers, we actually create a NAME, and hand that back - then when we assign (or use SkipName) we pull out the correct data
child = jsvMakeIntoVariableName(jsvNewFromInteger(jsvGetInteger(nameVar)), object);
if (child) // turn into an 'array buffer name'
child->flags = (child->flags & ~JSV_VARTYPEMASK) | JSV_ARRAYBUFFERNAME;
} else if (jsvIsString(object) && jsvIsInt(nameVar)) {
JsVarInt idx = jsvGetInteger(nameVar);
if (idx>=0 && idx<(JsVarInt)jsvGetStringLength(object)) {
char ch = jsvGetCharInString(object, (size_t)idx);
child = jsvNewStringOfLength(1, &ch);
} else if (returnName)
child = jsvCreateNewChild(object, nameVar, 0); // just return *something* to show this is handled
} else {
// get the name as a string
char name[JSLEX_MAX_TOKEN_LENGTH];
jsvGetString(nameVar, name, JSLEX_MAX_TOKEN_LENGTH);
// try and find it in parents
child = jspGetNamedFieldInParents(object, name, returnName);
// If not found and is the prototype, create it
if (!child && jsvIsFunction(object) && jsvIsStringEqual(nameVar, JSPARSE_PROTOTYPE_VAR)) {
JsVar *value = jsvNewObject(); // prototype is supposed to be an object
child = jsvAddNamedChild(object, value, JSPARSE_PROTOTYPE_VAR);
jsvUnLock(value);
}
}
}
if (returnName) return child;
else return jsvSkipNameAndUnLock(child);
}
/// Call the named function on the object - whether it's built in, or predefined. Returns the return value of the function.
JsVar *jspCallNamedFunction(JsVar *object, char* name, int argCount, JsVar **argPtr) {
JsVar *child = jspGetNamedField(object, name, false);
JsVar *r = 0;
if (jsvIsFunction(child))
r = jspeFunctionCall(child, 0, object, false, argCount, argPtr);
jsvUnLock(child);
return r;
}
NO_INLINE JsVar *jspeFactorMember(JsVar *a, JsVar **parentResult) {
/* The parent if we're executing a method call */
JsVar *parent = 0;
while (lex->tk=='.' || lex->tk=='[') {
if (lex->tk == '.') { // ------------------------------------- Record Access
JSP_ASSERT_MATCH('.');
if (jslIsIDOrReservedWord(lex)) {
if (JSP_SHOULD_EXECUTE) {
// Note: name will go away when we parse something else!
const char *name = jslGetTokenValueAsString(lex);
JsVar *aVar = jsvSkipName(a);
JsVar *child = 0;
if (aVar)
child = jspGetNamedField(aVar, name, true);
if (!child) {
if (!jsvIsUndefined(aVar)) {
// if no child found, create a pointer to where it could be
// as we don't want to allocate it until it's written
JsVar *nameVar = jslGetTokenValueAsVar(lex);
child = jsvCreateNewChild(aVar, nameVar, 0);
jsvUnLock(nameVar);
} else {
// could have been a string...
jsExceptionHere(JSET_ERROR, "Cannot read property '%s' of undefined", name);
}
}
jsvUnLock(parent);
parent = aVar;
jsvUnLock(a);
a = child;
}
// skip over current token (we checked above that it was an ID or reserved word)
jslGetNextToken(lex);
} else {
// incorrect token - force a match fail by asking for an ID
JSP_MATCH_WITH_RETURN(LEX_ID, a);
}
} else if (lex->tk == '[') { // ------------------------------------- Array Access
JsVar *index;
JSP_ASSERT_MATCH('[');
if (!jspCheckStackPosition()) return parent;
index = jsvSkipNameAndUnLock(jspeAssignmentExpression());
JSP_MATCH_WITH_CLEANUP_AND_RETURN(']', jsvUnLock2(parent, index);, a);
if (JSP_SHOULD_EXECUTE) {
index = jsvAsArrayIndexAndUnLock(index);
JsVar *aVar = jsvSkipName(a);
JsVar *child = 0;
if (aVar)
child = jspGetVarNamedField(aVar, index, true);
if (!child) {
if (jsvHasChildren(aVar)) {
// if no child found, create a pointer to where it could be
// as we don't want to allocate it until it's written
child = jsvCreateNewChild(aVar, index, 0);
} else {
jsExceptionHere(JSET_ERROR, "Field or method %q does not already exist, and can't create it on %t", index, aVar);
}
}
jsvUnLock(parent);
parent = jsvLockAgainSafe(aVar);
jsvUnLock(a);
a = child;
jsvUnLock(aVar);
}
jsvUnLock(index);
} else {
assert(0);
}
}
if (parentResult) *parentResult = parent;
else jsvUnLock(parent);
return a;
}
NO_INLINE JsVar *jspeConstruct(JsVar *func, JsVar *funcName, bool hasArgs) {
assert(JSP_SHOULD_EXECUTE);
if (!jsvIsFunction(func)) {
jsExceptionHere(JSET_ERROR, "Constructor should be a function, but is %t", func);
return 0;
}
JsVar *thisObj = jsvNewObject();
if (!thisObj) return 0; // out of memory
// Make sure the function has a 'prototype' var
JsVar *prototypeName = jsvFindChildFromString(func, JSPARSE_PROTOTYPE_VAR, true);
jspEnsureIsPrototype(func, prototypeName); // make sure it's an object
JsVar *prototypeVar = jsvSkipName(prototypeName);
jsvUnLock3(jsvAddNamedChild(thisObj, prototypeVar, JSPARSE_INHERITS_VAR), prototypeVar, prototypeName);
JsVar *a = jspeFunctionCall(func, funcName, thisObj, hasArgs, 0, 0);
/* FIXME: we should ignore return values that aren't objects (bug #848), but then we need
* to be aware of `new String()` and `new Uint8Array()`. Ideally we'd let through
* arrays/etc, and then String/etc should return 'boxed' values.
*
* But they don't return boxed values at the moment, so let's just
* pass the return value through. If you try and return a string from
* a function it's broken JS code anyway.
*/
if (a) {
jsvUnLock(thisObj);
thisObj = a;
} else {
jsvUnLock(a);
}
return thisObj;
}
NO_INLINE JsVar *jspeFactorFunctionCall() {
/* The parent if we're executing a method call */
bool isConstructor = false;
if (lex->tk==LEX_R_NEW) {
JSP_ASSERT_MATCH(LEX_R_NEW);
isConstructor = true;
if (lex->tk==LEX_R_NEW) {
jsExceptionHere(JSET_ERROR, "Nesting 'new' operators is unsupported");
jspSetError(false);
return 0;
}
}
JsVar *parent = 0;
#ifndef SAVE_ON_FLASH
bool wasSuper = lex->tk==LEX_R_SUPER;
#endif
JsVar *a = jspeFactorMember(jspeFactor(), &parent);
#ifndef SAVE_ON_FLASH
if (wasSuper) {
/* if this was 'super.something' then we need
* to overwrite the parent, because it'll be
* set to the prototype otherwise.
*/
jsvUnLock(parent);
parent = jsvLockAgainSafe(execInfo.thisVar);
}
#endif
while ((lex->tk=='(' || (isConstructor && JSP_SHOULD_EXECUTE)) && !jspIsInterrupted()) {
JsVar *funcName = a;
JsVar *func = jsvSkipName(funcName);
/* The constructor function doesn't change parsing, so if we're
* not executing, just short-cut it. */
if (isConstructor && JSP_SHOULD_EXECUTE) {
// If we have '(' parse an argument list, otherwise don't look for any args
bool parseArgs = lex->tk=='(';
a = jspeConstruct(func, funcName, parseArgs);
isConstructor = false; // don't treat subsequent brackets as constructors
} else
a = jspeFunctionCall(func, funcName, parent, true, 0, 0);
jsvUnLock3(funcName, func, parent);
parent=0;
a = jspeFactorMember(a, &parent);
}
jsvUnLock(parent);
return a;
}
NO_INLINE JsVar *jspeFactorObject() {
if (JSP_SHOULD_EXECUTE) {
JsVar *contents = jsvNewObject();
if (!contents) { // out of memory
jspSetError(false);
return 0;
}
/* JSON-style object definition */
JSP_MATCH_WITH_RETURN('{', contents);
while (!JSP_SHOULDNT_PARSE && lex->tk != '}') {
JsVar *varName = 0;
// we only allow strings or IDs on the left hand side of an initialisation
if (jslIsIDOrReservedWord(lex)) {
if (JSP_SHOULD_EXECUTE)
varName = jslGetTokenValueAsVar(lex);
jslGetNextToken(lex); // skip over current token
} else if (
lex->tk==LEX_STR ||
lex->tk==LEX_TEMPLATE_LITERAL ||
lex->tk==LEX_FLOAT ||
lex->tk==LEX_INT ||
lex->tk==LEX_R_TRUE ||
lex->tk==LEX_R_FALSE ||
lex->tk==LEX_R_NULL ||
lex->tk==LEX_R_UNDEFINED) {
varName = jspeFactor();
} else {
JSP_MATCH_WITH_RETURN(LEX_ID, contents);
}
JSP_MATCH_WITH_CLEANUP_AND_RETURN(':', jsvUnLock(varName), contents);
if (JSP_SHOULD_EXECUTE) {
varName = jsvAsArrayIndexAndUnLock(varName);
JsVar *contentsName = jsvFindChildFromVar(contents, varName, true);
if (contentsName) {
JsVar *value = jsvSkipNameAndUnLock(jspeAssignmentExpression()); // value can be 0 (could be undefined!)
jsvUnLock2(jsvSetValueOfName(contentsName, value), value);
}
}
jsvUnLock(varName);
// no need to clean here, as it will definitely be used
if (lex->tk != '}') JSP_MATCH_WITH_RETURN(',', contents);
}
JSP_MATCH_WITH_RETURN('}', contents);
return contents;
} else {
// Not executing so do fast skip
jspeBlock();
return 0;
}
}
NO_INLINE JsVar *jspeFactorArray() {
int idx = 0;
JsVar *contents = 0;
if (JSP_SHOULD_EXECUTE) {
contents = jsvNewEmptyArray();
if (!contents) { // out of memory
jspSetError(false);
return 0;
}
}
/* JSON-style array */
JSP_MATCH_WITH_RETURN('[', contents);
while (!JSP_SHOULDNT_PARSE && lex->tk != ']') {
if (JSP_SHOULD_EXECUTE) {
JsVar *aVar = 0;
JsVar *indexName = 0;
if (lex->tk != ',') { // #287 - [,] and [1,2,,4] are allowed
aVar = jsvSkipNameAndUnLock(jspeAssignmentExpression());
indexName = jsvMakeIntoVariableName(jsvNewFromInteger(idx), aVar);
}
if (indexName) { // could be out of memory
jsvAddName(contents, indexName);
jsvUnLock(indexName);
}
jsvUnLock(aVar);
} else {
jsvUnLock(jspeAssignmentExpression());
}
// no need to clean here, as it will definitely be used
if (lex->tk != ']') JSP_MATCH_WITH_RETURN(',', contents);
idx++;
}
if (contents) jsvSetArrayLength(contents, idx, false);
JSP_MATCH_WITH_RETURN(']', contents);
return contents;
}
NO_INLINE void jspEnsureIsPrototype(JsVar *instanceOf, JsVar *prototypeName) {
if (!prototypeName) return;
JsVar *prototypeVar = jsvSkipName(prototypeName);
if (!jsvIsObject(prototypeVar)) {
if (!jsvIsUndefined(prototypeVar))
jsExceptionHere(JSET_TYPEERROR, "Prototype should be an object, got %t", prototypeVar);
jsvUnLock(prototypeVar);
prototypeVar = jsvNewObject(); // prototype is supposed to be an object
JsVar *lastName = jsvSkipToLastName(prototypeName);
jsvSetValueOfName(lastName, prototypeVar);
jsvUnLock(lastName);
}
JsVar *constructor = jsvFindChildFromString(prototypeVar, JSPARSE_CONSTRUCTOR_VAR, true);
if (constructor) jsvSetValueOfName(constructor, instanceOf);
jsvUnLock2(constructor, prototypeVar);
}
NO_INLINE JsVar *jspeFactorTypeOf() {
JSP_ASSERT_MATCH(LEX_R_TYPEOF);
JsVar *a = jspeUnaryExpression();
JsVar *result = 0;
if (JSP_SHOULD_EXECUTE) {
if (!jsvIsVariableDefined(a)) {
// so we don't get a ReferenceError when accessing an undefined var
result=jsvNewFromString("undefined");
} else {
a = jsvSkipNameAndUnLock(a);
result=jsvNewFromString(jsvGetTypeOf(a));
}
}
jsvUnLock(a);
return result;
}
NO_INLINE JsVar *jspeFactorDelete() {
JSP_ASSERT_MATCH(LEX_R_DELETE);
JsVar *parent = 0;
JsVar *a = jspeFactorMember(jspeFactor(), &parent);
JsVar *result = 0;
if (JSP_SHOULD_EXECUTE) {
bool ok = false;
if (jsvIsName(a) && !jsvIsNewChild(a)) {
// if no parent, check in root?
if (!parent && jsvIsChild(execInfo.root, a))
parent = jsvLockAgain(execInfo.root);
if (parent && !jsvIsFunction(parent)) {
// else remove properly.
if (jsvIsArray(parent)) {
// For arrays, we must make sure we don't change the length
JsVarInt l = jsvGetArrayLength(parent);
jsvRemoveChild(parent, a);
jsvSetArrayLength(parent, l, false);
} else {
jsvRemoveChild(parent, a);
}
ok = true;
}
}
result = jsvNewFromBool(ok);
}
jsvUnLock2(a, parent);
return result;
}
#ifndef SAVE_ON_FLASH
JsVar *jspeTemplateLiteral() {
JsVar *a = 0;
if (JSP_SHOULD_EXECUTE) {
JsVar *template = jslGetTokenValueAsVar(lex);
a = jsvNewFromEmptyString();
if (a && template) {
JsvStringIterator it, dit;
jsvStringIteratorNew(&it, template, 0);
jsvStringIteratorNew(&dit, a, 0);
while (jsvStringIteratorHasChar(&it)) {
char ch = jsvStringIteratorGetChar(&it);
if (ch=='$') {
jsvStringIteratorNext(&it);
ch = jsvStringIteratorGetChar(&it);
if (ch=='{') {
// Now parse out the expression
jsvStringIteratorNext(&it);
int brackets = 1;
JsVar *expr = jsvNewFromEmptyString();
if (!expr) break;
JsvStringIterator eit;
jsvStringIteratorNew(&eit, expr, 0);
while (jsvStringIteratorHasChar(&it)) {
ch = jsvStringIteratorGetChar(&it);
jsvStringIteratorNext(&it);
if (ch=='{') brackets++;
if (ch=='}') {
brackets--;
if (!brackets) break;
}
jsvStringIteratorAppend(&eit, ch);
}
jsvStringIteratorFree(&eit);
JsVar *result = jspEvaluateExpressionVar(expr);
jsvUnLock(expr);
result = jsvAsString(result, true);
jsvStringIteratorAppendString(&dit, result, 0);
jsvUnLock(result);
} else {
jsvStringIteratorAppend(&dit, '$');
}
} else {
jsvStringIteratorAppend(&dit, ch);
jsvStringIteratorNext(&it);
}
}
jsvStringIteratorFree(&it);
jsvStringIteratorFree(&dit);
}
jsvUnLock(template);
}
JSP_ASSERT_MATCH(LEX_TEMPLATE_LITERAL);
return a;
}
#endif
NO_INLINE JsVar *jspeAddNamedFunctionParameter(JsVar *funcVar, JsVar *name) {
if (!funcVar) funcVar = jsvNewWithFlags(JSV_FUNCTION);
char buf[JSLEX_MAX_TOKEN_LENGTH+1];
buf[0] = '\xFF';
jsvGetString(name, &buf[1], JSLEX_MAX_TOKEN_LENGTH);
JsVar *param = jsvAddNamedChild(funcVar, 0, buf);
jsvMakeFunctionParameter(param);
jsvUnLock(param);
return funcVar;
}
#ifndef SAVE_ON_FLASH
// parse an arrow function
NO_INLINE JsVar *jspeArrowFunction(JsVar *funcVar, JsVar *a) {
assert(!a || jsvIsName(a));
JSP_ASSERT_MATCH(LEX_ARROW_FUNCTION);
funcVar = jspeAddNamedFunctionParameter(funcVar, a);
bool expressionOnly = lex->tk!='{';
jspeFunctionDefinitionInternal(funcVar, expressionOnly);
if (execInfo.thisVar) {
jsvObjectSetChild(funcVar, JSPARSE_FUNCTION_THIS_NAME, execInfo.thisVar);
}
return funcVar;
}
// parse expressions with commas, maybe followed by an arrow function (bracket already matched)
NO_INLINE JsVar *jspeExpressionOrArrowFunction() {
JsVar *a = 0;
JsVar *funcVar = 0;
bool allNames = true;
while (lex->tk!=')' && !JSP_SHOULDNT_PARSE) {
if (allNames && a) {
// we never get here if this isn't a name and a string
funcVar = jspeAddNamedFunctionParameter(funcVar, a);
}
jsvUnLock(a);
a = jspeAssignmentExpression();
if (!(jsvIsName(a) && jsvIsString(a))) allNames = false;
if (lex->tk!=')') JSP_MATCH_WITH_CLEANUP_AND_RETURN(',', jsvUnLock2(a,funcVar), 0);
}
JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock2(a,funcVar), 0);
// if arrow is found, create a function
if (allNames && lex->tk==LEX_ARROW_FUNCTION) {
funcVar = jspeArrowFunction(funcVar, a);
jsvUnLock(a);
return funcVar;
} else {
jsvUnLock(funcVar);
return a;
}
}
/// Parse an ES6 class, expects LEX_R_CLASS already parsed
NO_INLINE JsVar *jspeClassDefinition(bool parseNamedClass) {
JsVar *classFunction = 0;
JsVar *classPrototype = 0;
JsVar *classInternalName = 0;
bool actuallyCreateClass = JSP_SHOULD_EXECUTE;
if (actuallyCreateClass)
classFunction = jsvNewWithFlags(JSV_FUNCTION);
if (parseNamedClass && lex->tk==LEX_ID) {
if (classFunction)
classInternalName = jslGetTokenValueAsVar(lex);
JSP_ASSERT_MATCH(LEX_ID);
}
if (classFunction) {
JsVar *prototypeName = jsvFindChildFromString(classFunction, JSPARSE_PROTOTYPE_VAR, true);
jspEnsureIsPrototype(classFunction, prototypeName); // make sure it's an object
classPrototype = jsvSkipName(prototypeName);
jsvUnLock(prototypeName);
}
if (lex->tk==LEX_R_EXTENDS) {
JSP_ASSERT_MATCH(LEX_R_EXTENDS);
JsVar *extendsFrom = actuallyCreateClass ? jsvSkipNameAndUnLock(jspGetNamedVariable(jslGetTokenValueAsString(lex))) : 0;
JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID,jsvUnLock4(extendsFrom,classFunction,classInternalName,classPrototype),0);
if (classPrototype) {
if (jsvIsFunction(extendsFrom)) {
jsvObjectSetChild(classPrototype, JSPARSE_INHERITS_VAR, extendsFrom);
// link in default constructor if ours isn't supplied
jsvObjectSetChildAndUnLock(classFunction, JSPARSE_FUNCTION_CODE_NAME, jsvNewFromString("if(this.__proto__.__proto__)this.__proto__.__proto__.apply(this,arguments)"));
} else
jsExceptionHere(JSET_SYNTAXERROR, "'extends' argument should be a function, got %t", extendsFrom);
}
jsvUnLock(extendsFrom);
}
JSP_MATCH_WITH_CLEANUP_AND_RETURN('{',jsvUnLock3(classFunction,classInternalName,classPrototype),0);
while ((lex->tk==LEX_ID || lex->tk==LEX_R_STATIC) && !jspIsInterrupted()) {
bool isStatic = lex->tk==LEX_R_STATIC;
if (isStatic) JSP_ASSERT_MATCH(LEX_R_STATIC);
JsVar *funcName = jslGetTokenValueAsVar(lex);
JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID,jsvUnLock3(classFunction,classInternalName,classPrototype),0);
JsVar *method = jspeFunctionDefinition(false);
if (classFunction && classPrototype) {
if (jsvIsStringEqual(funcName, "get") || jsvIsStringEqual(funcName, "set")) {
jsExceptionHere(JSET_SYNTAXERROR, "'get' and 'set' and not supported in Espruino");
} else if (jsvIsStringEqual(funcName, "constructor")) {
jswrap_function_replaceWith(classFunction, method);
} else {
funcName = jsvMakeIntoVariableName(funcName, 0);
jsvSetValueOfName(funcName, method);
jsvAddName(isStatic ? classFunction : classPrototype, funcName);
}
}
jsvUnLock2(method,funcName);
}
jsvUnLock(classPrototype);
// If we had a name, add it to the end (or it gets confused with the constructor arguments)
if (classInternalName)
jsvObjectSetChildAndUnLock(classFunction, JSPARSE_FUNCTION_NAME_NAME, classInternalName);
JSP_MATCH_WITH_CLEANUP_AND_RETURN('}',jsvUnLock(classFunction),0);
return classFunction;
}
#endif
NO_INLINE JsVar *jspeFactor() {
if (lex->tk==LEX_ID) {
JsVar *a = jspGetNamedVariable(jslGetTokenValueAsString(lex));
JSP_ASSERT_MATCH(LEX_ID);
#ifndef SAVE_ON_FLASH
if (lex->tk==LEX_TEMPLATE_LITERAL)
jsExceptionHere(JSET_SYNTAXERROR, "Tagged template literals not supported");
else if (lex->tk==LEX_ARROW_FUNCTION && jsvIsName(a)) {
JsVar *funcVar = jspeArrowFunction(0,a);
jsvUnLock(a);
a=funcVar;
}
#endif
return a;
} else if (lex->tk==LEX_INT) {
JsVar *v = 0;
if (JSP_SHOULD_EXECUTE) {
v = jsvNewFromLongInteger(stringToInt(jslGetTokenValueAsString(lex)));
}
JSP_ASSERT_MATCH(LEX_INT);
return v;
} else if (lex->tk==LEX_FLOAT) {
JsVar *v = 0;
if (JSP_SHOULD_EXECUTE) {
v = jsvNewFromFloat(stringToFloat(jslGetTokenValueAsString(lex)));
}
JSP_ASSERT_MATCH(LEX_FLOAT);
return v;
} else if (lex->tk=='(') {
JSP_ASSERT_MATCH('(');
if (!jspCheckStackPosition()) return 0;
#ifdef SAVE_ON_FLASH
// Just parse a normal expression (which can include commas)
JsVar *a = jspeExpression();
if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN(')',a);
return a;
#else
return jspeExpressionOrArrowFunction();
#endif
} else if (lex->tk==LEX_R_TRUE) {
JSP_ASSERT_MATCH(LEX_R_TRUE);
return JSP_SHOULD_EXECUTE ? jsvNewFromBool(true) : 0;
} else if (lex->tk==LEX_R_FALSE) {
JSP_ASSERT_MATCH(LEX_R_FALSE);
return JSP_SHOULD_EXECUTE ? jsvNewFromBool(false) : 0;
} else if (lex->tk==LEX_R_NULL) {
JSP_ASSERT_MATCH(LEX_R_NULL);
return JSP_SHOULD_EXECUTE ? jsvNewWithFlags(JSV_NULL) : 0;
} else if (lex->tk==LEX_R_UNDEFINED) {
JSP_ASSERT_MATCH(LEX_R_UNDEFINED);
return 0;
} else if (lex->tk==LEX_STR) {
JsVar *a = 0;
if (JSP_SHOULD_EXECUTE)
a = jslGetTokenValueAsVar(lex);
JSP_ASSERT_MATCH(LEX_STR);
return a;
#ifndef SAVE_ON_FLASH
} else if (lex->tk==LEX_TEMPLATE_LITERAL) {
return jspeTemplateLiteral();
#endif
} else if (lex->tk==LEX_REGEX) {
JsVar *a = 0;
#ifdef SAVE_ON_FLASH
jsExceptionHere(JSET_SYNTAXERROR, "RegEx are not supported in this version of Espruino\n");
#else
JsVar *regex = jslGetTokenValueAsVar(lex);
size_t regexEnd = 0, regexLen = 0;
JsvStringIterator it;
jsvStringIteratorNew(&it, regex, 0);
while (jsvStringIteratorHasChar(&it)) {
regexLen++;
if (jsvStringIteratorGetChar(&it)=='/')
regexEnd = regexLen;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
JsVar *flags = 0;
if (regexEnd < regexLen)
flags = jsvNewFromStringVar(regex, regexEnd, JSVAPPENDSTRINGVAR_MAXLENGTH);
JsVar *regexSource = jsvNewFromStringVar(regex, 1, regexEnd-2);
a = jswrap_regexp_constructor(regexSource, flags);
jsvUnLock3(regex, flags, regexSource);
#endif
JSP_ASSERT_MATCH(LEX_REGEX);
return a;
} else if (lex->tk=='{') {
if (!jspCheckStackPosition()) return 0;
return jspeFactorObject();
} else if (lex->tk=='[') {
if (!jspCheckStackPosition()) return 0;
return jspeFactorArray();
} else if (lex->tk==LEX_R_FUNCTION) {
if (!jspCheckStackPosition()) return 0;
JSP_ASSERT_MATCH(LEX_R_FUNCTION);
return jspeFunctionDefinition(true);
#ifndef SAVE_ON_FLASH
} else if (lex->tk==LEX_R_CLASS) {
if (!jspCheckStackPosition()) return 0;
JSP_ASSERT_MATCH(LEX_R_CLASS);
return jspeClassDefinition(true);
} else if (lex->tk==LEX_R_SUPER) {
JSP_ASSERT_MATCH(LEX_R_SUPER);
/* This is kind of nasty, since super appears to do
three different things.
* In the constructor it references the extended class's constructor
* in a method it references the constructor's prototype.
* in a static method it references the extended class's constructor (but this is different)
*/
if (jsvIsObject(execInfo.thisVar)) {
// 'this' is an object - must be calling a normal method
JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_INHERITS_VAR, 0); // if we're in a method, get __proto__ first
JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; // still in method, get __proto__.__proto__
jsvUnLock(proto1);
if (!proto2) {
jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class");
return 0;
}
if (lex->tk=='(') return proto2; // eg. used in a constructor
// But if we're doing something else - eg '.' or '[' then it needs to reference the prototype
JsVar *proto3 = jsvIsFunction(proto2) ? jsvObjectGetChild(proto2, JSPARSE_PROTOTYPE_VAR, 0) : 0;
jsvUnLock(proto2);
return proto3;
} else if (jsvIsFunction(execInfo.thisVar)) {
// 'this' is a function - must be calling a static method
JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_PROTOTYPE_VAR, 0);
JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0;
jsvUnLock(proto1);
if (!proto2) {
jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class");
return 0;
}
return proto2;
}
jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class");
return 0;
#endif
} else if (lex->tk==LEX_R_THIS) {
JSP_ASSERT_MATCH(LEX_R_THIS);
return jsvLockAgain( execInfo.thisVar ? execInfo.thisVar : execInfo.root );
} else if (lex->tk==LEX_R_DELETE) {
if (!jspCheckStackPosition()) return 0;
return jspeFactorDelete();
} else if (lex->tk==LEX_R_TYPEOF) {
if (!jspCheckStackPosition()) return 0;
return jspeFactorTypeOf();
} else if (lex->tk==LEX_R_VOID) {
if (!jspCheckStackPosition()) return 0;
JSP_ASSERT_MATCH(LEX_R_VOID);
jsvUnLock(jspeUnaryExpression());
return 0;
}
JSP_MATCH(LEX_EOF);
jsExceptionHere(JSET_SYNTAXERROR, "Unexpected end of Input\n");
return 0;
}
NO_INLINE JsVar *__jspePostfixExpression(JsVar *a) {
while (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) {
int op = lex->tk;
JSP_ASSERT_MATCH(op);
if (JSP_SHOULD_EXECUTE) {
JsVar *one = jsvNewFromInteger(1);
JsVar *oldValue = jsvAsNumberAndUnLock(jsvSkipName(a)); // keep the old value (but convert to number)
JsVar *res = jsvMathsOpSkipNames(oldValue, one, op==LEX_PLUSPLUS ? '+' : '-');
jsvUnLock(one);
// in-place add/subtract
jspReplaceWith(a, res);
jsvUnLock(res);
// but then use the old value
jsvUnLock(a);
a = oldValue;
}
}
return a;
}
NO_INLINE JsVar *jspePostfixExpression() {
JsVar *a;
// TODO: should be in jspeUnaryExpression
if (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) {
int op = lex->tk;
JSP_ASSERT_MATCH(op);
a = jspePostfixExpression();
if (JSP_SHOULD_EXECUTE) {
JsVar *one = jsvNewFromInteger(1);
JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-');
jsvUnLock(one);
// in-place add/subtract
jspReplaceWith(a, res);
jsvUnLock(res);
}
} else
a = jspeFactorFunctionCall();
return __jspePostfixExpression(a);
}
NO_INLINE JsVar *jspeUnaryExpression() {
if (lex->tk=='!' || lex->tk=='~' || lex->tk=='-' || lex->tk=='+') {
short tk = lex->tk;
JSP_ASSERT_MATCH(tk);
if (!JSP_SHOULD_EXECUTE) {
return jspeUnaryExpression();
}
if (tk=='!') { // logical not
return jsvNewFromBool(!jsvGetBoolAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression())));
} else if (tk=='~') { // bitwise not
return jsvNewFromInteger(~jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression())));
} else if (tk=='-') { // unary minus
return jsvNegateAndUnLock(jspeUnaryExpression()); // names already skipped
} else if (tk=='+') { // unary plus (convert to number)
JsVar *v = jsvSkipNameAndUnLock(jspeUnaryExpression());
JsVar *r = jsvAsNumber(v); // names already skipped
jsvUnLock(v);
return r;
}
assert(0);
return 0;
} else
return jspePostfixExpression();
}
// Get the precedence of a BinaryExpression - or return 0 if not one
unsigned int jspeGetBinaryExpressionPrecedence(int op) {
switch (op) {
case LEX_OROR: return 1; break;
case LEX_ANDAND: return 2; break;
case '|' : return 3; break;
case '^' : return 4; break;
case '&' : return 5; break;
case LEX_EQUAL:
case LEX_NEQUAL:
case LEX_TYPEEQUAL:
case LEX_NTYPEEQUAL: return 6;
case LEX_LEQUAL:
case LEX_GEQUAL:
case '<':
case '>':
case LEX_R_INSTANCEOF: return 7;
case LEX_R_IN: return (execInfo.execute&EXEC_FOR_INIT)?0:7;
case LEX_LSHIFT:
case LEX_RSHIFT:
case LEX_RSHIFTUNSIGNED: return 8;
case '+':
case '-': return 9;
case '*':
case '/':
case '%': return 10;
default: return 0;
}
}
NO_INLINE JsVar *__jspeBinaryExpression(JsVar *a, unsigned int lastPrecedence) {
/* This one's a bit strange. Basically all the ops have their own precedence, it's not
* like & and | share the same precedence. We don't want to recurse for each one,
* so instead we do this.
*
* We deal with an expression in recursion ONLY if it's of higher precedence
* than the current one, otherwise we stick in the while loop.
*/
unsigned int precedence = jspeGetBinaryExpressionPrecedence(lex->tk);
while (precedence && precedence>lastPrecedence) {
int op = lex->tk;
JSP_ASSERT_MATCH(op);
// if we have short-circuit ops, then if we know the outcome
// we don't bother to execute the other op. Even if not
// we need to tell mathsOp it's an & or |
if (op==LEX_ANDAND || op==LEX_OROR) {
bool aValue = jsvGetBoolAndUnLock(jsvSkipName(a));
if ((!aValue && op==LEX_ANDAND) ||
(aValue && op==LEX_OROR)) {
// use first argument (A)
JSP_SAVE_EXECUTE();
jspSetNoExecute();
jsvUnLock(__jspeBinaryExpression(jspeUnaryExpression(),precedence));
JSP_RESTORE_EXECUTE();
} else {
// use second argument (B)
jsvUnLock(a);
a = __jspeBinaryExpression(jspeUnaryExpression(),precedence);
}
} else { // else it's a more 'normal' logical expression - just use Maths
JsVar *b = __jspeBinaryExpression(jspeUnaryExpression(),precedence);
if (JSP_SHOULD_EXECUTE) {
if (op==LEX_R_IN) {
JsVar *av = jsvSkipName(a); // needle
JsVar *bv = jsvSkipName(b); // haystack
if (jsvIsArray(bv) || jsvIsObject(bv)) { // search keys, NOT values
av = jsvAsArrayIndexAndUnLock(av);
JsVar *varFound = jspGetVarNamedField( bv, av, true);
jsvUnLock(a);
a = jsvNewFromBool(varFound!=0);
jsvUnLock(varFound);
} else {// else it will be undefined
jsExceptionHere(JSET_ERROR, "Cannot use 'in' operator to search a %t", bv);
jsvUnLock(a);
a = 0;
}
jsvUnLock2(av, bv);
} else if (op==LEX_R_INSTANCEOF) {
bool inst = false;
JsVar *av = jsvSkipName(a);
JsVar *bv = jsvSkipName(b);
if (!jsvIsFunction(bv)) {
jsExceptionHere(JSET_ERROR, "Expecting a function on RHS in instanceof check, got %t", bv);
} else {
if (jsvIsObject(av) || jsvIsFunction(av)) {
JsVar *bproto = jspGetNamedField(bv, JSPARSE_PROTOTYPE_VAR, false);
JsVar *proto = jsvObjectGetChild(av, JSPARSE_INHERITS_VAR, 0);
while (proto) {
if (proto == bproto) inst=true;
// search prototype chain
JsVar *childProto = jsvObjectGetChild(proto, JSPARSE_INHERITS_VAR, 0);
jsvUnLock(proto);
proto = childProto;
}
if (jspIsConstructor(bv, "Object")) inst = true;
jsvUnLock(bproto);
}
if (!inst) {
const char *name = jswGetBasicObjectName(av);
if (name) {
inst = jspIsConstructor(bv, name);
}
// Hack for built-ins that should also be instances of Object
if (!inst && (jsvIsArray(av) || jsvIsArrayBuffer(av)) &&
jspIsConstructor(bv, "Object"))
inst = true;
}
}
jsvUnLock3(av, bv, a);
a = jsvNewFromBool(inst);
} else { // --------------------------------------------- NORMAL
JsVar *res = jsvMathsOpSkipNames(a, b, op);
jsvUnLock(a); a = res;
}
}
jsvUnLock(b);
}
precedence = jspeGetBinaryExpressionPrecedence(lex->tk);
}
return a;
}
JsVar *jspeBinaryExpression() {
return __jspeBinaryExpression(jspeUnaryExpression(),0);
}
NO_INLINE JsVar *__jspeConditionalExpression(JsVar *lhs) {
if (lex->tk=='?') {
JSP_ASSERT_MATCH('?');
if (!JSP_SHOULD_EXECUTE) {
// just let lhs pass through
jsvUnLock(jspeAssignmentExpression());
JSP_MATCH(':');
jsvUnLock(jspeAssignmentExpression());
} else {
bool first = jsvGetBoolAndUnLock(jsvSkipName(lhs));
jsvUnLock(lhs);
if (first) {
lhs = jspeAssignmentExpression();
JSP_MATCH(':');
JSP_SAVE_EXECUTE();
jspSetNoExecute();
jsvUnLock(jspeAssignmentExpression());
JSP_RESTORE_EXECUTE();
} else {
JSP_SAVE_EXECUTE();
jspSetNoExecute();
jsvUnLock(jspeAssignmentExpression());
JSP_RESTORE_EXECUTE();
JSP_MATCH(':');
lhs = jspeAssignmentExpression();
}
}
}
return lhs;
}
JsVar *jspeConditionalExpression() {
return __jspeConditionalExpression(jspeBinaryExpression());
}
NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) {
if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL ||
lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL ||
lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL ||
lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL ||
lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) {
JsVar *rhs;
int op = lex->tk;
JSP_ASSERT_MATCH(op);
rhs = jspeAssignmentExpression();
rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS
if (JSP_SHOULD_EXECUTE && lhs) {
if (op=='=') {
jspReplaceWithOrAddToRoot(lhs, rhs);
} else {
if (op==LEX_PLUSEQUAL) op='+';
else if (op==LEX_MINUSEQUAL) op='-';
else if (op==LEX_MULEQUAL) op='*';
else if (op==LEX_DIVEQUAL) op='/';
else if (op==LEX_MODEQUAL) op='%';
else if (op==LEX_ANDEQUAL) op='&';
else if (op==LEX_OREQUAL) op='|';
else if (op==LEX_XOREQUAL) op='^';
else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT;
else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT;
else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED;
if (op=='+' && jsvIsName(lhs)) {
JsVar *currentValue = jsvSkipName(lhs);
if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) {
/* A special case for string += where this is the only use of the string
* and we're not appending to ourselves. In this case we can do a
* simple append (rather than clone + append)*/
JsVar *str = jsvAsString(rhs, false);
jsvAppendStringVarComplete(currentValue, str);
jsvUnLock(str);
op = 0;
}
jsvUnLock(currentValue);
}
if (op) {
/* Fallback which does a proper add */
JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op);
jspReplaceWith(lhs, res);
jsvUnLock(res);
}
}
}
jsvUnLock(rhs);
}
return lhs;
}
JsVar *jspeAssignmentExpression() {
return __jspeAssignmentExpression(jspeConditionalExpression());
}
// ',' is allowed to add multiple expressions, this is not allowed in jspeAssignmentExpression
NO_INLINE JsVar *jspeExpression() {
while (!JSP_SHOULDNT_PARSE) {
JsVar *a = jspeAssignmentExpression();
if (lex->tk!=',') return a;
// if we get a comma, we just forget this data and parse the next bit...
jsvCheckReferenceError(a);
jsvUnLock(a);
JSP_ASSERT_MATCH(',');
}
return 0;
}
/** Parse a block `{ ... }` but assume brackets are already parsed */
NO_INLINE void jspeBlockNoBrackets() {
if (JSP_SHOULD_EXECUTE) {
while (lex->tk && lex->tk!='}') {
JsVar *a = jspeStatement();
jsvCheckReferenceError(a);
jsvUnLock(a);
if (JSP_HAS_ERROR) {
if (lex && !(execInfo.execute&EXEC_ERROR_LINE_REPORTED)) {
execInfo.execute = (JsExecFlags)(execInfo.execute | EXEC_ERROR_LINE_REPORTED);
JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0);
if (stackTrace) {
jsvAppendPrintf(stackTrace, "at ");
jspAppendStackTrace(stackTrace);
jsvUnLock(stackTrace);
}
}
}
if (JSP_SHOULDNT_PARSE)
return;
}
} else {
// fast skip of blocks
int brackets = 0;
while (lex->tk && (brackets || lex->tk != '}')) {
if (lex->tk == '{') brackets++;
if (lex->tk == '}') brackets--;
JSP_ASSERT_MATCH(lex->tk);
}
}
return;
}
/** Parse a block `{ ... }` */
NO_INLINE void jspeBlock() {
JSP_MATCH_WITH_RETURN('{',);
jspeBlockNoBrackets();
if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN('}',);
return;
}
NO_INLINE JsVar *jspeBlockOrStatement() {
if (lex->tk=='{') {
jspeBlock();
return 0;
} else {
JsVar *v = jspeStatement();
if (lex->tk==';') JSP_ASSERT_MATCH(';');
return v;
}
}
/** Parse using current lexer until we hit the end of
* input or there was some problem. */
NO_INLINE JsVar *jspParse() {
JsVar *v = 0;
while (!JSP_SHOULDNT_PARSE && lex->tk != LEX_EOF) {
jsvUnLock(v);
v = jspeBlockOrStatement();
}
return v;
}
NO_INLINE JsVar *jspeStatementVar() {
JsVar *lastDefined = 0;
/* variable creation. TODO - we need a better way of parsing the left
* hand side. Maybe just have a flag called can_create_var that we
* set and then we parse as if we're doing a normal equals.*/
assert(lex->tk==LEX_R_VAR || lex->tk==LEX_R_LET || lex->tk==LEX_R_CONST);
jslGetNextToken();
///TODO: Correctly implement CONST and LET - we just treat them like 'var' at the moment
bool hasComma = true; // for first time in loop
while (hasComma && lex->tk == LEX_ID && !jspIsInterrupted()) {
JsVar *a = 0;
if (JSP_SHOULD_EXECUTE) {
a = jspeiFindOnTop(jslGetTokenValueAsString(lex), true);
if (!a) { // out of memory
jspSetError(false);
return lastDefined;
}
}
JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(a), lastDefined);
// sort out initialiser
if (lex->tk == '=') {
JsVar *var;
JSP_MATCH_WITH_CLEANUP_AND_RETURN('=', jsvUnLock(a), lastDefined);
var = jsvSkipNameAndUnLock(jspeAssignmentExpression());
if (JSP_SHOULD_EXECUTE)
jspReplaceWith(a, var);
jsvUnLock(var);
}
jsvUnLock(lastDefined);
lastDefined = a;
hasComma = lex->tk == ',';
if (hasComma) JSP_MATCH_WITH_RETURN(',', lastDefined);
}
return lastDefined;
}
NO_INLINE JsVar *jspeStatementIf() {
bool cond;
JsVar *var, *result = 0;
JSP_ASSERT_MATCH(LEX_R_IF);
JSP_MATCH('(');
var = jspeExpression();
if (JSP_SHOULDNT_PARSE) return var;
JSP_MATCH(')');
cond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(var));
jsvUnLock(var);
JSP_SAVE_EXECUTE();
if (!cond) jspSetNoExecute();
JsVar *a = jspeBlockOrStatement();
if (!cond) {
jsvUnLock(a);
JSP_RESTORE_EXECUTE();
} else {
result = a;
}
if (lex->tk==LEX_R_ELSE) {
JSP_ASSERT_MATCH(LEX_R_ELSE);
JSP_SAVE_EXECUTE();
if (cond) jspSetNoExecute();
JsVar *a = jspeBlockOrStatement();
if (cond) {
jsvUnLock(a);
JSP_RESTORE_EXECUTE();
} else {
result = a;
}
}
return result;
}
NO_INLINE JsVar *jspeStatementSwitch() {
JSP_ASSERT_MATCH(LEX_R_SWITCH);
JSP_MATCH('(');
JsVar *switchOn = jspeExpression();
JSP_SAVE_EXECUTE();
bool execute = JSP_SHOULD_EXECUTE;
JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock(switchOn), 0);
// shortcut if not executing...
if (!execute) { jsvUnLock(switchOn); jspeBlock(); return 0; }
JSP_MATCH_WITH_CLEANUP_AND_RETURN('{', jsvUnLock(switchOn), 0);
bool executeDefault = true;
if (execute) execInfo.execute=EXEC_NO|EXEC_IN_SWITCH;
while (lex->tk==LEX_R_CASE) {
JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_R_CASE, jsvUnLock(switchOn), 0);
JsExecFlags oldFlags = execInfo.execute;
if (execute) execInfo.execute=EXEC_YES|EXEC_IN_SWITCH;
JsVar *test = jspeAssignmentExpression();
execInfo.execute = oldFlags|EXEC_IN_SWITCH;;
JSP_MATCH_WITH_CLEANUP_AND_RETURN(':', jsvUnLock2(switchOn, test), 0);
bool cond = false;
if (execute)
cond = jsvGetBoolAndUnLock(jsvMathsOpSkipNames(switchOn, test, LEX_TYPEEQUAL));
if (cond) executeDefault = false;
jsvUnLock(test);
if (cond && (execInfo.execute&EXEC_RUN_MASK)==EXEC_NO)
execInfo.execute=EXEC_YES|EXEC_IN_SWITCH;
while (!JSP_SHOULDNT_PARSE && lex->tk!=LEX_EOF && lex->tk!=LEX_R_CASE && lex->tk!=LEX_R_DEFAULT && lex->tk!='}')
jsvUnLock(jspeBlockOrStatement());
oldExecute |= execInfo.execute & (EXEC_ERROR_MASK|EXEC_RETURN); // copy across any errors/exceptions/returns
}
jsvUnLock(switchOn);
if (execute && (execInfo.execute&EXEC_RUN_MASK)==EXEC_BREAK) {
execInfo.execute=EXEC_YES|EXEC_IN_SWITCH;
} else {
executeDefault = true;
}
JSP_RESTORE_EXECUTE();
if (lex->tk==LEX_R_DEFAULT) {
JSP_ASSERT_MATCH(LEX_R_DEFAULT);
JSP_MATCH(':');
JSP_SAVE_EXECUTE();
if (!executeDefault) jspSetNoExecute();
else execInfo.execute |= EXEC_IN_SWITCH;
while (!JSP_SHOULDNT_PARSE && lex->tk!=LEX_EOF && lex->tk!='}')
jsvUnLock(jspeBlockOrStatement());
oldExecute |= execInfo.execute & (EXEC_ERROR_MASK|EXEC_RETURN); // copy across any errors/exceptions/returns
execInfo.execute = execInfo.execute & (JsExecFlags)~EXEC_BREAK;
JSP_RESTORE_EXECUTE();
}
JSP_MATCH('}');
return 0;
}
NO_INLINE JsVar *jspeStatementDoOrWhile(bool isWhile) {
#ifdef JSPARSE_MAX_LOOP_ITERATIONS
int loopCount = JSPARSE_MAX_LOOP_ITERATIONS;
#endif
JsVar *cond;
bool loopCond = true; // true for do...while loops
bool hasHadBreak = false;
JslCharPos whileCondStart;
// We do repetition by pulling out the string representing our statement
// there's definitely some opportunity for optimisation here
JSP_ASSERT_MATCH(isWhile ? LEX_R_WHILE : LEX_R_DO);
bool wasInLoop = (execInfo.execute&EXEC_IN_LOOP)!=0;
if (isWhile) { // while loop
JSP_MATCH('(');
whileCondStart = jslCharPosClone(&lex->tokenStart);
cond = jspeAssignmentExpression();
loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond));
jsvUnLock(cond);
JSP_MATCH_WITH_CLEANUP_AND_RETURN(')',jslCharPosFree(&whileCondStart);,0);
}
JslCharPos whileBodyStart = jslCharPosClone(&lex->tokenStart);
JSP_SAVE_EXECUTE();
// actually try and execute first bit of while loop (we'll do the rest in the actual loop later)
if (!loopCond) jspSetNoExecute();
execInfo.execute |= EXEC_IN_LOOP;
jsvUnLock(jspeBlockOrStatement());
if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
if (execInfo.execute & EXEC_CONTINUE)
execInfo.execute = (execInfo.execute & ~EXEC_RUN_MASK) | EXEC_YES;
else if (execInfo.execute & EXEC_BREAK) {
execInfo.execute = (execInfo.execute & ~EXEC_RUN_MASK) | EXEC_YES;
hasHadBreak = true; // fail loop condition, so we exit
}
if (!loopCond) JSP_RESTORE_EXECUTE();
if (!isWhile) { // do..while loop
JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_R_WHILE,jslCharPosFree(&whileBodyStart);,0);
JSP_MATCH_WITH_CLEANUP_AND_RETURN('(',jslCharPosFree(&whileBodyStart);if (isWhile)jslCharPosFree(&whileCondStart);,0);
whileCondStart = jslCharPosClone(&lex->tokenStart);
cond = jspeAssignmentExpression();
loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond));
jsvUnLock(cond);
JSP_MATCH_WITH_CLEANUP_AND_RETURN(')',jslCharPosFree(&whileBodyStart);jslCharPosFree(&whileCondStart);,0);
}
JslCharPos whileBodyEnd;
whileBodyEnd = jslCharPosClone(&lex->tokenStart);
while (!hasHadBreak && loopCond
#ifdef JSPARSE_MAX_LOOP_ITERATIONS
&& loopCount-->0
#endif
) {
jslSeekToP(&whileCondStart);
cond = jspeAssignmentExpression();
loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond));
jsvUnLock(cond);
if (loopCond) {
jslSeekToP(&whileBodyStart);
execInfo.execute |= EXEC_IN_LOOP;
jspDebuggerLoopIfCtrlC();
jsvUnLock(jspeBlockOrStatement());
if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
if (execInfo.execute & EXEC_CONTINUE)
execInfo.execute = (execInfo.execute & ~EXEC_RUN_MASK) | EXEC_YES;
else if (execInfo.execute & EXEC_BREAK) {
execInfo.execute = (execInfo.execute & ~EXEC_RUN_MASK) | EXEC_YES;
hasHadBreak = true;
}
}
}
jslSeekToP(&whileBodyEnd);
jslCharPosFree(&whileCondStart);
jslCharPosFree(&whileBodyStart);
jslCharPosFree(&whileBodyEnd);
#ifdef JSPARSE_MAX_LOOP_ITERATIONS
if (loopCount<=0) {
jsExceptionHere(JSET_ERROR, "WHILE Loop exceeded the maximum number of iterations (" STRINGIFY(JSPARSE_MAX_LOOP_ITERATIONS) ")");
}
#endif
return 0;
}
NO_INLINE JsVar *jspeStatementFor() {
JSP_ASSERT_MATCH(LEX_R_FOR);
JSP_MATCH('(');
bool wasInLoop = (execInfo.execute&EXEC_IN_LOOP)!=0;
execInfo.execute |= EXEC_FOR_INIT;
// initialisation
JsVar *forStatement = 0;
// we could have 'for (;;)' - so don't munch up our semicolon if that's all we have
if (lex->tk != ';')
forStatement = jspeStatement();
if (jspIsInterrupted()) {
jsvUnLock(forStatement);
return 0;
}
execInfo.execute &= (JsExecFlags)~EXEC_FOR_INIT;
if (lex->tk == LEX_R_IN) {
// for (i in array)
// where i = jsvUnLock(forStatement);
if (JSP_SHOULD_EXECUTE && !jsvIsName(forStatement)) {
jsvUnLock(forStatement);
jsExceptionHere(JSET_ERROR, "FOR a IN b - 'a' must be a variable name, not %t", forStatement);
return 0;
}
JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_R_IN, jsvUnLock(forStatement), 0);
JsVar *array = jsvSkipNameAndUnLock(jspeExpression());
JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock2(forStatement, array), 0);
JslCharPos forBodyStart = jslCharPosClone(&lex->tokenStart);
JSP_SAVE_EXECUTE();
jspSetNoExecute();
execInfo.execute |= EXEC_IN_LOOP;
jsvUnLock(jspeBlockOrStatement());
JslCharPos forBodyEnd = jslCharPosClone(&lex->tokenStart);
if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
JSP_RESTORE_EXECUTE();
if (JSP_SHOULD_EXECUTE) {
if (jsvIsIterable(array)) {
JsvIsInternalChecker checkerFunction = jsvGetInternalFunctionCheckerFor(array);
JsVar *foundPrototype = 0;
JsvIterator it;
jsvIteratorNew(&it, array, JSIF_DEFINED_ARRAY_ElEMENTS);
bool hasHadBreak = false;
while (JSP_SHOULD_EXECUTE && jsvIteratorHasElement(&it) && !hasHadBreak) {
JsVar *loopIndexVar = jsvIteratorGetKey(&it);
bool ignore = false;
if (checkerFunction && checkerFunction(loopIndexVar)) {
ignore = true;
if (jsvIsString(loopIndexVar) &&
jsvIsStringEqual(loopIndexVar, JSPARSE_INHERITS_VAR))
foundPrototype = jsvSkipName(loopIndexVar);
}
if (!ignore) {
JsVar *indexValue = jsvIsName(loopIndexVar) ?
jsvCopyNameOnly(loopIndexVar, false/*no copy children*/, false/*not a name*/) :
loopIndexVar;
if (indexValue) { // could be out of memory
assert(!jsvIsName(indexValue) && jsvGetRefs(indexValue)==0);
jspReplaceWithOrAddToRoot(forStatement, indexValue);
if (indexValue!=loopIndexVar) jsvUnLock(indexValue);
jsvIteratorNext(&it);
jslSeekToP(&forBodyStart);
execInfo.execute |= EXEC_IN_LOOP;
jspDebuggerLoopIfCtrlC();
jsvUnLock(jspeBlockOrStatement());
if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
if (execInfo.execute & EXEC_CONTINUE)
execInfo.execute = EXEC_YES;
else if (execInfo.execute & EXEC_BREAK) {
execInfo.execute = EXEC_YES;
hasHadBreak = true;
}
}
} else
jsvIteratorNext(&it);
jsvUnLock(loopIndexVar);
if (!jsvIteratorHasElement(&it) && foundPrototype) {
jsvIteratorFree(&it);
jsvIteratorNew(&it, foundPrototype, JSIF_DEFINED_ARRAY_ElEMENTS);
jsvUnLock(foundPrototype);
foundPrototype = 0;
}
}
assert(!foundPrototype);
jsvIteratorFree(&it);
} else if (!jsvIsUndefined(array)) {
jsExceptionHere(JSET_ERROR, "FOR loop can only iterate over Arrays, Strings or Objects, not %t", array);
}
}
jslSeekToP(&forBodyEnd);
jslCharPosFree(&forBodyStart);
jslCharPosFree(&forBodyEnd);
jsvUnLock2(forStatement, array);
} else { // ----------------------------------------------- NORMAL FOR LOOP
#ifdef JSPARSE_MAX_LOOP_ITERATIONS
int loopCount = JSPARSE_MAX_LOOP_ITERATIONS;
#endif
bool loopCond = true;
bool hasHadBreak = false;
jsvUnLock(forStatement);
JSP_MATCH(';');
JslCharPos forCondStart = jslCharPosClone(&lex->tokenStart);
if (lex->tk != ';') {
JsVar *cond = jspeAssignmentExpression(); // condition
loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond));
jsvUnLock(cond);
}
JSP_MATCH_WITH_CLEANUP_AND_RETURN(';',jslCharPosFree(&forCondStart);,0);
JslCharPos forIterStart = jslCharPosClone(&lex->tokenStart);
if (lex->tk != ')') { // we could have 'for (;;)'
JSP_SAVE_EXECUTE();
jspSetNoExecute();
jsvUnLock(jspeExpression()); // iterator
JSP_RESTORE_EXECUTE();
}
JSP_MATCH_WITH_CLEANUP_AND_RETURN(')',jslCharPosFree(&forCondStart);jslCharPosFree(&forIterStart);,0);
JslCharPos forBodyStart = jslCharPosClone(&lex->tokenStart); // actual for body
JSP_SAVE_EXECUTE();
if (!loopCond) jspSetNoExecute();
execInfo.execute |= EXEC_IN_LOOP;
jsvUnLock(jspeBlockOrStatement());
JslCharPos forBodyEnd = jslCharPosClone(&lex->tokenStart);
if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
if (loopCond || !JSP_SHOULD_EXECUTE) {
if (execInfo.execute & EXEC_CONTINUE)
execInfo.execute = EXEC_YES;
else if (execInfo.execute & EXEC_BREAK) {
execInfo.execute = EXEC_YES;
hasHadBreak = true;
}
}
if (!loopCond) JSP_RESTORE_EXECUTE();
if (loopCond) {
jslSeekToP(&forIterStart);
if (lex->tk != ')') jsvUnLock(jspeExpression());
}
while (!hasHadBreak && JSP_SHOULD_EXECUTE && loopCond
#ifdef JSPARSE_MAX_LOOP_ITERATIONS
&& loopCount-->0
#endif
) {
jslSeekToP(&forCondStart);
;
if (lex->tk == ';') {
loopCond = true;
} else {
JsVar *cond = jspeAssignmentExpression();
loopCond = jsvGetBoolAndUnLock(jsvSkipName(cond));
jsvUnLock(cond);
}
if (JSP_SHOULD_EXECUTE && loopCond) {
jslSeekToP(&forBodyStart);
execInfo.execute |= EXEC_IN_LOOP;
jspDebuggerLoopIfCtrlC();
jsvUnLock(jspeBlockOrStatement());
if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
if (execInfo.execute & EXEC_CONTINUE)
execInfo.execute = EXEC_YES;
else if (execInfo.execute & EXEC_BREAK) {
execInfo.execute = EXEC_YES;
hasHadBreak = true;
}
}
if (JSP_SHOULD_EXECUTE && loopCond && !hasHadBreak) {
jslSeekToP(&forIterStart);
if (lex->tk != ')') jsvUnLock(jspeExpression());
}
}
jslSeekToP(&forBodyEnd);
jslCharPosFree(&forCondStart);
jslCharPosFree(&forIterStart);
jslCharPosFree(&forBodyStart);
jslCharPosFree(&forBodyEnd);
#ifdef JSPARSE_MAX_LOOP_ITERATIONS
if (loopCount<=0) {
jsExceptionHere(JSET_ERROR, "FOR Loop exceeded the maximum number of iterations ("STRINGIFY(JSPARSE_MAX_LOOP_ITERATIONS)")");
}
#endif
}
return 0;
}
NO_INLINE JsVar *jspeStatementTry() {
// execute the try block
JSP_ASSERT_MATCH(LEX_R_TRY);
bool shouldExecuteBefore = JSP_SHOULD_EXECUTE;
jspeBlock();
bool hadException = shouldExecuteBefore && ((execInfo.execute & EXEC_EXCEPTION)!=0);
bool hadCatch = false;
if (lex->tk == LEX_R_CATCH) {
JSP_ASSERT_MATCH(LEX_R_CATCH);
hadCatch = true;
JSP_MATCH('(');
JsVar *scope = 0;
JsVar *exceptionVar = 0;
if (hadException) {
scope = jsvNewObject();
if (scope)
exceptionVar = jsvFindChildFromString(scope, jslGetTokenValueAsString(lex), true);
}
JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID,jsvUnLock2(scope,exceptionVar),0);
JSP_MATCH_WITH_CLEANUP_AND_RETURN(')',jsvUnLock2(scope,exceptionVar),0);
if (exceptionVar) {
// set the exception var up properly
JsVar *exception = jspGetException();
if (exception) {
jsvSetValueOfName(exceptionVar, exception);
jsvUnLock(exception);
}
// Now clear the exception flag (it's handled - we hope!)
execInfo.execute = execInfo.execute & (JsExecFlags)~(EXEC_EXCEPTION|EXEC_ERROR_LINE_REPORTED);
jsvUnLock(exceptionVar);
}
if (shouldExecuteBefore && !hadException) {
JSP_SAVE_EXECUTE();
jspSetNoExecute();
jspeBlock();
JSP_RESTORE_EXECUTE();
} else {
if (!scope || jspeiAddScope(scope)) {
jspeBlock();
if (scope) jspeiRemoveScope();
}
}
jsvUnLock(scope);
}
if (lex->tk == LEX_R_FINALLY || (!hadCatch && ((execInfo.execute&(EXEC_ERROR|EXEC_INTERRUPTED))==0))) {
JSP_MATCH(LEX_R_FINALLY);
// clear the exception flag - but only momentarily!
if (hadException) execInfo.execute = execInfo.execute & (JsExecFlags)~EXEC_EXCEPTION;
jspeBlock();
// put the flag back!
if (hadException && !hadCatch) execInfo.execute = execInfo.execute | EXEC_EXCEPTION;
}
return 0;
}
NO_INLINE JsVar *jspeStatementReturn() {
JsVar *result = 0;
JSP_ASSERT_MATCH(LEX_R_RETURN);
if (lex->tk != ';' && lex->tk != '}') {
// we only want the value, so skip the name if there was one
result = jsvSkipNameAndUnLock(jspeExpression());
}
if (JSP_SHOULD_EXECUTE) {
JsVar *resultVar = jspeiFindInScopes(JSPARSE_RETURN_VAR);
if (resultVar) {
jspReplaceWith(resultVar, result);
jsvUnLock(resultVar);
execInfo.execute |= EXEC_RETURN; // Stop anything else in this function executing
} else {
jsExceptionHere(JSET_SYNTAXERROR, "RETURN statement, but not in a function.\n");
}
}
jsvUnLock(result);
return 0;
}
NO_INLINE JsVar *jspeStatementThrow() {
JsVar *result = 0;
JSP_ASSERT_MATCH(LEX_R_THROW);
result = jsvSkipNameAndUnLock(jspeExpression());
if (JSP_SHOULD_EXECUTE) {
jspSetException(result); // Stop anything else in this function executing
}
jsvUnLock(result);
return 0;
}
NO_INLINE JsVar *jspeStatementFunctionDecl(bool isClass) {
JsVar *funcName = 0;
JsVar *funcVar;
#ifndef SAVE_ON_FLASH
JSP_ASSERT_MATCH(isClass ? LEX_R_CLASS : LEX_R_FUNCTION);
#else
JSP_ASSERT_MATCH(LEX_R_FUNCTION);
#endif
bool actuallyCreateFunction = JSP_SHOULD_EXECUTE;
if (actuallyCreateFunction) {
funcName = jsvMakeIntoVariableName(jslGetTokenValueAsVar(lex), 0);
if (!funcName) { // out of memory
return 0;
}
}
JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(funcName), 0);
#ifndef SAVE_ON_FLASH
funcVar = isClass ? jspeClassDefinition(false) : jspeFunctionDefinition(false);
#else
funcVar = jspeFunctionDefinition(false);
#endif
if (actuallyCreateFunction) {
// find a function with the same name (or make one)
// OPT: can Find* use just a JsVar that is a 'name'?
JsVar *existingName = jspeiFindNameOnTop(funcName, true);
JsVar *existingFunc = jsvSkipName(existingName);
if (jsvIsFunction(existingFunc)) {
// 'proper' replace, that keeps the original function var and swaps the children
funcVar = jsvSkipNameAndUnLock(funcVar);
jswrap_function_replaceWith(existingFunc, funcVar);
} else {
jspReplaceWith(existingName, funcVar);
}
jsvUnLock(funcName);
funcName = existingName;
jsvUnLock(existingFunc);
// existingName is used - don't UnLock
}
jsvUnLock(funcVar);
return funcName;
}
NO_INLINE JsVar *jspeStatement() {
#ifdef USE_DEBUGGER
if (execInfo.execute&EXEC_DEBUGGER_NEXT_LINE &&
lex->tk!=';' &&
JSP_SHOULD_EXECUTE) {
lex->tokenLastStart = jsvStringIteratorGetIndex(&lex->tokenStart.it)-1;
jsiDebuggerLoop();
}
#endif
if (lex->tk==LEX_ID ||
lex->tk==LEX_INT ||
lex->tk==LEX_FLOAT ||
lex->tk==LEX_STR ||
lex->tk==LEX_TEMPLATE_LITERAL ||
lex->tk==LEX_REGEX ||
lex->tk==LEX_R_NEW ||
lex->tk==LEX_R_NULL ||
lex->tk==LEX_R_UNDEFINED ||
lex->tk==LEX_R_TRUE ||
lex->tk==LEX_R_FALSE ||
lex->tk==LEX_R_THIS ||
lex->tk==LEX_R_DELETE ||
lex->tk==LEX_R_TYPEOF ||
lex->tk==LEX_R_VOID ||
lex->tk==LEX_R_SUPER ||
lex->tk==LEX_PLUSPLUS ||
lex->tk==LEX_MINUSMINUS ||
lex->tk=='!' ||
lex->tk=='-' ||
lex->tk=='+' ||
lex->tk=='~' ||
lex->tk=='[' ||
lex->tk=='(') {
/* Execute a simple statement that only contains basic arithmetic... */
return jspeExpression();
} else if (lex->tk=='{') {
/* A block of code */
jspeBlock();
return 0;
} else if (lex->tk==';') {
/* Empty statement - to allow things like ;;; */
JSP_ASSERT_MATCH(';');
return 0;
} else if (lex->tk==LEX_R_VAR ||
lex->tk==LEX_R_LET ||
lex->tk==LEX_R_CONST) {
return jspeStatementVar();
} else if (lex->tk==LEX_R_IF) {
return jspeStatementIf();
} else if (lex->tk==LEX_R_DO) {
return jspeStatementDoOrWhile(false);
} else if (lex->tk==LEX_R_WHILE) {
return jspeStatementDoOrWhile(true);
} else if (lex->tk==LEX_R_FOR) {
return jspeStatementFor();
} else if (lex->tk==LEX_R_TRY) {
return jspeStatementTry();
} else if (lex->tk==LEX_R_RETURN) {
return jspeStatementReturn();
} else if (lex->tk==LEX_R_THROW) {
return jspeStatementThrow();
} else if (lex->tk==LEX_R_FUNCTION) {
return jspeStatementFunctionDecl(false/* function */);
#ifndef SAVE_ON_FLASH
} else if (lex->tk==LEX_R_CLASS) {
return jspeStatementFunctionDecl(true/* class */);
#endif
} else if (lex->tk==LEX_R_CONTINUE) {
JSP_ASSERT_MATCH(LEX_R_CONTINUE);
if (JSP_SHOULD_EXECUTE) {
if (!(execInfo.execute & EXEC_IN_LOOP))
jsExceptionHere(JSET_SYNTAXERROR, "CONTINUE statement outside of FOR or WHILE loop");
else
execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_RUN_MASK) | EXEC_CONTINUE;
}
} else if (lex->tk==LEX_R_BREAK) {
JSP_ASSERT_MATCH(LEX_R_BREAK);
if (JSP_SHOULD_EXECUTE) {
if (!(execInfo.execute & (EXEC_IN_LOOP|EXEC_IN_SWITCH)))
jsExceptionHere(JSET_SYNTAXERROR, "BREAK statement outside of SWITCH, FOR or WHILE loop");
else
execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_RUN_MASK) | EXEC_BREAK;
}
} else if (lex->tk==LEX_R_SWITCH) {
return jspeStatementSwitch();
} else if (lex->tk==LEX_R_DEBUGGER) {
JSP_ASSERT_MATCH(LEX_R_DEBUGGER);
#ifdef USE_DEBUGGER
if (JSP_SHOULD_EXECUTE)
jsiDebuggerLoop();
#endif
} else JSP_MATCH(LEX_EOF);
return 0;
}
// -----------------------------------------------------------------------------
/// Create a new built-in object that jswrapper can use to check for built-in functions
JsVar *jspNewBuiltin(const char *instanceOf) {
JsVar *objFunc = jswFindBuiltInFunction(0, instanceOf);
if (!objFunc) return 0; // out of memory
return objFunc;
}
/// Create a new Class of the given instance and return its prototype
NO_INLINE JsVar *jspNewPrototype(const char *instanceOf) {
JsVar *objFuncName = jsvFindChildFromString(execInfo.root, instanceOf, true);
if (!objFuncName) // out of memory
return 0;
JsVar *objFunc = jsvSkipName(objFuncName);
if (!objFunc) {
objFunc = jspNewBuiltin(instanceOf);
if (!objFunc) { // out of memory
jsvUnLock(objFuncName);
return 0;
}
// set up name
jsvSetValueOfName(objFuncName, objFunc);
}
JsVar *prototypeName = jsvFindChildFromString(objFunc, JSPARSE_PROTOTYPE_VAR, true);
jspEnsureIsPrototype(objFunc, prototypeName); // make sure it's an object
jsvUnLock2(objFunc, objFuncName);
return prototypeName;
}
/** Create a new object of the given instance and add it to root with name 'name'.
* If name!=0, added to root with name, and the name is returned
* If name==0, not added to root and Object itself returned */
NO_INLINE JsVar *jspNewObject(const char *name, const char *instanceOf) {
JsVar *prototypeName = jspNewPrototype(instanceOf);
JsVar *obj = jsvNewObject();
if (!obj) { // out of memory
jsvUnLock(prototypeName);
return 0;
}
if (name) {
// If it's a device, set the device number up as the Object data
// See jsiGetDeviceFromClass
IOEventFlags device = jshFromDeviceString(name);
if (device!=EV_NONE) {
obj->varData.str[0] = 'D';
obj->varData.str[1] = 'E';
obj->varData.str[2] = 'V';
obj->varData.str[3] = (char)device;
}
}
// add __proto__
JsVar *prototypeVar = jsvSkipName(prototypeName);
jsvUnLock3(jsvAddNamedChild(obj, prototypeVar, JSPARSE_INHERITS_VAR), prototypeVar, prototypeName);prototypeName=0;
if (name) {
JsVar *objName = jsvFindChildFromString(execInfo.root, name, true);
if (objName) jsvSetValueOfName(objName, obj);
jsvUnLock(obj);
if (!objName) { // out of memory
return 0;
}
return objName;
} else
return obj;
}
/** Returns true if the constructor function given is the same as that
* of the object with the given name. */
bool jspIsConstructor(JsVar *constructor, const char *constructorName) {
JsVar *objFunc = jsvObjectGetChild(execInfo.root, constructorName, 0);
if (!objFunc) return false;
bool isConstructor = objFunc == constructor;
jsvUnLock(objFunc);
return isConstructor;
}
/** Get the constructor of the given object, or return 0 if ot found, or not a function */
JsVar *jspGetConstructor(JsVar *object) {
if (!jsvIsObject(object)) return 0;
JsVar *proto = jsvObjectGetChild(object, JSPARSE_INHERITS_VAR, 0);
if (jsvIsObject(proto)) {
JsVar *constr = jsvObjectGetChild(proto, JSPARSE_CONSTRUCTOR_VAR, 0);
if (jsvIsFunction(constr)) {
jsvUnLock(proto);
return constr;
}
jsvUnLock(constr);
}
jsvUnLock(proto);
return 0;
}
// -----------------------------------------------------------------------------
void jspSoftInit() {
execInfo.root = jsvFindOrCreateRoot();
// Root now has a lock and a ref
execInfo.hiddenRoot = jsvObjectGetChild(execInfo.root, JS_HIDDEN_CHAR_STR, JSV_OBJECT);
execInfo.execute = EXEC_YES;
}
void jspSoftKill() {
jsvUnLock(execInfo.hiddenRoot);
execInfo.hiddenRoot = 0;
jsvUnLock(execInfo.root);
execInfo.root = 0;
// Root is now left with just a ref
}
void jspInit() {
jspSoftInit();
}
void jspKill() {
jspSoftKill();
// Unreffing this should completely kill everything attached to root
JsVar *r = jsvFindOrCreateRoot();
jsvUnRef(r);
jsvUnLock(r);
}
/** Evaluate the given variable as an expression (in current scope) */
JsVar *jspEvaluateExpressionVar(JsVar *str) {
JsLex lex;
assert(jsvIsString(str));
JsLex *oldLex = jslSetLex(&lex);
jslInit(str);
lex.lineNumberOffset = oldLex->lineNumberOffset;
// actually do the parsing
JsVar *v = jspeExpression();
jslKill();
jslSetLex(oldLex);
return jsvSkipNameAndUnLock(v);
}
/** Execute code form a variable and return the result. If lineNumberOffset
* is nonzero it's added to the line numbers that get reported for errors/debug */
JsVar *jspEvaluateVar(JsVar *str, JsVar *scope, uint16_t lineNumberOffset) {
JsLex lex;
assert(jsvIsString(str));
JsLex *oldLex = jslSetLex(&lex);
jslInit(str);
lex.lineNumberOffset = lineNumberOffset;
JsExecInfo oldExecInfo = execInfo;
execInfo.execute = EXEC_YES;
bool scopeAdded = false;
if (scope) {
// if we're adding a scope, make sure it's the *only* scope
execInfo.scopeCount = 0;
scopeAdded = jspeiAddScope(scope);
}
// actually do the parsing
JsVar *v = jspParse();
// clean up
if (scopeAdded)
jspeiRemoveScope();
jslKill();
jslSetLex(oldLex);
// restore state and execInfo
JsExecFlags mask = EXEC_FOR_INIT|EXEC_IN_LOOP|EXEC_IN_SWITCH;
oldExecInfo.execute = (oldExecInfo.execute & mask) | (execInfo.execute & ~mask);
execInfo = oldExecInfo;
// It may have returned a reference, but we just want the value...
return jsvSkipNameAndUnLock(v);
}
JsVar *jspEvaluate(const char *str, bool stringIsStatic) {
/* using a memory area is more efficient, but the interpreter
* may use substrings from it for function code. This means that
* if the string goes away, everything gets corrupted - hence
* the option here.
*/
JsVar *evCode;
if (stringIsStatic)
evCode = jsvNewNativeString((char*)str, strlen(str));
else
evCode = jsvNewFromString(str);
if (!evCode) return 0;
JsVar *v = 0;
if (!jsvIsMemoryFull())
v = jspEvaluateVar(evCode, 0, 0);
jsvUnLock(evCode);
return v;
}
JsVar *jspExecuteFunction(JsVar *func, JsVar *thisArg, int argCount, JsVar **argPtr) {
JsExecInfo oldExecInfo = execInfo;
execInfo.scopeCount = 0;
execInfo.execute = EXEC_YES;
execInfo.thisVar = 0;
JsVar *result = jspeFunctionCall(func, 0, thisArg, false, argCount, argPtr);
// clean up
assert(execInfo.scopeCount==0);
// restore state
oldExecInfo.execute = execInfo.execute; // JSP_RESTORE_EXECUTE has made this ok.
execInfo = oldExecInfo;
return result;
}
/// Evaluate a JavaScript module and return its exports
JsVar *jspEvaluateModule(JsVar *moduleContents) {
assert(jsvIsString(moduleContents) || jsvIsFunction(moduleContents));
if (jsvIsFunction(moduleContents)) {
moduleContents = jsvObjectGetChild(moduleContents,JSPARSE_FUNCTION_CODE_NAME,0);
if (!jsvIsString(moduleContents)) {
jsvUnLock(moduleContents);
return 0;
}
} else
jsvLockAgain(moduleContents);
JsVar *scope = jsvNewObject();
JsVar *scopeExports = jsvNewObject();
if (!scope || !scopeExports) { // out of mem
jsvUnLock3(scope, scopeExports, moduleContents);
return 0;
}
JsVar *exportsName = jsvAddNamedChild(scope, scopeExports, "exports");
jsvUnLock2(scopeExports, jsvAddNamedChild(scope, scope, "module"));
JsExecFlags oldExecute = execInfo.execute;
JsVar *oldThisVar = execInfo.thisVar;
execInfo.thisVar = scopeExports; // set 'this' variable to exports
jsvUnLock(jspEvaluateVar(moduleContents, scope, 0));
execInfo.thisVar = oldThisVar;
execInfo.execute = oldExecute; // make sure we fully restore state after parsing a module
jsvUnLock2(moduleContents, scope);
return jsvSkipNameAndUnLock(exportsName);
}
/** Get the owner of the current prototype. We assume that it's
* the first item in the array, because that's what we will
* have added when we created it. It's safe to call this on
* non-prototypes and non-objects. */
JsVar *jspGetPrototypeOwner(JsVar *proto) {
if (jsvIsObject(proto) || jsvIsArray(proto)) {
return jsvSkipNameAndUnLock(jsvObjectGetChild(proto, JSPARSE_CONSTRUCTOR_VAR, 0));
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_163_1 |
crossvul-cpp_data_bad_4938_0 | /*
* Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/objects.h>
#include <openssl/bn.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/ts.h>
#include "ts_lcl.h"
int TS_ASN1_INTEGER_print_bio(BIO *bio, const ASN1_INTEGER *num)
{
BIGNUM *num_bn;
int result = 0;
char *hex;
num_bn = BN_new();
if (num_bn == NULL)
return -1;
ASN1_INTEGER_to_BN(num, num_bn);
if ((hex = BN_bn2hex(num_bn))) {
result = BIO_write(bio, "0x", 2) > 0;
result = result && BIO_write(bio, hex, strlen(hex)) > 0;
OPENSSL_free(hex);
}
BN_free(num_bn);
return result;
}
int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj)
{
char obj_txt[128];
int len = OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0);
BIO_write(bio, obj_txt, len);
BIO_write(bio, "\n", 1);
return 1;
}
int TS_ext_print_bio(BIO *bio, const STACK_OF(X509_EXTENSION) *extensions)
{
int i, critical, n;
X509_EXTENSION *ex;
ASN1_OBJECT *obj;
BIO_printf(bio, "Extensions:\n");
n = X509v3_get_ext_count(extensions);
for (i = 0; i < n; i++) {
ex = X509v3_get_ext(extensions, i);
obj = X509_EXTENSION_get_object(ex);
i2a_ASN1_OBJECT(bio, obj);
critical = X509_EXTENSION_get_critical(ex);
BIO_printf(bio, ": %s\n", critical ? "critical" : "");
if (!X509V3_EXT_print(bio, ex, 0, 4)) {
BIO_printf(bio, "%4s", "");
ASN1_STRING_print(bio, X509_EXTENSION_get_data(ex));
}
BIO_write(bio, "\n", 1);
}
return 1;
}
int TS_X509_ALGOR_print_bio(BIO *bio, const X509_ALGOR *alg)
{
int i = OBJ_obj2nid(alg->algorithm);
return BIO_printf(bio, "Hash Algorithm: %s\n",
(i == NID_undef) ? "UNKNOWN" : OBJ_nid2ln(i));
}
int TS_MSG_IMPRINT_print_bio(BIO *bio, TS_MSG_IMPRINT *a)
{
ASN1_OCTET_STRING *msg;
TS_X509_ALGOR_print_bio(bio, a->hash_algo);
BIO_printf(bio, "Message data:\n");
msg = a->hashed_msg;
BIO_dump_indent(bio, (const char *)ASN1_STRING_data(msg),
ASN1_STRING_length(msg), 4);
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4938_0 |
crossvul-cpp_data_bad_2890_0 | /* radare - LGPL - Copyright 2008-2017 - nibble, pancake, alvaro_fe */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <r_types.h>
#include <r_util.h>
#include "elf.h"
#ifdef IFDBG
#undef IFDBG
#endif
#define DO_THE_DBG 0
#define IFDBG if (DO_THE_DBG)
#define IFINT if (0)
#define ELF_PAGE_MASK 0xFFFFFFFFFFFFF000LL
#define ELF_PAGE_SIZE 12
#define R_ELF_NO_RELRO 0
#define R_ELF_PART_RELRO 1
#define R_ELF_FULL_RELRO 2
#define bprintf if(bin->verbose)eprintf
#define READ8(x, i) r_read_ble8(x + i); i += 1;
#define READ16(x, i) r_read_ble16(x + i, bin->endian); i += 2;
#define READ32(x, i) r_read_ble32(x + i, bin->endian); i += 4;
#define READ64(x, i) r_read_ble64(x + i, bin->endian); i += 8;
#define GROWTH_FACTOR (1.5)
static inline int __strnlen(const char *str, int len) {
int l = 0;
while (IS_PRINTABLE (*str) && --len) {
if (((ut8)*str) == 0xff) {
break;
}
str++;
l++;
}
return l + 1;
}
static int handle_e_ident(ELFOBJ *bin) {
return !strncmp ((char *)bin->ehdr.e_ident, ELFMAG, SELFMAG) ||
!strncmp ((char *)bin->ehdr.e_ident, CGCMAG, SCGCMAG);
}
static int init_ehdr(ELFOBJ *bin) {
ut8 e_ident[EI_NIDENT];
ut8 ehdr[sizeof (Elf_(Ehdr))] = {0};
int i, len;
if (r_buf_read_at (bin->b, 0, e_ident, EI_NIDENT) == -1) {
bprintf ("Warning: read (magic)\n");
return false;
}
sdb_set (bin->kv, "elf_type.cparse", "enum elf_type { ET_NONE=0, ET_REL=1,"
" ET_EXEC=2, ET_DYN=3, ET_CORE=4, ET_LOOS=0xfe00, ET_HIOS=0xfeff,"
" ET_LOPROC=0xff00, ET_HIPROC=0xffff };", 0);
sdb_set (bin->kv, "elf_machine.cparse", "enum elf_machine{EM_NONE=0, EM_M32=1,"
" EM_SPARC=2, EM_386=3, EM_68K=4, EM_88K=5, EM_486=6, "
" EM_860=7, EM_MIPS=8, EM_S370=9, EM_MIPS_RS3_LE=10, EM_RS6000=11,"
" EM_UNKNOWN12=12, EM_UNKNOWN13=13, EM_UNKNOWN14=14, "
" EM_PA_RISC=15, EM_PARISC=EM_PA_RISC, EM_nCUBE=16, EM_VPP500=17,"
" EM_SPARC32PLUS=18, EM_960=19, EM_PPC=20, EM_PPC64=21, "
" EM_S390=22, EM_UNKNOWN22=EM_S390, EM_UNKNOWN23=23, EM_UNKNOWN24=24,"
" EM_UNKNOWN25=25, EM_UNKNOWN26=26, EM_UNKNOWN27=27, EM_UNKNOWN28=28,"
" EM_UNKNOWN29=29, EM_UNKNOWN30=30, EM_UNKNOWN31=31, EM_UNKNOWN32=32,"
" EM_UNKNOWN33=33, EM_UNKNOWN34=34, EM_UNKNOWN35=35, EM_V800=36,"
" EM_FR20=37, EM_RH32=38, EM_RCE=39, EM_ARM=40, EM_ALPHA=41, EM_SH=42,"
" EM_SPARCV9=43, EM_TRICORE=44, EM_ARC=45, EM_H8_300=46, EM_H8_300H=47,"
" EM_H8S=48, EM_H8_500=49, EM_IA_64=50, EM_MIPS_X=51, EM_COLDFIRE=52,"
" EM_68HC12=53, EM_MMA=54, EM_PCP=55, EM_NCPU=56, EM_NDR1=57,"
" EM_STARCORE=58, EM_ME16=59, EM_ST100=60, EM_TINYJ=61, EM_AMD64=62,"
" EM_X86_64=EM_AMD64, EM_PDSP=63, EM_UNKNOWN64=64, EM_UNKNOWN65=65,"
" EM_FX66=66, EM_ST9PLUS=67, EM_ST7=68, EM_68HC16=69, EM_68HC11=70,"
" EM_68HC08=71, EM_68HC05=72, EM_SVX=73, EM_ST19=74, EM_VAX=75, "
" EM_CRIS=76, EM_JAVELIN=77, EM_FIREPATH=78, EM_ZSP=79, EM_MMIX=80,"
" EM_HUANY=81, EM_PRISM=82, EM_AVR=83, EM_FR30=84, EM_D10V=85, EM_D30V=86,"
" EM_V850=87, EM_M32R=88, EM_MN10300=89, EM_MN10200=90, EM_PJ=91,"
" EM_OPENRISC=92, EM_ARC_A5=93, EM_XTENSA=94, EM_NUM=95};", 0);
sdb_num_set (bin->kv, "elf_header.offset", 0, 0);
sdb_num_set (bin->kv, "elf_header.size", sizeof (Elf_(Ehdr)), 0);
#if R_BIN_ELF64
sdb_set (bin->kv, "elf_header.format", "[16]z[2]E[2]Exqqqxwwwwww"
" ident (elf_type)type (elf_machine)machine version entry phoff shoff flags ehsize"
" phentsize phnum shentsize shnum shstrndx", 0);
#else
sdb_set (bin->kv, "elf_header.format", "[16]z[2]E[2]Exxxxxwwwwww"
" ident (elf_type)type (elf_machine)machine version entry phoff shoff flags ehsize"
" phentsize phnum shentsize shnum shstrndx", 0);
#endif
bin->endian = (e_ident[EI_DATA] == ELFDATA2MSB)? 1: 0;
memset (&bin->ehdr, 0, sizeof (Elf_(Ehdr)));
len = r_buf_read_at (bin->b, 0, ehdr, sizeof (Elf_(Ehdr)));
if (len < 1) {
bprintf ("Warning: read (ehdr)\n");
return false;
}
memcpy (&bin->ehdr.e_ident, ehdr, 16);
i = 16;
bin->ehdr.e_type = READ16 (ehdr, i)
bin->ehdr.e_machine = READ16 (ehdr, i)
bin->ehdr.e_version = READ32 (ehdr, i)
#if R_BIN_ELF64
bin->ehdr.e_entry = READ64 (ehdr, i)
bin->ehdr.e_phoff = READ64 (ehdr, i)
bin->ehdr.e_shoff = READ64 (ehdr, i)
#else
bin->ehdr.e_entry = READ32 (ehdr, i)
bin->ehdr.e_phoff = READ32 (ehdr, i)
bin->ehdr.e_shoff = READ32 (ehdr, i)
#endif
bin->ehdr.e_flags = READ32 (ehdr, i)
bin->ehdr.e_ehsize = READ16 (ehdr, i)
bin->ehdr.e_phentsize = READ16 (ehdr, i)
bin->ehdr.e_phnum = READ16 (ehdr, i)
bin->ehdr.e_shentsize = READ16 (ehdr, i)
bin->ehdr.e_shnum = READ16 (ehdr, i)
bin->ehdr.e_shstrndx = READ16 (ehdr, i)
return handle_e_ident (bin);
// Usage example:
// > td `k bin/cur/info/elf_type.cparse`; td `k bin/cur/info/elf_machine.cparse`
// > pf `k bin/cur/info/elf_header.format` @ `k bin/cur/info/elf_header.offset`
}
static int init_phdr(ELFOBJ *bin) {
ut32 phdr_size;
ut8 phdr[sizeof (Elf_(Phdr))] = {0};
int i, j, len;
if (!bin->ehdr.e_phnum) {
return false;
}
if (bin->phdr) {
return true;
}
if (!UT32_MUL (&phdr_size, (ut32)bin->ehdr.e_phnum, sizeof (Elf_(Phdr)))) {
return false;
}
if (!phdr_size) {
return false;
}
if (phdr_size > bin->size) {
return false;
}
if (phdr_size > (ut32)bin->size) {
return false;
}
if (bin->ehdr.e_phoff > bin->size) {
return false;
}
if (bin->ehdr.e_phoff + phdr_size > bin->size) {
return false;
}
if (!(bin->phdr = calloc (phdr_size, 1))) {
perror ("malloc (phdr)");
return false;
}
for (i = 0; i < bin->ehdr.e_phnum; i++) {
j = 0;
len = r_buf_read_at (bin->b, bin->ehdr.e_phoff + i * sizeof (Elf_(Phdr)), phdr, sizeof (Elf_(Phdr)));
if (len < 1) {
bprintf ("Warning: read (phdr)\n");
R_FREE (bin->phdr);
return false;
}
bin->phdr[i].p_type = READ32 (phdr, j)
#if R_BIN_ELF64
bin->phdr[i].p_flags = READ32 (phdr, j)
bin->phdr[i].p_offset = READ64 (phdr, j)
bin->phdr[i].p_vaddr = READ64 (phdr, j)
bin->phdr[i].p_paddr = READ64 (phdr, j)
bin->phdr[i].p_filesz = READ64 (phdr, j)
bin->phdr[i].p_memsz = READ64 (phdr, j)
bin->phdr[i].p_align = READ64 (phdr, j)
#else
bin->phdr[i].p_offset = READ32 (phdr, j)
bin->phdr[i].p_vaddr = READ32 (phdr, j)
bin->phdr[i].p_paddr = READ32 (phdr, j)
bin->phdr[i].p_filesz = READ32 (phdr, j)
bin->phdr[i].p_memsz = READ32 (phdr, j)
bin->phdr[i].p_flags = READ32 (phdr, j)
bin->phdr[i].p_align = READ32 (phdr, j)
#endif
}
sdb_num_set (bin->kv, "elf_phdr.offset", bin->ehdr.e_phoff, 0);
sdb_num_set (bin->kv, "elf_phdr.size", sizeof (Elf_(Phdr)), 0);
sdb_set (bin->kv, "elf_p_type.cparse", "enum elf_p_type {PT_NULL=0,PT_LOAD=1,PT_DYNAMIC=2,"
"PT_INTERP=3,PT_NOTE=4,PT_SHLIB=5,PT_PHDR=6,PT_LOOS=0x60000000,"
"PT_HIOS=0x6fffffff,PT_LOPROC=0x70000000,PT_HIPROC=0x7fffffff};", 0);
sdb_set (bin->kv, "elf_p_flags.cparse", "enum elf_p_flags {PF_None=0,PF_Exec=1,"
"PF_Write=2,PF_Write_Exec=3,PF_Read=4,PF_Read_Exec=5,PF_Read_Write=6,"
"PF_Read_Write_Exec=7};", 0);
#if R_BIN_ELF64
sdb_set (bin->kv, "elf_phdr.format", "[4]E[4]Eqqqqqq (elf_p_type)type (elf_p_flags)flags"
" offset vaddr paddr filesz memsz align", 0);
#else
sdb_set (bin->kv, "elf_phdr.format", "[4]Exxxxx[4]Ex (elf_p_type)type offset vaddr paddr"
" filesz memsz (elf_p_flags)flags align", 0);
#endif
return true;
// Usage example:
// > td `k bin/cur/info/elf_p_type.cparse`; td `k bin/cur/info/elf_p_flags.cparse`
// > pf `k bin/cur/info/elf_phdr.format` @ `k bin/cur/info/elf_phdr.offset`
}
static int init_shdr(ELFOBJ *bin) {
ut32 shdr_size;
ut8 shdr[sizeof (Elf_(Shdr))] = {0};
int i, j, len;
if (!bin || bin->shdr) {
return true;
}
if (!UT32_MUL (&shdr_size, bin->ehdr.e_shnum, sizeof (Elf_(Shdr)))) {
return false;
}
if (shdr_size < 1) {
return false;
}
if (shdr_size > bin->size) {
return false;
}
if (bin->ehdr.e_shoff > bin->size) {
return false;
}
if (bin->ehdr.e_shoff + shdr_size > bin->size) {
return false;
}
if (!(bin->shdr = calloc (1, shdr_size + 1))) {
perror ("malloc (shdr)");
return false;
}
sdb_num_set (bin->kv, "elf_shdr.offset", bin->ehdr.e_shoff, 0);
sdb_num_set (bin->kv, "elf_shdr.size", sizeof (Elf_(Shdr)), 0);
sdb_set (bin->kv, "elf_s_type.cparse", "enum elf_s_type {SHT_NULL=0,SHT_PROGBITS=1,"
"SHT_SYMTAB=2,SHT_STRTAB=3,SHT_RELA=4,SHT_HASH=5,SHT_DYNAMIC=6,SHT_NOTE=7,"
"SHT_NOBITS=8,SHT_REL=9,SHT_SHLIB=10,SHT_DYNSYM=11,SHT_LOOS=0x60000000,"
"SHT_HIOS=0x6fffffff,SHT_LOPROC=0x70000000,SHT_HIPROC=0x7fffffff};", 0);
for (i = 0; i < bin->ehdr.e_shnum; i++) {
j = 0;
len = r_buf_read_at (bin->b, bin->ehdr.e_shoff + i * sizeof (Elf_(Shdr)), shdr, sizeof (Elf_(Shdr)));
if (len < 1) {
bprintf ("Warning: read (shdr) at 0x%"PFMT64x"\n", (ut64) bin->ehdr.e_shoff);
R_FREE (bin->shdr);
return false;
}
bin->shdr[i].sh_name = READ32 (shdr, j)
bin->shdr[i].sh_type = READ32 (shdr, j)
#if R_BIN_ELF64
bin->shdr[i].sh_flags = READ64 (shdr, j)
bin->shdr[i].sh_addr = READ64 (shdr, j)
bin->shdr[i].sh_offset = READ64 (shdr, j)
bin->shdr[i].sh_size = READ64 (shdr, j)
bin->shdr[i].sh_link = READ32 (shdr, j)
bin->shdr[i].sh_info = READ32 (shdr, j)
bin->shdr[i].sh_addralign = READ64 (shdr, j)
bin->shdr[i].sh_entsize = READ64 (shdr, j)
#else
bin->shdr[i].sh_flags = READ32 (shdr, j)
bin->shdr[i].sh_addr = READ32 (shdr, j)
bin->shdr[i].sh_offset = READ32 (shdr, j)
bin->shdr[i].sh_size = READ32 (shdr, j)
bin->shdr[i].sh_link = READ32 (shdr, j)
bin->shdr[i].sh_info = READ32 (shdr, j)
bin->shdr[i].sh_addralign = READ32 (shdr, j)
bin->shdr[i].sh_entsize = READ32 (shdr, j)
#endif
}
#if R_BIN_ELF64
sdb_set (bin->kv, "elf_s_flags_64.cparse", "enum elf_s_flags_64 {SF64_None=0,SF64_Exec=1,"
"SF64_Alloc=2,SF64_Alloc_Exec=3,SF64_Write=4,SF64_Write_Exec=5,"
"SF64_Write_Alloc=6,SF64_Write_Alloc_Exec=7};", 0);
sdb_set (bin->kv, "elf_shdr.format", "x[4]E[8]Eqqqxxqq name (elf_s_type)type"
" (elf_s_flags_64)flags addr offset size link info addralign entsize", 0);
#else
sdb_set (bin->kv, "elf_s_flags_32.cparse", "enum elf_s_flags_32 {SF32_None=0,SF32_Exec=1,"
"SF32_Alloc=2,SF32_Alloc_Exec=3,SF32_Write=4,SF32_Write_Exec=5,"
"SF32_Write_Alloc=6,SF32_Write_Alloc_Exec=7};", 0);
sdb_set (bin->kv, "elf_shdr.format", "x[4]E[4]Exxxxxxx name (elf_s_type)type"
" (elf_s_flags_32)flags addr offset size link info addralign entsize", 0);
#endif
return true;
// Usage example:
// > td `k bin/cur/info/elf_s_type.cparse`; td `k bin/cur/info/elf_s_flags_64.cparse`
// > pf `k bin/cur/info/elf_shdr.format` @ `k bin/cur/info/elf_shdr.offset`
}
static int init_strtab(ELFOBJ *bin) {
if (bin->strtab || !bin->shdr) {
return false;
}
if (bin->ehdr.e_shstrndx != SHN_UNDEF &&
(bin->ehdr.e_shstrndx >= bin->ehdr.e_shnum ||
(bin->ehdr.e_shstrndx >= SHN_LORESERVE &&
bin->ehdr.e_shstrndx < SHN_HIRESERVE)))
return false;
/* sh_size must be lower than UT32_MAX and not equal to zero, to avoid bugs on malloc() */
if (bin->shdr[bin->ehdr.e_shstrndx].sh_size > UT32_MAX) {
return false;
}
if (!bin->shdr[bin->ehdr.e_shstrndx].sh_size) {
return false;
}
bin->shstrtab_section = bin->strtab_section = &bin->shdr[bin->ehdr.e_shstrndx];
bin->shstrtab_size = bin->strtab_section->sh_size;
if (bin->shstrtab_size > bin->size) {
return false;
}
if (!(bin->shstrtab = calloc (1, bin->shstrtab_size + 1))) {
perror ("malloc");
bin->shstrtab = NULL;
return false;
}
if (bin->shstrtab_section->sh_offset > bin->size) {
R_FREE (bin->shstrtab);
return false;
}
if (bin->shstrtab_section->sh_offset +
bin->shstrtab_section->sh_size > bin->size) {
R_FREE (bin->shstrtab);
return false;
}
if (r_buf_read_at (bin->b, bin->shstrtab_section->sh_offset, (ut8*)bin->shstrtab,
bin->shstrtab_section->sh_size + 1) < 1) {
bprintf ("Warning: read (shstrtab) at 0x%"PFMT64x"\n",
(ut64) bin->shstrtab_section->sh_offset);
R_FREE (bin->shstrtab);
return false;
}
bin->shstrtab[bin->shstrtab_section->sh_size] = '\0';
sdb_num_set (bin->kv, "elf_shstrtab.offset", bin->shstrtab_section->sh_offset, 0);
sdb_num_set (bin->kv, "elf_shstrtab.size", bin->shstrtab_section->sh_size, 0);
return true;
}
static int init_dynamic_section(struct Elf_(r_bin_elf_obj_t) *bin) {
Elf_(Dyn) *dyn = NULL;
Elf_(Dyn) d = {0};
Elf_(Addr) strtabaddr = 0;
ut64 offset = 0;
char *strtab = NULL;
size_t relentry = 0, strsize = 0;
int entries;
int i, j, len, r;
ut8 sdyn[sizeof (Elf_(Dyn))] = {0};
ut32 dyn_size = 0;
if (!bin || !bin->phdr || !bin->ehdr.e_phnum) {
return false;
}
for (i = 0; i < bin->ehdr.e_phnum ; i++) {
if (bin->phdr[i].p_type == PT_DYNAMIC) {
dyn_size = bin->phdr[i].p_filesz;
break;
}
}
if (i == bin->ehdr.e_phnum) {
return false;
}
if (bin->phdr[i].p_filesz > bin->size) {
return false;
}
if (bin->phdr[i].p_offset > bin->size) {
return false;
}
if (bin->phdr[i].p_offset + sizeof(Elf_(Dyn)) > bin->size) {
return false;
}
for (entries = 0; entries < (dyn_size / sizeof (Elf_(Dyn))); entries++) {
j = 0;
len = r_buf_read_at (bin->b, bin->phdr[i].p_offset + entries * sizeof (Elf_(Dyn)), sdyn, sizeof (Elf_(Dyn)));
if (len < 1) {
goto beach;
}
#if R_BIN_ELF64
d.d_tag = READ64 (sdyn, j)
#else
d.d_tag = READ32 (sdyn, j)
#endif
if (d.d_tag == DT_NULL) {
break;
}
}
if (entries < 1) {
return false;
}
dyn = (Elf_(Dyn)*)calloc (entries, sizeof (Elf_(Dyn)));
if (!dyn) {
return false;
}
if (!UT32_MUL (&dyn_size, entries, sizeof (Elf_(Dyn)))) {
goto beach;
}
if (!dyn_size) {
goto beach;
}
offset = Elf_(r_bin_elf_v2p) (bin, bin->phdr[i].p_vaddr);
if (offset > bin->size || offset + dyn_size > bin->size) {
goto beach;
}
for (i = 0; i < entries; i++) {
j = 0;
r_buf_read_at (bin->b, offset + i * sizeof (Elf_(Dyn)), sdyn, sizeof (Elf_(Dyn)));
if (len < 1) {
bprintf("Warning: read (dyn)\n");
}
#if R_BIN_ELF64
dyn[i].d_tag = READ64 (sdyn, j)
dyn[i].d_un.d_ptr = READ64 (sdyn, j)
#else
dyn[i].d_tag = READ32 (sdyn, j)
dyn[i].d_un.d_ptr = READ32 (sdyn, j)
#endif
switch (dyn[i].d_tag) {
case DT_STRTAB: strtabaddr = Elf_(r_bin_elf_v2p) (bin, dyn[i].d_un.d_ptr); break;
case DT_STRSZ: strsize = dyn[i].d_un.d_val; break;
case DT_PLTREL: bin->is_rela = dyn[i].d_un.d_val; break;
case DT_RELAENT: relentry = dyn[i].d_un.d_val; break;
default:
if ((dyn[i].d_tag >= DT_VERSYM) && (dyn[i].d_tag <= DT_VERNEEDNUM)) {
bin->version_info[DT_VERSIONTAGIDX (dyn[i].d_tag)] = dyn[i].d_un.d_val;
}
break;
}
}
if (!bin->is_rela) {
bin->is_rela = sizeof (Elf_(Rela)) == relentry? DT_RELA : DT_REL;
}
if (!strtabaddr || strtabaddr > bin->size || strsize > ST32_MAX || !strsize || strsize > bin->size) {
if (!strtabaddr) {
bprintf ("Warning: section.shstrtab not found or invalid\n");
}
goto beach;
}
strtab = (char *)calloc (1, strsize + 1);
if (!strtab) {
goto beach;
}
if (strtabaddr + strsize > bin->size) {
free (strtab);
goto beach;
}
r = r_buf_read_at (bin->b, strtabaddr, (ut8 *)strtab, strsize);
if (r < 1) {
free (strtab);
goto beach;
}
bin->dyn_buf = dyn;
bin->dyn_entries = entries;
bin->strtab = strtab;
bin->strtab_size = strsize;
r = Elf_(r_bin_elf_has_relro)(bin);
switch (r) {
case R_ELF_FULL_RELRO:
sdb_set (bin->kv, "elf.relro", "full", 0);
break;
case R_ELF_PART_RELRO:
sdb_set (bin->kv, "elf.relro", "partial", 0);
break;
default:
sdb_set (bin->kv, "elf.relro", "no", 0);
break;
}
sdb_num_set (bin->kv, "elf_strtab.offset", strtabaddr, 0);
sdb_num_set (bin->kv, "elf_strtab.size", strsize, 0);
return true;
beach:
free (dyn);
return false;
}
static RBinElfSection* get_section_by_name(ELFOBJ *bin, const char *section_name) {
int i;
if (!bin->g_sections) {
return NULL;
}
for (i = 0; !bin->g_sections[i].last; i++) {
if (!strncmp (bin->g_sections[i].name, section_name, ELF_STRING_LENGTH-1)) {
return &bin->g_sections[i];
}
}
return NULL;
}
static char *get_ver_flags(ut32 flags) {
static char buff[32];
buff[0] = 0;
if (!flags) {
return "none";
}
if (flags & VER_FLG_BASE) {
strcpy (buff, "BASE ");
}
if (flags & VER_FLG_WEAK) {
if (flags & VER_FLG_BASE) {
strcat (buff, "| ");
}
strcat (buff, "WEAK ");
}
if (flags & ~(VER_FLG_BASE | VER_FLG_WEAK)) {
strcat (buff, "| <unknown>");
}
return buff;
}
static Sdb *store_versioninfo_gnu_versym(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
int i;
const ut64 num_entries = sz / sizeof (Elf_(Versym));
const char *section_name = "";
const char *link_section_name = "";
Elf_(Shdr) *link_shdr = NULL;
Sdb *sdb = sdb_new0();
if (!sdb) {
return NULL;
}
if (!bin->version_info[DT_VERSIONTAGIDX (DT_VERSYM)]) {
sdb_free (sdb);
return NULL;
}
if (shdr->sh_link > bin->ehdr.e_shnum) {
sdb_free (sdb);
return NULL;
}
link_shdr = &bin->shdr[shdr->sh_link];
ut8 *edata = (ut8*) calloc (R_MAX (1, num_entries), sizeof (ut16));
if (!edata) {
sdb_free (sdb);
return NULL;
}
ut16 *data = (ut16*) calloc (R_MAX (1, num_entries), sizeof (ut16));
if (!data) {
free (edata);
sdb_free (sdb);
return NULL;
}
ut64 off = Elf_(r_bin_elf_v2p) (bin, bin->version_info[DT_VERSIONTAGIDX (DT_VERSYM)]);
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
r_buf_read_at (bin->b, off, edata, sizeof (ut16) * num_entries);
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "num_entries", num_entries, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (i = num_entries; i--;) {
data[i] = r_read_ble16 (&edata[i * sizeof (ut16)], bin->endian);
}
R_FREE (edata);
for (i = 0; i < num_entries; i += 4) {
int j;
int check_def;
char key[32] = {0};
Sdb *sdb_entry = sdb_new0 ();
snprintf (key, sizeof (key), "entry%d", i / 4);
sdb_ns_set (sdb, key, sdb_entry);
sdb_num_set (sdb_entry, "idx", i, 0);
for (j = 0; (j < 4) && (i + j) < num_entries; ++j) {
int k;
char *tmp_val = NULL;
snprintf (key, sizeof (key), "value%d", j);
switch (data[i + j]) {
case 0:
sdb_set (sdb_entry, key, "0 (*local*)", 0);
break;
case 1:
sdb_set (sdb_entry, key, "1 (*global*)", 0);
break;
default:
tmp_val = sdb_fmt (0, "%x ", data[i+j] & 0x7FFF);
check_def = true;
if (bin->version_info[DT_VERSIONTAGIDX (DT_VERNEED)]) {
Elf_(Verneed) vn;
ut8 svn[sizeof (Elf_(Verneed))] = {0};
ut64 offset = Elf_(r_bin_elf_v2p) (bin, bin->version_info[DT_VERSIONTAGIDX (DT_VERNEED)]);
do {
Elf_(Vernaux) vna;
ut8 svna[sizeof (Elf_(Vernaux))] = {0};
ut64 a_off;
if (offset > bin->size || offset + sizeof (vn) > bin->size) {
goto beach;
}
if (r_buf_read_at (bin->b, offset, svn, sizeof (svn)) < 0) {
bprintf ("Warning: Cannot read Verneed for Versym\n");
goto beach;
}
k = 0;
vn.vn_version = READ16 (svn, k)
vn.vn_cnt = READ16 (svn, k)
vn.vn_file = READ32 (svn, k)
vn.vn_aux = READ32 (svn, k)
vn.vn_next = READ32 (svn, k)
a_off = offset + vn.vn_aux;
do {
if (a_off > bin->size || a_off + sizeof (vna) > bin->size) {
goto beach;
}
if (r_buf_read_at (bin->b, a_off, svna, sizeof (svna)) < 0) {
bprintf ("Warning: Cannot read Vernaux for Versym\n");
goto beach;
}
k = 0;
vna.vna_hash = READ32 (svna, k)
vna.vna_flags = READ16 (svna, k)
vna.vna_other = READ16 (svna, k)
vna.vna_name = READ32 (svna, k)
vna.vna_next = READ32 (svna, k)
a_off += vna.vna_next;
} while (vna.vna_other != data[i + j] && vna.vna_next != 0);
if (vna.vna_other == data[i + j]) {
if (vna.vna_name > bin->strtab_size) {
goto beach;
}
sdb_set (sdb_entry, key, sdb_fmt (0, "%s(%s)", tmp_val, bin->strtab + vna.vna_name), 0);
check_def = false;
break;
}
offset += vn.vn_next;
} while (vn.vn_next);
}
ut64 vinfoaddr = bin->version_info[DT_VERSIONTAGIDX (DT_VERDEF)];
if (check_def && data[i + j] != 0x8001 && vinfoaddr) {
Elf_(Verdef) vd;
ut8 svd[sizeof (Elf_(Verdef))] = {0};
ut64 offset = Elf_(r_bin_elf_v2p) (bin, vinfoaddr);
if (offset > bin->size || offset + sizeof (vd) > bin->size) {
goto beach;
}
do {
if (r_buf_read_at (bin->b, offset, svd, sizeof (svd)) < 0) {
bprintf ("Warning: Cannot read Verdef for Versym\n");
goto beach;
}
k = 0;
vd.vd_version = READ16 (svd, k)
vd.vd_flags = READ16 (svd, k)
vd.vd_ndx = READ16 (svd, k)
vd.vd_cnt = READ16 (svd, k)
vd.vd_hash = READ32 (svd, k)
vd.vd_aux = READ32 (svd, k)
vd.vd_next = READ32 (svd, k)
offset += vd.vd_next;
} while (vd.vd_ndx != (data[i + j] & 0x7FFF) && vd.vd_next != 0);
if (vd.vd_ndx == (data[i + j] & 0x7FFF)) {
Elf_(Verdaux) vda;
ut8 svda[sizeof (Elf_(Verdaux))] = {0};
ut64 off_vda = offset - vd.vd_next + vd.vd_aux;
if (off_vda > bin->size || off_vda + sizeof (vda) > bin->size) {
goto beach;
}
if (r_buf_read_at (bin->b, off_vda, svda, sizeof (svda)) < 0) {
bprintf ("Warning: Cannot read Verdaux for Versym\n");
goto beach;
}
k = 0;
vda.vda_name = READ32 (svda, k)
vda.vda_next = READ32 (svda, k)
if (vda.vda_name > bin->strtab_size) {
goto beach;
}
const char *name = bin->strtab + vda.vda_name;
sdb_set (sdb_entry, key, sdb_fmt (0,"%s(%s%-*s)", tmp_val, name, (int)(12 - strlen (name)),")") , 0);
}
}
}
}
}
beach:
free (data);
return sdb;
}
static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
vstart += verdef->vd_aux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
ut8 *end, *need = NULL;
const char *section_name = "";
Elf_(Shdr) *link_shdr = NULL;
const char *link_section_name = "";
Sdb *sdb_vernaux = NULL;
Sdb *sdb_version = NULL;
Sdb *sdb = NULL;
int i, cnt;
if (!bin || !bin->dynstr) {
return NULL;
}
if (shdr->sh_link > bin->ehdr.e_shnum) {
return NULL;
}
if (shdr->sh_size < 1) {
return NULL;
}
sdb = sdb_new0 ();
if (!sdb) {
return NULL;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) {
bprintf ("Warning: Cannot allocate memory for Elf_(Verneed)\n");
goto beach;
}
end = need + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "num_entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) {
goto beach;
}
if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) {
goto beach;
}
i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size);
if (i < 0)
goto beach;
//XXX we should use DT_VERNEEDNUM instead of sh_info
//TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html
for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) {
int j, isum;
ut8 *vstart = need + i;
Elf_(Verneed) vvn = {0};
if (vstart + sizeof (Elf_(Verneed)) > end) {
goto beach;
}
Elf_(Verneed) *entry = &vvn;
char key[32] = {0};
sdb_version = sdb_new0 ();
if (!sdb_version) {
goto beach;
}
j = 0;
vvn.vn_version = READ16 (vstart, j)
vvn.vn_cnt = READ16 (vstart, j)
vvn.vn_file = READ32 (vstart, j)
vvn.vn_aux = READ32 (vstart, j)
vvn.vn_next = READ32 (vstart, j)
sdb_num_set (sdb_version, "vn_version", entry->vn_version, 0);
sdb_num_set (sdb_version, "idx", i, 0);
if (entry->vn_file > bin->dynstr_size) {
goto beach;
}
{
char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16);
sdb_set (sdb_version, "file_name", s, 0);
free (s);
}
sdb_num_set (sdb_version, "cnt", entry->vn_cnt, 0);
st32 vnaux = entry->vn_aux;
if (vnaux < 1) {
goto beach;
}
vstart += vnaux;
for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) {
int k;
Elf_(Vernaux) * aux = NULL;
Elf_(Vernaux) vaux = {0};
sdb_vernaux = sdb_new0 ();
if (!sdb_vernaux) {
goto beach;
}
aux = (Elf_(Vernaux)*)&vaux;
k = 0;
vaux.vna_hash = READ32 (vstart, k)
vaux.vna_flags = READ16 (vstart, k)
vaux.vna_other = READ16 (vstart, k)
vaux.vna_name = READ32 (vstart, k)
vaux.vna_next = READ32 (vstart, k)
if (aux->vna_name > bin->dynstr_size) {
goto beach;
}
sdb_num_set (sdb_vernaux, "idx", isum, 0);
if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) {
char name [16];
strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1);
name[sizeof(name)-1] = 0;
sdb_set (sdb_vernaux, "name", name, 0);
}
sdb_set (sdb_vernaux, "flags", get_ver_flags (aux->vna_flags), 0);
sdb_num_set (sdb_vernaux, "version", aux->vna_other, 0);
isum += aux->vna_next;
vstart += aux->vna_next;
snprintf (key, sizeof (key), "vernaux%d", j);
sdb_ns_set (sdb_version, key, sdb_vernaux);
}
if ((int)entry->vn_next < 0) {
bprintf ("Invalid vn_next\n");
break;
}
i += entry->vn_next;
snprintf (key, sizeof (key), "version%d", cnt );
sdb_ns_set (sdb, key, sdb_version);
//if entry->vn_next is 0 it iterate infinitely
if (!entry->vn_next) {
break;
}
}
free (need);
return sdb;
beach:
free (need);
sdb_free (sdb_vernaux);
sdb_free (sdb_version);
sdb_free (sdb);
return NULL;
}
static Sdb *store_versioninfo(ELFOBJ *bin) {
Sdb *sdb_versioninfo = NULL;
int num_verdef = 0;
int num_verneed = 0;
int num_versym = 0;
int i;
if (!bin || !bin->shdr) {
return NULL;
}
if (!(sdb_versioninfo = sdb_new0 ())) {
return NULL;
}
for (i = 0; i < bin->ehdr.e_shnum; i++) {
Sdb *sdb = NULL;
char key[32] = {0};
int size = bin->shdr[i].sh_size;
if (size - (i*sizeof(Elf_(Shdr)) > bin->size)) {
size = bin->size - (i*sizeof(Elf_(Shdr)));
}
int left = size - (i * sizeof (Elf_(Shdr)));
left = R_MIN (left, bin->shdr[i].sh_size);
if (left < 0) {
break;
}
switch (bin->shdr[i].sh_type) {
case SHT_GNU_verdef:
sdb = store_versioninfo_gnu_verdef (bin, &bin->shdr[i], left);
snprintf (key, sizeof (key), "verdef%d", num_verdef++);
sdb_ns_set (sdb_versioninfo, key, sdb);
break;
case SHT_GNU_verneed:
sdb = store_versioninfo_gnu_verneed (bin, &bin->shdr[i], left);
snprintf (key, sizeof (key), "verneed%d", num_verneed++);
sdb_ns_set (sdb_versioninfo, key, sdb);
break;
case SHT_GNU_versym:
sdb = store_versioninfo_gnu_versym (bin, &bin->shdr[i], left);
snprintf (key, sizeof (key), "versym%d", num_versym++);
sdb_ns_set (sdb_versioninfo, key, sdb);
break;
}
}
return sdb_versioninfo;
}
static bool init_dynstr(ELFOBJ *bin) {
int i, r;
const char *section_name = NULL;
if (!bin || !bin->shdr) {
return false;
}
if (!bin->shstrtab) {
return false;
}
for (i = 0; i < bin->ehdr.e_shnum; ++i) {
if (bin->shdr[i].sh_name > bin->shstrtab_size) {
return false;
}
section_name = &bin->shstrtab[bin->shdr[i].sh_name];
if (bin->shdr[i].sh_type == SHT_STRTAB && !strcmp (section_name, ".dynstr")) {
if (!(bin->dynstr = (char*) calloc (bin->shdr[i].sh_size + 1, sizeof (char)))) {
bprintf("Warning: Cannot allocate memory for dynamic strings\n");
return false;
}
if (bin->shdr[i].sh_offset > bin->size) {
return false;
}
if (bin->shdr[i].sh_offset + bin->shdr[i].sh_size > bin->size) {
return false;
}
if (bin->shdr[i].sh_offset + bin->shdr[i].sh_size < bin->shdr[i].sh_size) {
return false;
}
r = r_buf_read_at (bin->b, bin->shdr[i].sh_offset, (ut8*)bin->dynstr, bin->shdr[i].sh_size);
if (r < 1) {
R_FREE (bin->dynstr);
bin->dynstr_size = 0;
return false;
}
bin->dynstr_size = bin->shdr[i].sh_size;
return true;
}
}
return false;
}
static int elf_init(ELFOBJ *bin) {
bin->phdr = NULL;
bin->shdr = NULL;
bin->strtab = NULL;
bin->shstrtab = NULL;
bin->strtab_size = 0;
bin->strtab_section = NULL;
bin->dyn_buf = NULL;
bin->dynstr = NULL;
ZERO_FILL (bin->version_info);
bin->g_sections = NULL;
bin->g_symbols = NULL;
bin->g_imports = NULL;
/* bin is not an ELF */
if (!init_ehdr (bin)) {
return false;
}
if (!init_phdr (bin)) {
bprintf ("Warning: Cannot initialize program headers\n");
}
if (!init_shdr (bin)) {
bprintf ("Warning: Cannot initialize section headers\n");
}
if (!init_strtab (bin)) {
bprintf ("Warning: Cannot initialize strings table\n");
}
if (!init_dynstr (bin)) {
bprintf ("Warning: Cannot initialize dynamic strings\n");
}
bin->baddr = Elf_(r_bin_elf_get_baddr) (bin);
if (!init_dynamic_section (bin) && !Elf_(r_bin_elf_get_static)(bin))
bprintf ("Warning: Cannot initialize dynamic section\n");
bin->imports_by_ord_size = 0;
bin->imports_by_ord = NULL;
bin->symbols_by_ord_size = 0;
bin->symbols_by_ord = NULL;
bin->g_sections = Elf_(r_bin_elf_get_sections) (bin);
bin->boffset = Elf_(r_bin_elf_get_boffset) (bin);
sdb_ns_set (bin->kv, "versioninfo", store_versioninfo (bin));
return true;
}
ut64 Elf_(r_bin_elf_get_section_offset)(ELFOBJ *bin, const char *section_name) {
RBinElfSection *section = get_section_by_name (bin, section_name);
if (!section) return UT64_MAX;
return section->offset;
}
ut64 Elf_(r_bin_elf_get_section_addr)(ELFOBJ *bin, const char *section_name) {
RBinElfSection *section = get_section_by_name (bin, section_name);
return section? section->rva: UT64_MAX;
}
ut64 Elf_(r_bin_elf_get_section_addr_end)(ELFOBJ *bin, const char *section_name) {
RBinElfSection *section = get_section_by_name (bin, section_name);
return section? section->rva + section->size: UT64_MAX;
}
#define REL (is_rela ? (void*)rela : (void*)rel)
#define REL_BUF is_rela ? (ut8*)(&rela[k]) : (ut8*)(&rel[k])
#define REL_OFFSET is_rela ? rela[k].r_offset : rel[k].r_offset
#define REL_TYPE is_rela ? rela[k].r_info : rel[k].r_info
static ut64 get_import_addr(ELFOBJ *bin, int sym) {
Elf_(Rel) *rel = NULL;
Elf_(Rela) *rela = NULL;
ut8 rl[sizeof (Elf_(Rel))] = {0};
ut8 rla[sizeof (Elf_(Rela))] = {0};
RBinElfSection *rel_sec = NULL;
Elf_(Addr) plt_sym_addr = -1;
ut64 got_addr, got_offset;
ut64 plt_addr;
int j, k, tsize, len, nrel;
bool is_rela = false;
const char *rel_sect[] = { ".rel.plt", ".rela.plt", ".rel.dyn", ".rela.dyn", NULL };
const char *rela_sect[] = { ".rela.plt", ".rel.plt", ".rela.dyn", ".rel.dyn", NULL };
if ((!bin->shdr || !bin->strtab) && !bin->phdr) {
return -1;
}
if ((got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got")) == -1 &&
(got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got.plt")) == -1) {
return -1;
}
if ((got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got")) == -1 &&
(got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got.plt")) == -1) {
return -1;
}
if (bin->is_rela == DT_REL) {
j = 0;
while (!rel_sec && rel_sect[j]) {
rel_sec = get_section_by_name (bin, rel_sect[j++]);
}
tsize = sizeof (Elf_(Rel));
} else if (bin->is_rela == DT_RELA) {
j = 0;
while (!rel_sec && rela_sect[j]) {
rel_sec = get_section_by_name (bin, rela_sect[j++]);
}
is_rela = true;
tsize = sizeof (Elf_(Rela));
}
if (!rel_sec) {
return -1;
}
if (rel_sec->size < 1) {
return -1;
}
nrel = (ut32)((int)rel_sec->size / (int)tsize);
if (nrel < 1) {
return -1;
}
if (is_rela) {
rela = calloc (nrel, tsize);
if (!rela) {
return -1;
}
} else {
rel = calloc (nrel, tsize);
if (!rel) {
return -1;
}
}
for (j = k = 0; j < rel_sec->size && k < nrel; j += tsize, k++) {
int l = 0;
if (rel_sec->offset + j > bin->size) {
goto out;
}
if (rel_sec->offset + j + tsize > bin->size) {
goto out;
}
len = r_buf_read_at (
bin->b, rel_sec->offset + j, is_rela ? rla : rl,
is_rela ? sizeof (Elf_ (Rela)) : sizeof (Elf_ (Rel)));
if (len < 1) {
goto out;
}
#if R_BIN_ELF64
if (is_rela) {
rela[k].r_offset = READ64 (rla, l)
rela[k].r_info = READ64 (rla, l)
rela[k].r_addend = READ64 (rla, l)
} else {
rel[k].r_offset = READ64 (rl, l)
rel[k].r_info = READ64 (rl, l)
}
#else
if (is_rela) {
rela[k].r_offset = READ32 (rla, l)
rela[k].r_info = READ32 (rla, l)
rela[k].r_addend = READ32 (rla, l)
} else {
rel[k].r_offset = READ32 (rl, l)
rel[k].r_info = READ32 (rl, l)
}
#endif
int reloc_type = ELF_R_TYPE (REL_TYPE);
int reloc_sym = ELF_R_SYM (REL_TYPE);
if (reloc_sym == sym) {
int of = REL_OFFSET;
of = of - got_addr + got_offset;
switch (bin->ehdr.e_machine) {
case EM_PPC:
case EM_PPC64:
{
RBinElfSection *s = get_section_by_name (bin, ".plt");
if (s) {
ut8 buf[4];
ut64 base;
len = r_buf_read_at (bin->b, s->offset, buf, sizeof (buf));
if (len < 4) {
goto out;
}
base = r_read_be32 (buf);
base -= (nrel * 16);
base += (k * 16);
plt_addr = base;
free (REL);
return plt_addr;
}
}
break;
case EM_SPARC:
case EM_SPARCV9:
case EM_SPARC32PLUS:
plt_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".plt");
if (plt_addr == -1) {
free (rela);
return -1;
}
if (reloc_type == R_386_PC16) {
plt_addr += k * 12 + 20;
// thumb symbol
if (plt_addr & 1) {
plt_addr--;
}
free (REL);
return plt_addr;
} else {
bprintf ("Unknown sparc reloc type %d\n", reloc_type);
}
/* SPARC */
break;
case EM_ARM:
case EM_AARCH64:
plt_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".plt");
if (plt_addr == -1) {
free (rela);
return UT32_MAX;
}
switch (reloc_type) {
case R_386_8:
{
plt_addr += k * 12 + 20;
// thumb symbol
if (plt_addr & 1) {
plt_addr--;
}
free (REL);
return plt_addr;
}
break;
case 1026: // arm64 aarch64
plt_sym_addr = plt_addr + k * 16 + 32;
goto done;
default:
bprintf ("Unsupported relocation type for imports %d\n", reloc_type);
break;
}
break;
case EM_386:
case EM_X86_64:
switch (reloc_type) {
case 1: // unknown relocs found in voidlinux for x86-64
// break;
case R_386_GLOB_DAT:
case R_386_JMP_SLOT:
{
ut8 buf[8];
if (of + sizeof(Elf_(Addr)) < bin->size) {
// ONLY FOR X86
if (of > bin->size || of + sizeof (Elf_(Addr)) > bin->size) {
goto out;
}
len = r_buf_read_at (bin->b, of, buf, sizeof (Elf_(Addr)));
if (len < -1) {
goto out;
}
plt_sym_addr = sizeof (Elf_(Addr)) == 4
? r_read_le32 (buf)
: r_read_le64 (buf);
if (!plt_sym_addr) {
//XXX HACK ALERT!!!! full relro?? try to fix it
//will there always be .plt.got, what would happen if is .got.plt?
RBinElfSection *s = get_section_by_name (bin, ".plt.got");
if (Elf_(r_bin_elf_has_relro)(bin) < R_ELF_PART_RELRO || !s) {
goto done;
}
plt_addr = s->offset;
of = of + got_addr - got_offset;
while (plt_addr + 2 + 4 < s->offset + s->size) {
/*we try to locate the plt entry that correspond with the relocation
since got does not point back to .plt. In this case it has the following
form
ff253a152000 JMP QWORD [RIP + 0x20153A]
6690 NOP
----
ff25ec9f0408 JMP DWORD [reloc.puts_236]
plt_addr + 2 to remove jmp opcode and get the imm reading 4
and if RIP (plt_addr + 6) + imm == rel->offset
return plt_addr, that will be our sym addr
perhaps this hack doesn't work on 32 bits
*/
len = r_buf_read_at (bin->b, plt_addr + 2, buf, 4);
if (len < -1) {
goto out;
}
plt_sym_addr = sizeof (Elf_(Addr)) == 4
? r_read_le32 (buf)
: r_read_le64 (buf);
//relative address
if ((plt_addr + 6 + Elf_(r_bin_elf_v2p) (bin, plt_sym_addr)) == of) {
plt_sym_addr = plt_addr;
goto done;
} else if (plt_sym_addr == of) {
plt_sym_addr = plt_addr;
goto done;
}
plt_addr += 8;
}
} else {
plt_sym_addr -= 6;
}
goto done;
}
break;
}
default:
bprintf ("Unsupported relocation type for imports %d\n", reloc_type);
free (REL);
return of;
break;
}
break;
case 8:
// MIPS32 BIG ENDIAN relocs
{
RBinElfSection *s = get_section_by_name (bin, ".rela.plt");
if (s) {
ut8 buf[1024];
const ut8 *base;
plt_addr = s->rva + s->size;
len = r_buf_read_at (bin->b, s->offset + s->size, buf, sizeof (buf));
if (len != sizeof (buf)) {
// oops
}
base = r_mem_mem_aligned (buf, sizeof (buf), (const ut8*)"\x3c\x0f\x00", 3, 4);
if (base) {
plt_addr += (int)(size_t)(base - buf);
} else {
plt_addr += 108 + 8; // HARDCODED HACK
}
plt_addr += k * 16;
free (REL);
return plt_addr;
}
}
break;
default:
bprintf ("Unsupported relocs type %d for arch %d\n",
reloc_type, bin->ehdr.e_machine);
break;
}
}
}
done:
free (REL);
return plt_sym_addr;
out:
free (REL);
return -1;
}
int Elf_(r_bin_elf_has_nx)(ELFOBJ *bin) {
int i;
if (bin && bin->phdr) {
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_GNU_STACK) {
return (!(bin->phdr[i].p_flags & 1))? 1: 0;
}
}
}
return 0;
}
int Elf_(r_bin_elf_has_relro)(ELFOBJ *bin) {
int i;
bool haveBindNow = false;
bool haveGnuRelro = false;
if (bin && bin->dyn_buf) {
for (i = 0; i < bin->dyn_entries; i++) {
switch (bin->dyn_buf[i].d_tag) {
case DT_BIND_NOW:
haveBindNow = true;
break;
case DT_FLAGS:
for (i++; i < bin->dyn_entries ; i++) {
ut32 dTag = bin->dyn_buf[i].d_tag;
if (!dTag) {
break;
}
switch (dTag) {
case DT_FLAGS_1:
if (bin->dyn_buf[i].d_un.d_val & DF_1_NOW) {
haveBindNow = true;
break;
}
}
}
break;
}
}
}
if (bin && bin->phdr) {
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_GNU_RELRO) {
haveGnuRelro = true;
break;
}
}
}
if (haveGnuRelro) {
if (haveBindNow) {
return R_ELF_FULL_RELRO;
}
return R_ELF_PART_RELRO;
}
return R_ELF_NO_RELRO;
}
/*
To compute the base address, one determines the memory
address associated with the lowest p_vaddr value for a
PT_LOAD segment. One then obtains the base address by
truncating the memory address to the nearest multiple
of the maximum page size
*/
ut64 Elf_(r_bin_elf_get_baddr)(ELFOBJ *bin) {
int i;
ut64 tmp, base = UT64_MAX;
if (!bin) {
return 0;
}
if (bin->phdr) {
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_LOAD) {
tmp = (ut64)bin->phdr[i].p_vaddr & ELF_PAGE_MASK;
tmp = tmp - (tmp % (1 << ELF_PAGE_SIZE));
if (tmp < base) {
base = tmp;
}
}
}
}
if (base == UT64_MAX && bin->ehdr.e_type == ET_REL) {
//we return our own base address for ET_REL type
//we act as a loader for ELF
return 0x08000000;
}
return base == UT64_MAX ? 0 : base;
}
ut64 Elf_(r_bin_elf_get_boffset)(ELFOBJ *bin) {
int i;
ut64 tmp, base = UT64_MAX;
if (bin && bin->phdr) {
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_LOAD) {
tmp = (ut64)bin->phdr[i].p_offset & ELF_PAGE_MASK;
tmp = tmp - (tmp % (1 << ELF_PAGE_SIZE));
if (tmp < base) {
base = tmp;
}
}
}
}
return base == UT64_MAX ? 0 : base;
}
ut64 Elf_(r_bin_elf_get_init_offset)(ELFOBJ *bin) {
ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin);
ut8 buf[512];
if (!bin) {
return 0LL;
}
if (r_buf_read_at (bin->b, entry + 16, buf, sizeof (buf)) < 1) {
bprintf ("Warning: read (init_offset)\n");
return 0;
}
if (buf[0] == 0x68) { // push // x86 only
ut64 addr;
memmove (buf, buf+1, 4);
addr = (ut64)r_read_le32 (buf);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
return 0;
}
ut64 Elf_(r_bin_elf_get_fini_offset)(ELFOBJ *bin) {
ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin);
ut8 buf[512];
if (!bin) {
return 0LL;
}
if (r_buf_read_at (bin->b, entry+11, buf, sizeof (buf)) == -1) {
bprintf ("Warning: read (get_fini)\n");
return 0;
}
if (*buf == 0x68) { // push // x86/32 only
ut64 addr;
memmove (buf, buf+1, 4);
addr = (ut64)r_read_le32 (buf);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
return 0;
}
ut64 Elf_(r_bin_elf_get_entry_offset)(ELFOBJ *bin) {
ut64 entry;
if (!bin) {
return 0LL;
}
entry = bin->ehdr.e_entry;
if (!entry) {
entry = Elf_(r_bin_elf_get_section_offset)(bin, ".init.text");
if (entry != UT64_MAX) {
return entry;
}
entry = Elf_(r_bin_elf_get_section_offset)(bin, ".text");
if (entry != UT64_MAX) {
return entry;
}
entry = Elf_(r_bin_elf_get_section_offset)(bin, ".init");
if (entry != UT64_MAX) {
return entry;
}
if (entry == UT64_MAX) {
return 0;
}
}
return Elf_(r_bin_elf_v2p) (bin, entry);
}
static ut64 getmainsymbol(ELFOBJ *bin) {
struct r_bin_elf_symbol_t *symbol;
int i;
if (!(symbol = Elf_(r_bin_elf_get_symbols) (bin))) {
return UT64_MAX;
}
for (i = 0; !symbol[i].last; i++) {
if (!strcmp (symbol[i].name, "main")) {
ut64 paddr = symbol[i].offset;
return Elf_(r_bin_elf_p2v) (bin, paddr);
}
}
return UT64_MAX;
}
ut64 Elf_(r_bin_elf_get_main_offset)(ELFOBJ *bin) {
ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin);
ut8 buf[512];
if (!bin) {
return 0LL;
}
if (entry > bin->size || (entry + sizeof (buf)) > bin->size) {
return 0;
}
if (r_buf_read_at (bin->b, entry, buf, sizeof (buf)) < 1) {
bprintf ("Warning: read (main)\n");
return 0;
}
// ARM64
if (buf[0x18+3] == 0x58 && buf[0x2f] == 0x00) {
ut32 entry_vaddr = Elf_(r_bin_elf_p2v) (bin, entry);
ut32 main_addr = r_read_le32 (&buf[0x30]);
if ((main_addr >> 16) == (entry_vaddr >> 16)) {
return Elf_(r_bin_elf_v2p) (bin, main_addr);
}
}
// TODO: Use arch to identify arch before memcmp's
// ARM
ut64 text = Elf_(r_bin_elf_get_section_offset)(bin, ".text");
ut64 text_end = text + bin->size;
// ARM-Thumb-Linux
if (entry & 1 && !memcmp (buf, "\xf0\x00\x0b\x4f\xf0\x00", 6)) {
ut32 * ptr = (ut32*)(buf+40-1);
if (*ptr &1) {
return Elf_(r_bin_elf_v2p) (bin, *ptr -1);
}
}
if (!memcmp (buf, "\x00\xb0\xa0\xe3\x00\xe0\xa0\xe3", 8)) {
// endian stuff here
ut32 *addr = (ut32*)(buf+0x34);
/*
0x00012000 00b0a0e3 mov fp, 0
0x00012004 00e0a0e3 mov lr, 0
*/
if (*addr > text && *addr < (text_end)) {
return Elf_(r_bin_elf_v2p) (bin, *addr);
}
}
// MIPS
/* get .got, calculate offset of main symbol */
if (!memcmp (buf, "\x21\x00\xe0\x03\x01\x00\x11\x04", 8)) {
/*
assuming the startup code looks like
got = gp-0x7ff0
got[index__libc_start_main] ( got[index_main] );
looking for the instruction generating the first argument to find main
lw a0, offset(gp)
*/
ut64 got_offset;
if ((got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got")) != -1 ||
(got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got.plt")) != -1)
{
const ut64 gp = got_offset + 0x7ff0;
unsigned i;
for (i = 0; i < sizeof(buf) / sizeof(buf[0]); i += 4) {
const ut32 instr = r_read_le32 (&buf[i]);
if ((instr & 0xffff0000) == 0x8f840000) { // lw a0, offset(gp)
const short delta = instr & 0x0000ffff;
r_buf_read_at (bin->b, /* got_entry_offset = */ gp + delta, buf, 4);
return Elf_(r_bin_elf_v2p) (bin, r_read_le32 (&buf[0]));
}
}
}
return 0;
}
// ARM
if (!memcmp (buf, "\x24\xc0\x9f\xe5\x00\xb0\xa0\xe3", 8)) {
ut64 addr = r_read_le32 (&buf[48]);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
// X86-CGC
if (buf[0] == 0xe8 && !memcmp (buf + 5, "\x50\xe8\x00\x00\x00\x00\xb8\x01\x00\x00\x00\x53", 12)) {
size_t SIZEOF_CALL = 5;
ut64 rel_addr = (ut64)((int)(buf[1] + (buf[2] << 8) + (buf[3] << 16) + (buf[4] << 24)));
ut64 addr = Elf_(r_bin_elf_p2v)(bin, entry + SIZEOF_CALL);
addr += rel_addr;
return Elf_(r_bin_elf_v2p) (bin, addr);
}
// X86-PIE
if (buf[0x00] == 0x48 && buf[0x1e] == 0x8d && buf[0x11] == 0xe8) {
ut32 *pmain = (ut32*)(buf + 0x30);
ut64 vmain = Elf_(r_bin_elf_p2v) (bin, (ut64)*pmain);
ut64 ventry = Elf_(r_bin_elf_p2v) (bin, entry);
if (vmain >> 16 == ventry >> 16) {
return (ut64)vmain;
}
}
// X86-PIE
if (buf[0x1d] == 0x48 && buf[0x1e] == 0x8b) {
if (!memcmp (buf, "\x31\xed\x49\x89", 4)) {// linux
ut64 maddr, baddr;
ut8 n32s[sizeof (ut32)] = {0};
maddr = entry + 0x24 + r_read_le32 (buf + 0x20);
if (r_buf_read_at (bin->b, maddr, n32s, sizeof (ut32)) == -1) {
bprintf ("Warning: read (maddr) 2\n");
return 0;
}
maddr = (ut64)r_read_le32 (&n32s[0]);
baddr = (bin->ehdr.e_entry >> 16) << 16;
if (bin->phdr) {
baddr = Elf_(r_bin_elf_get_baddr) (bin);
}
maddr += baddr;
return maddr;
}
}
// X86-NONPIE
#if R_BIN_ELF64
if (!memcmp (buf, "\x49\x89\xd9", 3) && buf[156] == 0xe8) { // openbsd
return r_read_le32 (&buf[157]) + entry + 156 + 5;
}
if (!memcmp (buf+29, "\x48\xc7\xc7", 3)) { // linux
ut64 addr = (ut64)r_read_le32 (&buf[29 + 3]);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
#else
if (buf[23] == '\x68') {
ut64 addr = (ut64)r_read_le32 (&buf[23 + 1]);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
#endif
/* linux64 pie main -- probably buggy in some cases */
if (buf[29] == 0x48 && buf[30] == 0x8d) { // lea rdi, qword [rip-0x21c4]
ut8 *p = buf + 32;
st32 maindelta = (st32)r_read_le32 (p);
ut64 vmain = (ut64)(entry + 29 + maindelta) + 7;
ut64 ventry = Elf_(r_bin_elf_p2v) (bin, entry);
if (vmain>>16 == ventry>>16) {
return (ut64)vmain;
}
}
/* find sym.main if possible */
{
ut64 m = getmainsymbol (bin);
if (m != UT64_MAX) return m;
}
return UT64_MAX;
}
int Elf_(r_bin_elf_get_stripped)(ELFOBJ *bin) {
int i;
if (!bin->shdr) {
return false;
}
for (i = 0; i < bin->ehdr.e_shnum; i++) {
if (bin->shdr[i].sh_type == SHT_SYMTAB) {
return false;
}
}
return true;
}
char *Elf_(r_bin_elf_intrp)(ELFOBJ *bin) {
int i;
if (!bin || !bin->phdr) {
return NULL;
}
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_INTERP) {
char *str = NULL;
ut64 addr = bin->phdr[i].p_offset;
int sz = bin->phdr[i].p_memsz;
sdb_num_set (bin->kv, "elf_header.intrp_addr", addr, 0);
sdb_num_set (bin->kv, "elf_header.intrp_size", sz, 0);
if (sz < 1) {
return NULL;
}
str = malloc (sz + 1);
if (!str) {
return NULL;
}
if (r_buf_read_at (bin->b, addr, (ut8*)str, sz) < 1) {
bprintf ("Warning: read (main)\n");
return 0;
}
str[sz] = 0;
sdb_set (bin->kv, "elf_header.intrp", str, 0);
return str;
}
}
return NULL;
}
int Elf_(r_bin_elf_get_static)(ELFOBJ *bin) {
int i;
if (!bin->phdr) {
return false;
}
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_INTERP) {
return false;
}
}
return true;
}
char* Elf_(r_bin_elf_get_data_encoding)(ELFOBJ *bin) {
switch (bin->ehdr.e_ident[EI_DATA]) {
case ELFDATANONE: return strdup ("none");
case ELFDATA2LSB: return strdup ("2's complement, little endian");
case ELFDATA2MSB: return strdup ("2's complement, big endian");
default: return r_str_newf ("<unknown: %x>", bin->ehdr.e_ident[EI_DATA]);
}
}
int Elf_(r_bin_elf_has_va)(ELFOBJ *bin) {
return true;
}
char* Elf_(r_bin_elf_get_arch)(ELFOBJ *bin) {
switch (bin->ehdr.e_machine) {
case EM_ARC:
case EM_ARC_A5:
return strdup ("arc");
case EM_AVR: return strdup ("avr");
case EM_CRIS: return strdup ("cris");
case EM_68K: return strdup ("m68k");
case EM_MIPS:
case EM_MIPS_RS3_LE:
case EM_MIPS_X:
return strdup ("mips");
case EM_MCST_ELBRUS:
return strdup ("elbrus");
case EM_TRICORE:
return strdup ("tricore");
case EM_ARM:
case EM_AARCH64:
return strdup ("arm");
case EM_HEXAGON:
return strdup ("hexagon");
case EM_BLACKFIN:
return strdup ("blackfin");
case EM_SPARC:
case EM_SPARC32PLUS:
case EM_SPARCV9:
return strdup ("sparc");
case EM_PPC:
case EM_PPC64:
return strdup ("ppc");
case EM_PARISC:
return strdup ("hppa");
case EM_PROPELLER:
return strdup ("propeller");
case EM_MICROBLAZE:
return strdup ("microblaze.gnu");
case EM_RISCV:
return strdup ("riscv");
case EM_VAX:
return strdup ("vax");
case EM_XTENSA:
return strdup ("xtensa");
case EM_LANAI:
return strdup ("lanai");
case EM_VIDEOCORE3:
case EM_VIDEOCORE4:
return strdup ("vc4");
case EM_SH:
return strdup ("sh");
case EM_V850:
return strdup ("v850");
case EM_IA_64:
return strdup("ia64");
default: return strdup ("x86");
}
}
char* Elf_(r_bin_elf_get_machine_name)(ELFOBJ *bin) {
switch (bin->ehdr.e_machine) {
case EM_NONE: return strdup ("No machine");
case EM_M32: return strdup ("AT&T WE 32100");
case EM_SPARC: return strdup ("SUN SPARC");
case EM_386: return strdup ("Intel 80386");
case EM_68K: return strdup ("Motorola m68k family");
case EM_88K: return strdup ("Motorola m88k family");
case EM_860: return strdup ("Intel 80860");
case EM_MIPS: return strdup ("MIPS R3000");
case EM_S370: return strdup ("IBM System/370");
case EM_MIPS_RS3_LE: return strdup ("MIPS R3000 little-endian");
case EM_PARISC: return strdup ("HPPA");
case EM_VPP500: return strdup ("Fujitsu VPP500");
case EM_SPARC32PLUS: return strdup ("Sun's \"v8plus\"");
case EM_960: return strdup ("Intel 80960");
case EM_PPC: return strdup ("PowerPC");
case EM_PPC64: return strdup ("PowerPC 64-bit");
case EM_S390: return strdup ("IBM S390");
case EM_V800: return strdup ("NEC V800 series");
case EM_FR20: return strdup ("Fujitsu FR20");
case EM_RH32: return strdup ("TRW RH-32");
case EM_RCE: return strdup ("Motorola RCE");
case EM_ARM: return strdup ("ARM");
case EM_BLACKFIN: return strdup ("Analog Devices Blackfin");
case EM_FAKE_ALPHA: return strdup ("Digital Alpha");
case EM_SH: return strdup ("Hitachi SH");
case EM_SPARCV9: return strdup ("SPARC v9 64-bit");
case EM_TRICORE: return strdup ("Siemens Tricore");
case EM_ARC: return strdup ("Argonaut RISC Core");
case EM_H8_300: return strdup ("Hitachi H8/300");
case EM_H8_300H: return strdup ("Hitachi H8/300H");
case EM_H8S: return strdup ("Hitachi H8S");
case EM_H8_500: return strdup ("Hitachi H8/500");
case EM_IA_64: return strdup ("Intel Merced");
case EM_MIPS_X: return strdup ("Stanford MIPS-X");
case EM_COLDFIRE: return strdup ("Motorola Coldfire");
case EM_68HC12: return strdup ("Motorola M68HC12");
case EM_MMA: return strdup ("Fujitsu MMA Multimedia Accelerator");
case EM_PCP: return strdup ("Siemens PCP");
case EM_NCPU: return strdup ("Sony nCPU embeeded RISC");
case EM_NDR1: return strdup ("Denso NDR1 microprocessor");
case EM_STARCORE: return strdup ("Motorola Start*Core processor");
case EM_ME16: return strdup ("Toyota ME16 processor");
case EM_ST100: return strdup ("STMicroelectronic ST100 processor");
case EM_TINYJ: return strdup ("Advanced Logic Corp. Tinyj emb.fam");
case EM_X86_64: return strdup ("AMD x86-64 architecture");
case EM_LANAI: return strdup ("32bit LANAI architecture");
case EM_PDSP: return strdup ("Sony DSP Processor");
case EM_FX66: return strdup ("Siemens FX66 microcontroller");
case EM_ST9PLUS: return strdup ("STMicroelectronics ST9+ 8/16 mc");
case EM_ST7: return strdup ("STmicroelectronics ST7 8 bit mc");
case EM_68HC16: return strdup ("Motorola MC68HC16 microcontroller");
case EM_68HC11: return strdup ("Motorola MC68HC11 microcontroller");
case EM_68HC08: return strdup ("Motorola MC68HC08 microcontroller");
case EM_68HC05: return strdup ("Motorola MC68HC05 microcontroller");
case EM_SVX: return strdup ("Silicon Graphics SVx");
case EM_ST19: return strdup ("STMicroelectronics ST19 8 bit mc");
case EM_VAX: return strdup ("Digital VAX");
case EM_CRIS: return strdup ("Axis Communications 32-bit embedded processor");
case EM_JAVELIN: return strdup ("Infineon Technologies 32-bit embedded processor");
case EM_FIREPATH: return strdup ("Element 14 64-bit DSP Processor");
case EM_ZSP: return strdup ("LSI Logic 16-bit DSP Processor");
case EM_MMIX: return strdup ("Donald Knuth's educational 64-bit processor");
case EM_HUANY: return strdup ("Harvard University machine-independent object files");
case EM_PRISM: return strdup ("SiTera Prism");
case EM_AVR: return strdup ("Atmel AVR 8-bit microcontroller");
case EM_FR30: return strdup ("Fujitsu FR30");
case EM_D10V: return strdup ("Mitsubishi D10V");
case EM_D30V: return strdup ("Mitsubishi D30V");
case EM_V850: return strdup ("NEC v850");
case EM_M32R: return strdup ("Mitsubishi M32R");
case EM_MN10300: return strdup ("Matsushita MN10300");
case EM_MN10200: return strdup ("Matsushita MN10200");
case EM_PJ: return strdup ("picoJava");
case EM_OPENRISC: return strdup ("OpenRISC 32-bit embedded processor");
case EM_ARC_A5: return strdup ("ARC Cores Tangent-A5");
case EM_XTENSA: return strdup ("Tensilica Xtensa Architecture");
case EM_AARCH64: return strdup ("ARM aarch64");
case EM_PROPELLER: return strdup ("Parallax Propeller");
case EM_MICROBLAZE: return strdup ("Xilinx MicroBlaze");
case EM_RISCV: return strdup ("RISC V");
case EM_VIDEOCORE3: return strdup ("VideoCore III");
case EM_VIDEOCORE4: return strdup ("VideoCore IV");
default: return r_str_newf ("<unknown>: 0x%x", bin->ehdr.e_machine);
}
}
char* Elf_(r_bin_elf_get_file_type)(ELFOBJ *bin) {
ut32 e_type;
if (!bin) {
return NULL;
}
e_type = (ut32)bin->ehdr.e_type; // cast to avoid warn in iphone-gcc, must be ut16
switch (e_type) {
case ET_NONE: return strdup ("NONE (None)");
case ET_REL: return strdup ("REL (Relocatable file)");
case ET_EXEC: return strdup ("EXEC (Executable file)");
case ET_DYN: return strdup ("DYN (Shared object file)");
case ET_CORE: return strdup ("CORE (Core file)");
}
if ((e_type >= ET_LOPROC) && (e_type <= ET_HIPROC)) {
return r_str_newf ("Processor Specific: %x", e_type);
}
if ((e_type >= ET_LOOS) && (e_type <= ET_HIOS)) {
return r_str_newf ("OS Specific: %x", e_type);
}
return r_str_newf ("<unknown>: %x", e_type);
}
char* Elf_(r_bin_elf_get_elf_class)(ELFOBJ *bin) {
switch (bin->ehdr.e_ident[EI_CLASS]) {
case ELFCLASSNONE: return strdup ("none");
case ELFCLASS32: return strdup ("ELF32");
case ELFCLASS64: return strdup ("ELF64");
default: return r_str_newf ("<unknown: %x>", bin->ehdr.e_ident[EI_CLASS]);
}
}
int Elf_(r_bin_elf_get_bits)(ELFOBJ *bin) {
/* Hack for ARCompact */
if (bin->ehdr.e_machine == EM_ARC_A5) {
return 16;
}
/* Hack for Ps2 */
if (bin->phdr && bin->ehdr.e_machine == EM_MIPS) {
const ut32 mipsType = bin->ehdr.e_flags & EF_MIPS_ARCH;
if (bin->ehdr.e_type == ET_EXEC) {
int i;
bool haveInterp = false;
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_INTERP) {
haveInterp = true;
}
}
if (!haveInterp && mipsType == EF_MIPS_ARCH_3) {
// Playstation2 Hack
return 64;
}
}
// TODO: show this specific asm.cpu somewhere in bininfo (mips1, mips2, mips3, mips32r2, ...)
switch (mipsType) {
case EF_MIPS_ARCH_1:
case EF_MIPS_ARCH_2:
case EF_MIPS_ARCH_3:
case EF_MIPS_ARCH_4:
case EF_MIPS_ARCH_5:
case EF_MIPS_ARCH_32:
return 32;
case EF_MIPS_ARCH_64:
return 64;
case EF_MIPS_ARCH_32R2:
return 32;
case EF_MIPS_ARCH_64R2:
return 64;
break;
}
return 32;
}
/* Hack for Thumb */
if (bin->ehdr.e_machine == EM_ARM) {
if (bin->ehdr.e_type != ET_EXEC) {
struct r_bin_elf_symbol_t *symbol;
if ((symbol = Elf_(r_bin_elf_get_symbols) (bin))) {
int i = 0;
for (i = 0; !symbol[i].last; i++) {
ut64 paddr = symbol[i].offset;
if (paddr & 1) {
return 16;
}
}
}
}
{
ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin);
if (entry & 1) {
return 16;
}
}
}
switch (bin->ehdr.e_ident[EI_CLASS]) {
case ELFCLASS32: return 32;
case ELFCLASS64: return 64;
case ELFCLASSNONE:
default: return 32; // defaults
}
}
static inline int noodle(ELFOBJ *bin, const char *s) {
const ut8 *p = bin->b->buf;
if (bin->b->length > 64) {
p += bin->b->length - 64;
} else {
return 0;
}
return r_mem_mem (p, 64, (const ut8 *)s, strlen (s)) != NULL;
}
static inline int needle(ELFOBJ *bin, const char *s) {
if (bin->shstrtab) {
ut32 len = bin->shstrtab_size;
if (len > 4096) {
len = 4096; // avoid slow loading .. can be buggy?
}
return r_mem_mem ((const ut8*)bin->shstrtab, len,
(const ut8*)s, strlen (s)) != NULL;
}
return 0;
}
// TODO: must return const char * all those strings must be const char os[LINUX] or so
char* Elf_(r_bin_elf_get_osabi_name)(ELFOBJ *bin) {
switch (bin->ehdr.e_ident[EI_OSABI]) {
case ELFOSABI_LINUX: return strdup("linux");
case ELFOSABI_SOLARIS: return strdup("solaris");
case ELFOSABI_FREEBSD: return strdup("freebsd");
case ELFOSABI_HPUX: return strdup("hpux");
}
/* Hack to identify OS */
if (needle (bin, "openbsd")) return strdup ("openbsd");
if (needle (bin, "netbsd")) return strdup ("netbsd");
if (needle (bin, "freebsd")) return strdup ("freebsd");
if (noodle (bin, "BEOS:APP_VERSION")) return strdup ("beos");
if (needle (bin, "GNU")) return strdup ("linux");
return strdup ("linux");
}
ut8 *Elf_(r_bin_elf_grab_regstate)(ELFOBJ *bin, int *len) {
if (bin->phdr) {
int i;
int num = bin->ehdr.e_phnum;
for (i = 0; i < num; i++) {
if (bin->phdr[i].p_type != PT_NOTE) {
continue;
}
int bits = Elf_(r_bin_elf_get_bits)(bin);
int regdelta = (bits == 64)? 0x84: 0x40; // x64 vs x32
int regsize = 160; // for x86-64
ut8 *buf = malloc (regsize);
if (r_buf_read_at (bin->b, bin->phdr[i].p_offset + regdelta, buf, regsize) != regsize) {
free (buf);
bprintf ("Cannot read register state from CORE file\n");
return NULL;
}
if (len) {
*len = regsize;
}
return buf;
}
}
bprintf ("Cannot find NOTE section\n");
return NULL;
}
int Elf_(r_bin_elf_is_big_endian)(ELFOBJ *bin) {
return (bin->ehdr.e_ident[EI_DATA] == ELFDATA2MSB);
}
/* XXX Init dt_strtab? */
char *Elf_(r_bin_elf_get_rpath)(ELFOBJ *bin) {
char *ret = NULL;
int j;
if (!bin || !bin->phdr || !bin->dyn_buf || !bin->strtab) {
return NULL;
}
for (j = 0; j< bin->dyn_entries; j++) {
if (bin->dyn_buf[j].d_tag == DT_RPATH || bin->dyn_buf[j].d_tag == DT_RUNPATH) {
if (!(ret = calloc (1, ELF_STRING_LENGTH))) {
perror ("malloc (rpath)");
return NULL;
}
if (bin->dyn_buf[j].d_un.d_val > bin->strtab_size) {
free (ret);
return NULL;
}
strncpy (ret, bin->strtab + bin->dyn_buf[j].d_un.d_val, ELF_STRING_LENGTH);
ret[ELF_STRING_LENGTH - 1] = '\0';
break;
}
}
return ret;
}
static size_t get_relocs_num(ELFOBJ *bin) {
size_t i, size, ret = 0;
/* we need to be careful here, in malformed files the section size might
* not be a multiple of a Rel/Rela size; round up so we allocate enough
* space.
*/
#define NUMENTRIES_ROUNDUP(sectionsize, entrysize) (((sectionsize)+(entrysize)-1)/(entrysize))
if (!bin->g_sections) {
return 0;
}
size = bin->is_rela == DT_REL ? sizeof (Elf_(Rel)) : sizeof (Elf_(Rela));
for (i = 0; !bin->g_sections[i].last; i++) {
if (!strncmp (bin->g_sections[i].name, ".rela.", strlen (".rela."))) {
if (!bin->is_rela) {
size = sizeof (Elf_(Rela));
}
ret += NUMENTRIES_ROUNDUP (bin->g_sections[i].size, size);
} else if (!strncmp (bin->g_sections[i].name, ".rel.", strlen (".rel."))){
if (!bin->is_rela) {
size = sizeof (Elf_(Rel));
}
ret += NUMENTRIES_ROUNDUP (bin->g_sections[i].size, size);
}
}
return ret;
#undef NUMENTRIES_ROUNDUP
}
static int read_reloc(ELFOBJ *bin, RBinElfReloc *r, int is_rela, ut64 offset) {
ut8 *buf = bin->b->buf;
int j = 0;
if (offset + sizeof (Elf_ (Rela)) >
bin->size || offset + sizeof (Elf_(Rela)) < offset) {
return -1;
}
if (is_rela == DT_RELA) {
Elf_(Rela) rela;
#if R_BIN_ELF64
rela.r_offset = READ64 (buf + offset, j)
rela.r_info = READ64 (buf + offset, j)
rela.r_addend = READ64 (buf + offset, j)
#else
rela.r_offset = READ32 (buf + offset, j)
rela.r_info = READ32 (buf + offset, j)
rela.r_addend = READ32 (buf + offset, j)
#endif
r->is_rela = is_rela;
r->offset = rela.r_offset;
r->type = ELF_R_TYPE (rela.r_info);
r->sym = ELF_R_SYM (rela.r_info);
r->last = 0;
r->addend = rela.r_addend;
return sizeof (Elf_(Rela));
} else {
Elf_(Rel) rel;
#if R_BIN_ELF64
rel.r_offset = READ64 (buf + offset, j)
rel.r_info = READ64 (buf + offset, j)
#else
rel.r_offset = READ32 (buf + offset, j)
rel.r_info = READ32 (buf + offset, j)
#endif
r->is_rela = is_rela;
r->offset = rel.r_offset;
r->type = ELF_R_TYPE (rel.r_info);
r->sym = ELF_R_SYM (rel.r_info);
r->last = 0;
return sizeof (Elf_(Rel));
}
}
RBinElfReloc* Elf_(r_bin_elf_get_relocs)(ELFOBJ *bin) {
int res, rel, rela, i, j;
size_t reloc_num = 0;
RBinElfReloc *ret = NULL;
if (!bin || !bin->g_sections) {
return NULL;
}
reloc_num = get_relocs_num (bin);
if (!reloc_num) {
return NULL;
}
bin->reloc_num = reloc_num;
ret = (RBinElfReloc*)calloc ((size_t)reloc_num + 1, sizeof(RBinElfReloc));
if (!ret) {
return NULL;
}
#if DEAD_CODE
ut64 section_text_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".text");
if (section_text_offset == -1) {
section_text_offset = 0;
}
#endif
for (i = 0, rel = 0; !bin->g_sections[i].last && rel < reloc_num ; i++) {
bool is_rela = 0 == strncmp (bin->g_sections[i].name, ".rela.", strlen (".rela."));
bool is_rel = 0 == strncmp (bin->g_sections[i].name, ".rel.", strlen (".rel."));
if (!is_rela && !is_rel) {
continue;
}
for (j = 0; j < bin->g_sections[i].size; j += res) {
if (bin->g_sections[i].size > bin->size) {
break;
}
if (bin->g_sections[i].offset > bin->size) {
break;
}
if (rel >= reloc_num) {
bprintf ("Internal error: ELF relocation buffer too small,"
"please file a bug report.");
break;
}
if (!bin->is_rela) {
rela = is_rela? DT_RELA : DT_REL;
} else {
rela = bin->is_rela;
}
res = read_reloc (bin, &ret[rel], rela, bin->g_sections[i].offset + j);
if (j + res > bin->g_sections[i].size) {
bprintf ("Warning: malformed file, relocation entry #%u is partially beyond the end of section %u.\n", rel, i);
}
if (bin->ehdr.e_type == ET_REL) {
if (bin->g_sections[i].info < bin->ehdr.e_shnum && bin->shdr) {
ret[rel].rva = bin->shdr[bin->g_sections[i].info].sh_offset + ret[rel].offset;
ret[rel].rva = Elf_(r_bin_elf_p2v) (bin, ret[rel].rva);
} else {
ret[rel].rva = ret[rel].offset;
}
} else {
ret[rel].rva = ret[rel].offset;
ret[rel].offset = Elf_(r_bin_elf_v2p) (bin, ret[rel].offset);
}
ret[rel].last = 0;
if (res < 0) {
break;
}
rel++;
}
}
ret[reloc_num].last = 1;
return ret;
}
RBinElfLib* Elf_(r_bin_elf_get_libs)(ELFOBJ *bin) {
RBinElfLib *ret = NULL;
int j, k;
if (!bin || !bin->phdr || !bin->dyn_buf || !bin->strtab || *(bin->strtab+1) == '0') {
return NULL;
}
for (j = 0, k = 0; j < bin->dyn_entries; j++)
if (bin->dyn_buf[j].d_tag == DT_NEEDED) {
RBinElfLib *r = realloc (ret, (k + 1) * sizeof (RBinElfLib));
if (!r) {
perror ("realloc (libs)");
free (ret);
return NULL;
}
ret = r;
if (bin->dyn_buf[j].d_un.d_val > bin->strtab_size) {
free (ret);
return NULL;
}
strncpy (ret[k].name, bin->strtab + bin->dyn_buf[j].d_un.d_val, ELF_STRING_LENGTH);
ret[k].name[ELF_STRING_LENGTH - 1] = '\0';
ret[k].last = 0;
if (ret[k].name[0]) {
k++;
}
}
RBinElfLib *r = realloc (ret, (k + 1) * sizeof (RBinElfLib));
if (!r) {
perror ("realloc (libs)");
free (ret);
return NULL;
}
ret = r;
ret[k].last = 1;
return ret;
}
static RBinElfSection* get_sections_from_phdr(ELFOBJ *bin) {
RBinElfSection *ret;
int i, num_sections = 0;
ut64 reldyn = 0, relava = 0, pltgotva = 0, relva = 0;
ut64 reldynsz = 0, relasz = 0, pltgotsz = 0;
if (!bin || !bin->phdr || !bin->ehdr.e_phnum)
return NULL;
for (i = 0; i < bin->dyn_entries; i++) {
switch (bin->dyn_buf[i].d_tag) {
case DT_REL:
reldyn = bin->dyn_buf[i].d_un.d_ptr;
num_sections++;
break;
case DT_RELA:
relva = bin->dyn_buf[i].d_un.d_ptr;
num_sections++;
break;
case DT_RELSZ:
reldynsz = bin->dyn_buf[i].d_un.d_val;
break;
case DT_RELASZ:
relasz = bin->dyn_buf[i].d_un.d_val;
break;
case DT_PLTGOT:
pltgotva = bin->dyn_buf[i].d_un.d_ptr;
num_sections++;
break;
case DT_PLTRELSZ:
pltgotsz = bin->dyn_buf[i].d_un.d_val;
break;
case DT_JMPREL:
relava = bin->dyn_buf[i].d_un.d_ptr;
num_sections++;
break;
default: break;
}
}
ret = calloc (num_sections + 1, sizeof(RBinElfSection));
if (!ret) {
return NULL;
}
i = 0;
if (reldyn) {
ret[i].offset = Elf_(r_bin_elf_v2p) (bin, reldyn);
ret[i].rva = reldyn;
ret[i].size = reldynsz;
strcpy (ret[i].name, ".rel.dyn");
ret[i].last = 0;
i++;
}
if (relava) {
ret[i].offset = Elf_(r_bin_elf_v2p) (bin, relava);
ret[i].rva = relava;
ret[i].size = pltgotsz;
strcpy (ret[i].name, ".rela.plt");
ret[i].last = 0;
i++;
}
if (relva) {
ret[i].offset = Elf_(r_bin_elf_v2p) (bin, relva);
ret[i].rva = relva;
ret[i].size = relasz;
strcpy (ret[i].name, ".rel.plt");
ret[i].last = 0;
i++;
}
if (pltgotva) {
ret[i].offset = Elf_(r_bin_elf_v2p) (bin, pltgotva);
ret[i].rva = pltgotva;
ret[i].size = pltgotsz;
strcpy (ret[i].name, ".got.plt");
ret[i].last = 0;
i++;
}
ret[i].last = 1;
return ret;
}
RBinElfSection* Elf_(r_bin_elf_get_sections)(ELFOBJ *bin) {
RBinElfSection *ret = NULL;
char unknown_s[20], invalid_s[20];
int i, nidx, unknown_c=0, invalid_c=0;
if (!bin) {
return NULL;
}
if (bin->g_sections) {
return bin->g_sections;
}
if (!bin->shdr) {
//we don't give up search in phdr section
return get_sections_from_phdr (bin);
}
if (!(ret = calloc ((bin->ehdr.e_shnum + 1), sizeof (RBinElfSection)))) {
return NULL;
}
for (i = 0; i < bin->ehdr.e_shnum; i++) {
ret[i].offset = bin->shdr[i].sh_offset;
ret[i].size = bin->shdr[i].sh_size;
ret[i].align = bin->shdr[i].sh_addralign;
ret[i].flags = bin->shdr[i].sh_flags;
ret[i].link = bin->shdr[i].sh_link;
ret[i].info = bin->shdr[i].sh_info;
ret[i].type = bin->shdr[i].sh_type;
if (bin->ehdr.e_type == ET_REL) {
ret[i].rva = bin->baddr + bin->shdr[i].sh_offset;
} else {
ret[i].rva = bin->shdr[i].sh_addr;
}
nidx = bin->shdr[i].sh_name;
#define SHNAME (int)bin->shdr[i].sh_name
#define SHNLEN ELF_STRING_LENGTH - 4
#define SHSIZE (int)bin->shstrtab_size
if (nidx < 0 || !bin->shstrtab_section || !bin->shstrtab_size || nidx > bin->shstrtab_size) {
snprintf (invalid_s, sizeof (invalid_s) - 4, "invalid%d", invalid_c);
strncpy (ret[i].name, invalid_s, SHNLEN);
invalid_c++;
} else {
if (bin->shstrtab && (SHNAME > 0) && (SHNAME < SHSIZE)) {
strncpy (ret[i].name, &bin->shstrtab[SHNAME], SHNLEN);
} else {
if (bin->shdr[i].sh_type == SHT_NULL) {
//to follow the same behaviour as readelf
strncpy (ret[i].name, "", sizeof (ret[i].name) - 4);
} else {
snprintf (unknown_s, sizeof (unknown_s)-4, "unknown%d", unknown_c);
strncpy (ret[i].name, unknown_s, sizeof (ret[i].name)-4);
unknown_c++;
}
}
}
ret[i].name[ELF_STRING_LENGTH-2] = '\0';
ret[i].last = 0;
}
ret[i].last = 1;
return ret;
}
static void fill_symbol_bind_and_type (struct r_bin_elf_symbol_t *ret, Elf_(Sym) *sym) {
#define s_bind(x) ret->bind = x
#define s_type(x) ret->type = x
switch (ELF_ST_BIND(sym->st_info)) {
case STB_LOCAL: s_bind ("LOCAL"); break;
case STB_GLOBAL: s_bind ("GLOBAL"); break;
case STB_WEAK: s_bind ("WEAK"); break;
case STB_NUM: s_bind ("NUM"); break;
case STB_LOOS: s_bind ("LOOS"); break;
case STB_HIOS: s_bind ("HIOS"); break;
case STB_LOPROC: s_bind ("LOPROC"); break;
case STB_HIPROC: s_bind ("HIPROC"); break;
default: s_bind ("UNKNOWN");
}
switch (ELF_ST_TYPE (sym->st_info)) {
case STT_NOTYPE: s_type ("NOTYPE"); break;
case STT_OBJECT: s_type ("OBJECT"); break;
case STT_FUNC: s_type ("FUNC"); break;
case STT_SECTION: s_type ("SECTION"); break;
case STT_FILE: s_type ("FILE"); break;
case STT_COMMON: s_type ("COMMON"); break;
case STT_TLS: s_type ("TLS"); break;
case STT_NUM: s_type ("NUM"); break;
case STT_LOOS: s_type ("LOOS"); break;
case STT_HIOS: s_type ("HIOS"); break;
case STT_LOPROC: s_type ("LOPROC"); break;
case STT_HIPROC: s_type ("HIPROC"); break;
default: s_type ("UNKNOWN");
}
}
static RBinElfSymbol* get_symbols_from_phdr(ELFOBJ *bin, int type) {
Elf_(Sym) *sym = NULL;
Elf_(Addr) addr_sym_table = 0;
ut8 s[sizeof (Elf_(Sym))] = {0};
RBinElfSymbol *ret = NULL;
int i, j, r, tsize, nsym, ret_ctr;
ut64 toffset = 0, tmp_offset;
ut32 size, sym_size = 0;
if (!bin || !bin->phdr || !bin->ehdr.e_phnum) {
return NULL;
}
for (j = 0; j < bin->dyn_entries; j++) {
switch (bin->dyn_buf[j].d_tag) {
case (DT_SYMTAB):
addr_sym_table = Elf_(r_bin_elf_v2p) (bin, bin->dyn_buf[j].d_un.d_ptr);
break;
case (DT_SYMENT):
sym_size = bin->dyn_buf[j].d_un.d_val;
break;
default:
break;
}
}
if (!addr_sym_table) {
return NULL;
}
if (!sym_size) {
return NULL;
}
//since ELF doesn't specify the symbol table size we may read until the end of the buffer
nsym = (bin->size - addr_sym_table) / sym_size;
if (!UT32_MUL (&size, nsym, sizeof (Elf_ (Sym)))) {
goto beach;
}
if (size < 1) {
goto beach;
}
if (addr_sym_table > bin->size || addr_sym_table + size > bin->size) {
goto beach;
}
if (nsym < 1) {
return NULL;
}
// we reserve room for 4096 and grow as needed.
size_t capacity1 = 4096;
size_t capacity2 = 4096;
sym = (Elf_(Sym)*) calloc (capacity1, sym_size);
ret = (RBinElfSymbol *) calloc (capacity2, sizeof (struct r_bin_elf_symbol_t));
if (!sym || !ret) {
goto beach;
}
for (i = 1, ret_ctr = 0; i < nsym; i++) {
if (i >= capacity1) { // maybe grow
// You take what you want, but you eat what you take.
Elf_(Sym)* temp_sym = (Elf_(Sym)*) realloc(sym, (capacity1 * GROWTH_FACTOR) * sym_size);
if (!temp_sym) {
goto beach;
}
sym = temp_sym;
capacity1 *= GROWTH_FACTOR;
}
if (ret_ctr >= capacity2) { // maybe grow
RBinElfSymbol *temp_ret = realloc (ret, capacity2 * GROWTH_FACTOR * sizeof (struct r_bin_elf_symbol_t));
if (!temp_ret) {
goto beach;
}
ret = temp_ret;
capacity2 *= GROWTH_FACTOR;
}
// read in one entry
r = r_buf_read_at (bin->b, addr_sym_table + i * sizeof (Elf_ (Sym)), s, sizeof (Elf_ (Sym)));
if (r < 1) {
goto beach;
}
int j = 0;
#if R_BIN_ELF64
sym[i].st_name = READ32 (s, j);
sym[i].st_info = READ8 (s, j);
sym[i].st_other = READ8 (s, j);
sym[i].st_shndx = READ16 (s, j);
sym[i].st_value = READ64 (s, j);
sym[i].st_size = READ64 (s, j);
#else
sym[i].st_name = READ32 (s, j);
sym[i].st_value = READ32 (s, j);
sym[i].st_size = READ32 (s, j);
sym[i].st_info = READ8 (s, j);
sym[i].st_other = READ8 (s, j);
sym[i].st_shndx = READ16 (s, j);
#endif
// zero symbol is always empty
// Examine entry and maybe store
if (type == R_BIN_ELF_IMPORTS && sym[i].st_shndx == STN_UNDEF) {
if (sym[i].st_value) {
toffset = sym[i].st_value;
} else if ((toffset = get_import_addr (bin, i)) == -1){
toffset = 0;
}
tsize = 16;
} else if (type == R_BIN_ELF_SYMBOLS &&
sym[i].st_shndx != STN_UNDEF &&
ELF_ST_TYPE (sym[i].st_info) != STT_SECTION &&
ELF_ST_TYPE (sym[i].st_info) != STT_FILE) {
tsize = sym[i].st_size;
toffset = (ut64) sym[i].st_value;
} else {
continue;
}
tmp_offset = Elf_(r_bin_elf_v2p) (bin, toffset);
if (tmp_offset > bin->size) {
goto done;
}
if (sym[i].st_name + 2 > bin->strtab_size) {
// Since we are reading beyond the symbol table what's happening
// is that some entry is trying to dereference the strtab beyond its capacity
// is not a symbol so is the end
goto done;
}
ret[ret_ctr].offset = tmp_offset;
ret[ret_ctr].size = tsize;
{
int rest = ELF_STRING_LENGTH - 1;
int st_name = sym[i].st_name;
int maxsize = R_MIN (bin->size, bin->strtab_size);
if (st_name < 0 || st_name >= maxsize) {
ret[ret_ctr].name[0] = 0;
} else {
const int len = __strnlen (bin->strtab + st_name, rest);
memcpy (ret[ret_ctr].name, &bin->strtab[st_name], len);
}
}
ret[ret_ctr].ordinal = i;
ret[ret_ctr].in_shdr = false;
ret[ret_ctr].name[ELF_STRING_LENGTH - 2] = '\0';
fill_symbol_bind_and_type (&ret[ret_ctr], &sym[i]);
ret[ret_ctr].last = 0;
ret_ctr++;
}
done:
ret[ret_ctr].last = 1;
// Size everything down to only what is used
{
nsym = i > 0 ? i : 1;
Elf_ (Sym) * temp_sym = (Elf_ (Sym)*) realloc (sym, (nsym * GROWTH_FACTOR) * sym_size);
if (!temp_sym) {
goto beach;
}
sym = temp_sym;
}
{
ret_ctr = ret_ctr > 0 ? ret_ctr : 1;
RBinElfSymbol *p = (RBinElfSymbol *) realloc (ret, (ret_ctr + 1) * sizeof (RBinElfSymbol));
if (!p) {
goto beach;
}
ret = p;
}
if (type == R_BIN_ELF_IMPORTS && !bin->imports_by_ord_size) {
bin->imports_by_ord_size = ret_ctr + 1;
if (ret_ctr > 0) {
bin->imports_by_ord = (RBinImport * *) calloc (ret_ctr + 1, sizeof (RBinImport*));
} else {
bin->imports_by_ord = NULL;
}
} else if (type == R_BIN_ELF_SYMBOLS && !bin->symbols_by_ord_size && ret_ctr) {
bin->symbols_by_ord_size = ret_ctr + 1;
if (ret_ctr > 0) {
bin->symbols_by_ord = (RBinSymbol * *) calloc (ret_ctr + 1, sizeof (RBinSymbol*));
}else {
bin->symbols_by_ord = NULL;
}
}
free (sym);
return ret;
beach:
free (sym);
free (ret);
return NULL;
}
static RBinElfSymbol *Elf_(r_bin_elf_get_phdr_symbols)(ELFOBJ *bin) {
if (!bin) {
return NULL;
}
if (bin->phdr_symbols) {
return bin->phdr_symbols;
}
bin->phdr_symbols = get_symbols_from_phdr (bin, R_BIN_ELF_SYMBOLS);
return bin->phdr_symbols;
}
static RBinElfSymbol *Elf_(r_bin_elf_get_phdr_imports)(ELFOBJ *bin) {
if (!bin) {
return NULL;
}
if (bin->phdr_imports) {
return bin->phdr_imports;
}
bin->phdr_imports = get_symbols_from_phdr (bin, R_BIN_ELF_IMPORTS);
return bin->phdr_imports;
}
static int Elf_(fix_symbols)(ELFOBJ *bin, int nsym, int type, RBinElfSymbol **sym) {
int count = 0;
RBinElfSymbol *ret = *sym;
RBinElfSymbol *phdr_symbols = (type == R_BIN_ELF_SYMBOLS)
? Elf_(r_bin_elf_get_phdr_symbols) (bin)
: Elf_(r_bin_elf_get_phdr_imports) (bin);
RBinElfSymbol *tmp, *p;
if (phdr_symbols) {
RBinElfSymbol *d = ret;
while (!d->last) {
/* find match in phdr */
p = phdr_symbols;
while (!p->last) {
if (p->offset && d->offset == p->offset) {
p->in_shdr = true;
if (*p->name && strcmp (d->name, p->name)) {
strcpy (d->name, p->name);
}
}
p++;
}
d++;
}
p = phdr_symbols;
while (!p->last) {
if (!p->in_shdr) {
count++;
}
p++;
}
/*Take those symbols that are not present in the shdr but yes in phdr*/
/*This should only should happen with fucked up binaries*/
if (count > 0) {
/*what happens if a shdr says it has only one symbol? we should look anyway into phdr*/
tmp = (RBinElfSymbol*)realloc (ret, (nsym + count + 1) * sizeof (RBinElfSymbol));
if (!tmp) {
return -1;
}
ret = tmp;
ret[nsym--].last = 0;
p = phdr_symbols;
while (!p->last) {
if (!p->in_shdr) {
memcpy (&ret[++nsym], p, sizeof (RBinElfSymbol));
}
p++;
}
ret[nsym + 1].last = 1;
}
*sym = ret;
return nsym + 1;
}
return nsym;
}
static RBinElfSymbol* Elf_(_r_bin_elf_get_symbols_imports)(ELFOBJ *bin, int type) {
ut32 shdr_size;
int tsize, nsym, ret_ctr = 0, i, j, r, k, newsize;
ut64 toffset;
ut32 size = 0;
RBinElfSymbol *ret = NULL;
Elf_(Shdr) *strtab_section = NULL;
Elf_(Sym) *sym = NULL;
ut8 s[sizeof (Elf_(Sym))] = { 0 };
char *strtab = NULL;
if (!bin || !bin->shdr || !bin->ehdr.e_shnum || bin->ehdr.e_shnum == 0xffff) {
return (type == R_BIN_ELF_SYMBOLS)
? Elf_(r_bin_elf_get_phdr_symbols) (bin)
: Elf_(r_bin_elf_get_phdr_imports) (bin);
}
if (!UT32_MUL (&shdr_size, bin->ehdr.e_shnum, sizeof (Elf_(Shdr)))) {
return false;
}
if (shdr_size + 8 > bin->size) {
return false;
}
for (i = 0; i < bin->ehdr.e_shnum; i++) {
if ((type == R_BIN_ELF_IMPORTS && bin->shdr[i].sh_type == (bin->ehdr.e_type == ET_REL ? SHT_SYMTAB : SHT_DYNSYM)) ||
(type == R_BIN_ELF_SYMBOLS && bin->shdr[i].sh_type == (Elf_(r_bin_elf_get_stripped) (bin) ? SHT_DYNSYM : SHT_SYMTAB))) {
if (bin->shdr[i].sh_link < 1) {
/* oops. fix out of range pointers */
continue;
}
// hack to avoid asan cry
if ((bin->shdr[i].sh_link * sizeof(Elf_(Shdr))) >= shdr_size) {
/* oops. fix out of range pointers */
continue;
}
strtab_section = &bin->shdr[bin->shdr[i].sh_link];
if (strtab_section->sh_size > ST32_MAX || strtab_section->sh_size+8 > bin->size) {
bprintf ("size (syms strtab)");
free (ret);
free (strtab);
return NULL;
}
if (!strtab) {
if (!(strtab = (char *)calloc (1, 8 + strtab_section->sh_size))) {
bprintf ("malloc (syms strtab)");
goto beach;
}
if (strtab_section->sh_offset > bin->size ||
strtab_section->sh_offset + strtab_section->sh_size > bin->size) {
goto beach;
}
if (r_buf_read_at (bin->b, strtab_section->sh_offset,
(ut8*)strtab, strtab_section->sh_size) == -1) {
bprintf ("Warning: read (syms strtab)\n");
goto beach;
}
}
newsize = 1 + bin->shdr[i].sh_size;
if (newsize < 0 || newsize > bin->size) {
bprintf ("invalid shdr %d size\n", i);
goto beach;
}
nsym = (int)(bin->shdr[i].sh_size / sizeof (Elf_(Sym)));
if (nsym < 0) {
goto beach;
}
if (!(sym = (Elf_(Sym) *)calloc (nsym, sizeof (Elf_(Sym))))) {
bprintf ("calloc (syms)");
goto beach;
}
if (!UT32_MUL (&size, nsym, sizeof (Elf_(Sym)))) {
goto beach;
}
if (size < 1 || size > bin->size) {
goto beach;
}
if (bin->shdr[i].sh_offset > bin->size) {
goto beach;
}
if (bin->shdr[i].sh_offset + size > bin->size) {
goto beach;
}
for (j = 0; j < nsym; j++) {
int k = 0;
r = r_buf_read_at (bin->b, bin->shdr[i].sh_offset + j * sizeof (Elf_(Sym)), s, sizeof (Elf_(Sym)));
if (r < 1) {
bprintf ("Warning: read (sym)\n");
goto beach;
}
#if R_BIN_ELF64
sym[j].st_name = READ32 (s, k)
sym[j].st_info = READ8 (s, k)
sym[j].st_other = READ8 (s, k)
sym[j].st_shndx = READ16 (s, k)
sym[j].st_value = READ64 (s, k)
sym[j].st_size = READ64 (s, k)
#else
sym[j].st_name = READ32 (s, k)
sym[j].st_value = READ32 (s, k)
sym[j].st_size = READ32 (s, k)
sym[j].st_info = READ8 (s, k)
sym[j].st_other = READ8 (s, k)
sym[j].st_shndx = READ16 (s, k)
#endif
}
free (ret);
ret = calloc (nsym, sizeof (RBinElfSymbol));
if (!ret) {
bprintf ("Cannot allocate %d symbols\n", nsym);
goto beach;
}
for (k = 1, ret_ctr = 0; k < nsym; k++) {
if (type == R_BIN_ELF_IMPORTS && sym[k].st_shndx == STN_UNDEF) {
if (sym[k].st_value) {
toffset = sym[k].st_value;
} else if ((toffset = get_import_addr (bin, k)) == -1){
toffset = 0;
}
tsize = 16;
} else if (type == R_BIN_ELF_SYMBOLS &&
sym[k].st_shndx != STN_UNDEF &&
ELF_ST_TYPE (sym[k].st_info) != STT_SECTION &&
ELF_ST_TYPE (sym[k].st_info) != STT_FILE) {
//int idx = sym[k].st_shndx;
tsize = sym[k].st_size;
toffset = (ut64)sym[k].st_value;
} else {
continue;
}
if (bin->ehdr.e_type == ET_REL) {
if (sym[k].st_shndx < bin->ehdr.e_shnum)
ret[ret_ctr].offset = sym[k].st_value + bin->shdr[sym[k].st_shndx].sh_offset;
} else {
ret[ret_ctr].offset = Elf_(r_bin_elf_v2p) (bin, toffset);
}
ret[ret_ctr].size = tsize;
if (sym[k].st_name + 2 > strtab_section->sh_size) {
bprintf ("Warning: index out of strtab range\n");
goto beach;
}
{
int rest = ELF_STRING_LENGTH - 1;
int st_name = sym[k].st_name;
int maxsize = R_MIN (bin->b->length, strtab_section->sh_size);
if (st_name < 0 || st_name >= maxsize) {
ret[ret_ctr].name[0] = 0;
} else {
const size_t len = __strnlen (strtab + sym[k].st_name, rest);
memcpy (ret[ret_ctr].name, &strtab[sym[k].st_name], len);
}
}
ret[ret_ctr].ordinal = k;
ret[ret_ctr].name[ELF_STRING_LENGTH - 2] = '\0';
fill_symbol_bind_and_type (&ret[ret_ctr], &sym[k]);
ret[ret_ctr].last = 0;
ret_ctr++;
}
ret[ret_ctr].last = 1; // ugly dirty hack :D
R_FREE (strtab);
R_FREE (sym);
}
}
if (!ret) {
return (type == R_BIN_ELF_SYMBOLS)
? Elf_(r_bin_elf_get_phdr_symbols) (bin)
: Elf_(r_bin_elf_get_phdr_imports) (bin);
}
int max = -1;
RBinElfSymbol *aux = NULL;
nsym = Elf_(fix_symbols) (bin, ret_ctr, type, &ret);
if (nsym == -1) {
goto beach;
}
aux = ret;
while (!aux->last) {
if ((int)aux->ordinal > max) {
max = aux->ordinal;
}
aux++;
}
nsym = max;
if (type == R_BIN_ELF_IMPORTS) {
R_FREE (bin->imports_by_ord);
bin->imports_by_ord_size = nsym + 1;
bin->imports_by_ord = (RBinImport**)calloc (R_MAX (1, nsym + 1), sizeof (RBinImport*));
} else if (type == R_BIN_ELF_SYMBOLS) {
R_FREE (bin->symbols_by_ord);
bin->symbols_by_ord_size = nsym + 1;
bin->symbols_by_ord = (RBinSymbol**)calloc (R_MAX (1, nsym + 1), sizeof (RBinSymbol*));
}
return ret;
beach:
free (ret);
free (sym);
free (strtab);
return NULL;
}
RBinElfSymbol *Elf_(r_bin_elf_get_symbols)(ELFOBJ *bin) {
if (!bin->g_symbols) {
bin->g_symbols = Elf_(_r_bin_elf_get_symbols_imports) (bin, R_BIN_ELF_SYMBOLS);
}
return bin->g_symbols;
}
RBinElfSymbol *Elf_(r_bin_elf_get_imports)(ELFOBJ *bin) {
if (!bin->g_imports) {
bin->g_imports = Elf_(_r_bin_elf_get_symbols_imports) (bin, R_BIN_ELF_IMPORTS);
}
return bin->g_imports;
}
RBinElfField* Elf_(r_bin_elf_get_fields)(ELFOBJ *bin) {
RBinElfField *ret = NULL;
int i = 0, j;
if (!bin || !(ret = calloc ((bin->ehdr.e_phnum + 3 + 1), sizeof (RBinElfField)))) {
return NULL;
}
strncpy (ret[i].name, "ehdr", ELF_STRING_LENGTH);
ret[i].offset = 0;
ret[i++].last = 0;
strncpy (ret[i].name, "shoff", ELF_STRING_LENGTH);
ret[i].offset = bin->ehdr.e_shoff;
ret[i++].last = 0;
strncpy (ret[i].name, "phoff", ELF_STRING_LENGTH);
ret[i].offset = bin->ehdr.e_phoff;
ret[i++].last = 0;
for (j = 0; bin->phdr && j < bin->ehdr.e_phnum; i++, j++) {
snprintf (ret[i].name, ELF_STRING_LENGTH, "phdr_%i", j);
ret[i].offset = bin->phdr[j].p_offset;
ret[i].last = 0;
}
ret[i].last = 1;
return ret;
}
void* Elf_(r_bin_elf_free)(ELFOBJ* bin) {
int i;
if (!bin) {
return NULL;
}
free (bin->phdr);
free (bin->shdr);
free (bin->strtab);
free (bin->dyn_buf);
free (bin->shstrtab);
free (bin->dynstr);
//free (bin->strtab_section);
if (bin->imports_by_ord) {
for (i = 0; i<bin->imports_by_ord_size; i++) {
free (bin->imports_by_ord[i]);
}
free (bin->imports_by_ord);
}
if (bin->symbols_by_ord) {
for (i = 0; i<bin->symbols_by_ord_size; i++) {
free (bin->symbols_by_ord[i]);
}
free (bin->symbols_by_ord);
}
r_buf_free (bin->b);
if (bin->g_symbols != bin->phdr_symbols) {
R_FREE (bin->phdr_symbols);
}
if (bin->g_imports != bin->phdr_imports) {
R_FREE (bin->phdr_imports);
}
R_FREE (bin->g_sections);
R_FREE (bin->g_symbols);
R_FREE (bin->g_imports);
free (bin);
return NULL;
}
ELFOBJ* Elf_(r_bin_elf_new)(const char* file, bool verbose) {
ut8 *buf;
int size;
ELFOBJ *bin = R_NEW0 (ELFOBJ);
if (!bin) {
return NULL;
}
memset (bin, 0, sizeof (ELFOBJ));
bin->file = file;
if (!(buf = (ut8*)r_file_slurp (file, &size))) {
return Elf_(r_bin_elf_free) (bin);
}
bin->size = size;
bin->verbose = verbose;
bin->b = r_buf_new ();
if (!r_buf_set_bytes (bin->b, buf, bin->size)) {
free (buf);
return Elf_(r_bin_elf_free) (bin);
}
if (!elf_init (bin)) {
free (buf);
return Elf_(r_bin_elf_free) (bin);
}
free (buf);
return bin;
}
ELFOBJ* Elf_(r_bin_elf_new_buf)(RBuffer *buf, bool verbose) {
ELFOBJ *bin = R_NEW0 (ELFOBJ);
bin->kv = sdb_new0 ();
bin->b = r_buf_new ();
bin->size = (ut32)buf->length;
bin->verbose = verbose;
if (!r_buf_set_bytes (bin->b, buf->buf, buf->length)) {
return Elf_(r_bin_elf_free) (bin);
}
if (!elf_init (bin)) {
return Elf_(r_bin_elf_free) (bin);
}
return bin;
}
static int is_in_pphdr (Elf_(Phdr) *p, ut64 addr) {
return addr >= p->p_offset && addr < p->p_offset + p->p_memsz;
}
static int is_in_vphdr (Elf_(Phdr) *p, ut64 addr) {
return addr >= p->p_vaddr && addr < p->p_vaddr + p->p_memsz;
}
/* converts a physical address to the virtual address, looking
* at the program headers in the binary bin */
ut64 Elf_(r_bin_elf_p2v) (ELFOBJ *bin, ut64 paddr) {
int i;
if (!bin) return 0;
if (!bin->phdr) {
if (bin->ehdr.e_type == ET_REL) {
return bin->baddr + paddr;
}
return paddr;
}
for (i = 0; i < bin->ehdr.e_phnum; ++i) {
Elf_(Phdr) *p = &bin->phdr[i];
if (!p) {
break;
}
if (p->p_type == PT_LOAD && is_in_pphdr (p, paddr)) {
if (!p->p_vaddr && !p->p_offset) {
continue;
}
return p->p_vaddr + paddr - p->p_offset;
}
}
return paddr;
}
/* converts a virtual address to the relative physical address, looking
* at the program headers in the binary bin */
ut64 Elf_(r_bin_elf_v2p) (ELFOBJ *bin, ut64 vaddr) {
int i;
if (!bin) {
return 0;
}
if (!bin->phdr) {
if (bin->ehdr.e_type == ET_REL) {
return vaddr - bin->baddr;
}
return vaddr;
}
for (i = 0; i < bin->ehdr.e_phnum; ++i) {
Elf_(Phdr) *p = &bin->phdr[i];
if (!p) {
break;
}
if (p->p_type == PT_LOAD && is_in_vphdr (p, vaddr)) {
if (!p->p_offset && !p->p_vaddr) {
continue;
}
return p->p_offset + vaddr - p->p_vaddr;
}
}
return vaddr;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2890_0 |
crossvul-cpp_data_good_5240_0 | /**
* File: TGA Input
*
* Read TGA images.
*/
#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"
/*
Function: gdImageCreateFromTga
Creates a gdImage from a TGA file
Parameters:
infile - Pointer to TGA binary file
*/
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;
}
/*
Function: gdImageCreateFromTgaPtr
*/
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;
}
/*
Function: gdImageCreateFromTgaCtx
Creates a gdImage from a gdIOCtx referencing a TGA binary file.
Parameters:
ctx - Pointer to a gdIOCtx structure
*/
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;
int* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int encoded_pixels;
int rle_size;
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 = (int*) gdMalloc(image_block_size * sizeof(int));
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;
}
rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx);
if (rle_size <= 0) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < rle_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
|| buffer_caret + pixel_block_size > rle_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 * sizeof(int));
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
|| buffer_caret + (encoded_pixels * pixel_block_size) > rle_size) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size * sizeof(int));
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_5240_0 |
crossvul-cpp_data_good_210_2 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre
* Copyright (c) Telecom ParisTech 2000-2012
* All rights reserved
*
* This file is part of GPAC / ISO Media File Format sub-project
*
* GPAC is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GPAC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <gpac/internal/isomedia_dev.h>
#include <gpac/utf.h>
#include <gpac/network.h>
#include <gpac/color.h>
#include <gpac/avparse.h>
#include <time.h>
#ifndef GPAC_DISABLE_ISOM_DUMP
static void dump_data(FILE *trace, char *data, u32 dataLength)
{
u32 i;
fprintf(trace, "data:application/octet-string,");
for (i=0; i<dataLength; i++) {
fprintf(trace, "%02X", (unsigned char) data[i]);
}
}
static void dump_data_hex(FILE *trace, char *data, u32 dataLength)
{
u32 i;
fprintf(trace, "0x");
for (i=0; i<dataLength; i++) {
fprintf(trace, "%02X", (unsigned char) data[i]);
}
}
static void dump_data_attribute(FILE *trace, char *name, char *data, u32 data_size)
{
u32 i;
if (!data || !data_size) {
fprintf(trace, "%s=\"\"", name);
return;
}
fprintf(trace, "%s=\"0x", name);
for (i=0; i<data_size; i++) fprintf(trace, "%02X", (unsigned char) data[i]);
fprintf(trace, "\" ");
}
static void dump_data_string(FILE *trace, char *data, u32 dataLength)
{
u32 i;
for (i=0; i<dataLength; i++) {
switch ((unsigned char) data[i]) {
case '\'':
fprintf(trace, "'");
break;
case '\"':
fprintf(trace, """);
break;
case '&':
fprintf(trace, "&");
break;
case '>':
fprintf(trace, ">");
break;
case '<':
fprintf(trace, "<");
break;
default:
fprintf(trace, "%c", (u8) data[i]);
break;
}
}
}
GF_Err gf_isom_box_dump(void *ptr, FILE * trace)
{
return gf_isom_box_dump_ex(ptr, trace, 0);
}
GF_Err gf_isom_box_array_dump(GF_List *list, FILE * trace)
{
u32 i;
GF_Box *a;
if (!list) return GF_OK;
i=0;
while ((a = (GF_Box *)gf_list_enum(list, &i))) {
gf_isom_box_dump(a, trace);
}
return GF_OK;
}
extern Bool use_dump_mode;
GF_EXPORT
GF_Err gf_isom_dump(GF_ISOFile *mov, FILE * trace)
{
u32 i;
GF_Box *box;
if (!mov || !trace) return GF_BAD_PARAM;
use_dump_mode = mov->dump_mode_alloc;
fprintf(trace, "<!--MP4Box dump trace-->\n");
fprintf(trace, "<IsoMediaFile xmlns=\"urn:mpeg:isobmff:schema:file:2016\" Name=\"%s\">\n", mov->fileName);
i=0;
while ((box = (GF_Box *)gf_list_enum(mov->TopBoxes, &i))) {
if (box->type==GF_ISOM_BOX_TYPE_UNKNOWN) {
fprintf(trace, "<!--WARNING: Unknown Top-level Box Found -->\n");
} else if (box->type==GF_ISOM_BOX_TYPE_UUID) {
} else if (!gf_isom_box_is_file_level(box)) {
fprintf(trace, "<!--ERROR: Invalid Top-level Box Found (\"%s\")-->\n", gf_4cc_to_str(box->type));
}
gf_isom_box_dump(box, trace);
}
fprintf(trace, "</IsoMediaFile>\n");
return GF_OK;
}
GF_Err reftype_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_TrackReferenceTypeBox *p = (GF_TrackReferenceTypeBox *)a;
if (!p->reference_type) return GF_OK;
p->type = p->reference_type;
gf_isom_box_dump_start(a, "TrackReferenceTypeBox", trace);
fprintf(trace, ">\n");
for (i=0; i<p->trackIDCount; i++) {
fprintf(trace, "<TrackReferenceEntry TrackID=\"%d\"/>\n", p->trackIDs[i]);
}
if (!p->size)
fprintf(trace, "<TrackReferenceEntry TrackID=\"\"/>\n");
gf_isom_box_dump_done("TrackReferenceTypeBox", a, trace);
p->type = GF_ISOM_BOX_TYPE_REFT;
return GF_OK;
}
GF_Err ireftype_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_ItemReferenceTypeBox *p = (GF_ItemReferenceTypeBox *)a;
if (!p->reference_type) return GF_OK;
p->type = p->reference_type;
gf_isom_box_dump_start(a, "ItemReferenceBox", trace);
fprintf(trace, "from_item_id=\"%d\">\n", p->from_item_id);
for (i = 0; i < p->reference_count; i++) {
fprintf(trace, "<ItemReferenceBoxEntry ItemID=\"%d\"/>\n", p->to_item_IDs[i]);
}
if (!p->size)
fprintf(trace, "<ItemReferenceBoxEntry ItemID=\"\"/>\n");
gf_isom_box_dump_done("ItemReferenceBox", a, trace);
p->type = GF_ISOM_BOX_TYPE_REFI;
return GF_OK;
}
GF_Err free_dump(GF_Box *a, FILE * trace)
{
GF_FreeSpaceBox *p = (GF_FreeSpaceBox *)a;
gf_isom_box_dump_start(a, (a->type==GF_ISOM_BOX_TYPE_FREE) ? "FreeSpaceBox" : "SkipBox", trace);
fprintf(trace, "dataSize=\"%d\">\n", p->dataSize);
gf_isom_box_dump_done( (a->type==GF_ISOM_BOX_TYPE_FREE) ? "FreeSpaceBox" : "SkipBox", a, trace);
return GF_OK;
}
GF_Err mdat_dump(GF_Box *a, FILE * trace)
{
GF_MediaDataBox *p;
const char *name = (a->type==GF_ISOM_BOX_TYPE_IDAT ? "ItemDataBox" : "MediaDataBox");
p = (GF_MediaDataBox *)a;
gf_isom_box_dump_start(a, name, trace);
fprintf(trace, "dataSize=\""LLD"\">\n", LLD_CAST p->dataSize);
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
GF_Err moov_dump(GF_Box *a, FILE * trace)
{
GF_MovieBox *p;
p = (GF_MovieBox *)a;
gf_isom_box_dump_start(a, "MovieBox", trace);
fprintf(trace, ">\n");
if (p->iods) gf_isom_box_dump(p->iods, trace);
if (p->meta) gf_isom_box_dump(p->meta, trace);
//dump only if size
if (p->size)
gf_isom_box_dump_ex(p->mvhd, trace,GF_ISOM_BOX_TYPE_MVHD);
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
if (p->mvex) gf_isom_box_dump(p->mvex, trace);
#endif
gf_isom_box_array_dump(p->trackList, trace);
if (p->udta) gf_isom_box_dump(p->udta, trace);
gf_isom_box_dump_done("MovieBox", a, trace);
return GF_OK;
}
GF_Err mvhd_dump(GF_Box *a, FILE * trace)
{
GF_MovieHeaderBox *p;
p = (GF_MovieHeaderBox *) a;
gf_isom_box_dump_start(a, "MovieHeaderBox", trace);
fprintf(trace, "CreationTime=\""LLD"\" ", LLD_CAST p->creationTime);
fprintf(trace, "ModificationTime=\""LLD"\" ", LLD_CAST p->modificationTime);
fprintf(trace, "TimeScale=\"%d\" ", p->timeScale);
fprintf(trace, "Duration=\""LLD"\" ", LLD_CAST p->duration);
fprintf(trace, "NextTrackID=\"%d\">\n", p->nextTrackID);
gf_isom_box_dump_done("MovieHeaderBox", a, trace);
return GF_OK;
}
GF_Err mdhd_dump(GF_Box *a, FILE * trace)
{
GF_MediaHeaderBox *p;
p = (GF_MediaHeaderBox *)a;
gf_isom_box_dump_start(a, "MediaHeaderBox", trace);
fprintf(trace, "CreationTime=\""LLD"\" ", LLD_CAST p->creationTime);
fprintf(trace, "ModificationTime=\""LLD"\" ", LLD_CAST p->modificationTime);
fprintf(trace, "TimeScale=\"%d\" ", p->timeScale);
fprintf(trace, "Duration=\""LLD"\" ", LLD_CAST p->duration);
fprintf(trace, "LanguageCode=\"%c%c%c\">\n", p->packedLanguage[0], p->packedLanguage[1], p->packedLanguage[2]);
gf_isom_box_dump_done("MediaHeaderBox", a, trace);
return GF_OK;
}
GF_Err vmhd_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "VideoMediaHeaderBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("VideoMediaHeaderBox", a, trace);
return GF_OK;
}
GF_Err smhd_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "SoundMediaHeaderBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("SoundMediaHeaderBox", a, trace);
return GF_OK;
}
GF_Err hmhd_dump(GF_Box *a, FILE * trace)
{
GF_HintMediaHeaderBox *p;
p = (GF_HintMediaHeaderBox *)a;
gf_isom_box_dump_start(a, "HintMediaHeaderBox", trace);
fprintf(trace, "MaximumPDUSize=\"%d\" ", p->maxPDUSize);
fprintf(trace, "AveragePDUSize=\"%d\" ", p->avgPDUSize);
fprintf(trace, "MaxBitRate=\"%d\" ", p->maxBitrate);
fprintf(trace, "AverageBitRate=\"%d\">\n", p->avgBitrate);
gf_isom_box_dump_done("HintMediaHeaderBox", a, trace);
return GF_OK;
}
GF_Err nmhd_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "MPEGMediaHeaderBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("MPEGMediaHeaderBox", a, trace);
return GF_OK;
}
GF_Err stbl_dump(GF_Box *a, FILE * trace)
{
GF_SampleTableBox *p;
p = (GF_SampleTableBox *)a;
gf_isom_box_dump_start(a, "SampleTableBox", trace);
fprintf(trace, ">\n");
if (p->size)
gf_isom_box_dump_ex(p->SampleDescription, trace, GF_ISOM_BOX_TYPE_STSD);
if (p->size)
gf_isom_box_dump_ex(p->TimeToSample, trace, GF_ISOM_BOX_TYPE_STTS);
if (p->CompositionOffset) gf_isom_box_dump(p->CompositionOffset, trace);
if (p->CompositionToDecode) gf_isom_box_dump(p->CompositionToDecode, trace);
if (p->SyncSample) gf_isom_box_dump(p->SyncSample, trace);
if (p->ShadowSync) gf_isom_box_dump(p->ShadowSync, trace);
if (p->size)
gf_isom_box_dump_ex(p->SampleToChunk, trace, GF_ISOM_BOX_TYPE_STSC);
if (p->size)
gf_isom_box_dump_ex(p->SampleSize, trace, GF_ISOM_BOX_TYPE_STSZ);
if (p->size)
gf_isom_box_dump_ex(p->ChunkOffset, trace, GF_ISOM_BOX_TYPE_STCO);
if (p->DegradationPriority) gf_isom_box_dump(p->DegradationPriority, trace);
if (p->SampleDep) gf_isom_box_dump(p->SampleDep, trace);
if (p->PaddingBits) gf_isom_box_dump(p->PaddingBits, trace);
if (p->Fragments) gf_isom_box_dump(p->Fragments, trace);
if (p->sub_samples) gf_isom_box_array_dump(p->sub_samples, trace);
if (p->sampleGroupsDescription) gf_isom_box_array_dump(p->sampleGroupsDescription, trace);
if (p->sampleGroups) gf_isom_box_array_dump(p->sampleGroups, trace);
if (p->sai_sizes) {
u32 i;
for (i = 0; i < gf_list_count(p->sai_sizes); i++) {
GF_SampleAuxiliaryInfoSizeBox *saiz = (GF_SampleAuxiliaryInfoSizeBox *)gf_list_get(p->sai_sizes, i);
gf_isom_box_dump(saiz, trace);
}
}
if (p->sai_offsets) {
u32 i;
for (i = 0; i < gf_list_count(p->sai_offsets); i++) {
GF_SampleAuxiliaryInfoOffsetBox *saio = (GF_SampleAuxiliaryInfoOffsetBox *)gf_list_get(p->sai_offsets, i);
gf_isom_box_dump(saio, trace);
}
}
gf_isom_box_dump_done("SampleTableBox", a, trace);
return GF_OK;
}
GF_Err dinf_dump(GF_Box *a, FILE * trace)
{
GF_DataInformationBox *p;
p = (GF_DataInformationBox *)a;
gf_isom_box_dump_start(a, "DataInformationBox", trace);
fprintf(trace, ">\n");
if (p->size)
gf_isom_box_dump_ex(p->dref, trace, GF_ISOM_BOX_TYPE_DREF);
gf_isom_box_dump_done("DataInformationBox", a, trace);
return GF_OK;
}
GF_Err url_dump(GF_Box *a, FILE * trace)
{
GF_DataEntryURLBox *p;
p = (GF_DataEntryURLBox *)a;
gf_isom_box_dump_start(a, "URLDataEntryBox", trace);
if (p->location) {
fprintf(trace, " URL=\"%s\">\n", p->location);
} else {
fprintf(trace, ">\n");
if (p->size) {
if (! (p->flags & 1) ) {
fprintf(trace, "<!--ERROR: No location indicated-->\n");
} else {
fprintf(trace, "<!--Data is contained in the movie file-->\n");
}
}
}
gf_isom_box_dump_done("URLDataEntryBox", a, trace);
return GF_OK;
}
GF_Err urn_dump(GF_Box *a, FILE * trace)
{
GF_DataEntryURNBox *p;
p = (GF_DataEntryURNBox *)a;
gf_isom_box_dump_start(a, "URNDataEntryBox", trace);
if (p->nameURN) fprintf(trace, " URN=\"%s\"", p->nameURN);
if (p->location) fprintf(trace, " URL=\"%s\"", p->location);
fprintf(trace, ">\n");
gf_isom_box_dump_done("URNDataEntryBox", a, trace);
return GF_OK;
}
GF_Err cprt_dump(GF_Box *a, FILE * trace)
{
GF_CopyrightBox *p;
p = (GF_CopyrightBox *)a;
gf_isom_box_dump_start(a, "CopyrightBox", trace);
fprintf(trace, "LanguageCode=\"%s\" CopyrightNotice=\"%s\">\n", p->packedLanguageCode, p->notice);
gf_isom_box_dump_done("CopyrightBox", a, trace);
return GF_OK;
}
GF_Err kind_dump(GF_Box *a, FILE * trace)
{
GF_KindBox *p;
p = (GF_KindBox *)a;
gf_isom_box_dump_start(a, "KindBox", trace);
fprintf(trace, "schemeURI=\"%s\" value=\"%s\">\n", p->schemeURI, (p->value ? p->value : ""));
gf_isom_box_dump_done("KindBox", a, trace);
return GF_OK;
}
static char *format_duration(u64 dur, u32 timescale, char *szDur)
{
u32 h, m, s, ms;
dur = (u32) (( ((Double) (s64) dur)/timescale)*1000);
h = (u32) (dur / 3600000);
dur -= h*3600000;
m = (u32) (dur / 60000);
dur -= m*60000;
s = (u32) (dur/1000);
dur -= s*1000;
ms = (u32) (dur);
sprintf(szDur, "%02d:%02d:%02d.%03d", h, m, s, ms);
return szDur;
}
static void dump_escape_string(FILE * trace, char *name)
{
u32 i, len = (u32) strlen(name);
for (i=0; i<len; i++) {
if (name[i]=='"') fprintf(trace, """);
else fputc(name[i], trace);
}
}
GF_Err chpl_dump(GF_Box *a, FILE * trace)
{
u32 i, count;
char szDur[20];
GF_ChapterListBox *p = (GF_ChapterListBox *)a;
gf_isom_box_dump_start(a, "ChapterListBox", trace);
fprintf(trace, ">\n");
if (p->size) {
count = gf_list_count(p->list);
for (i=0; i<count; i++) {
GF_ChapterEntry *ce = (GF_ChapterEntry *)gf_list_get(p->list, i);
fprintf(trace, "<Chapter name=\"");
dump_escape_string(trace, ce->name);
fprintf(trace, "\" startTime=\"%s\" />\n", format_duration(ce->start_time, 1000*10000, szDur));
}
} else {
fprintf(trace, "<Chapter name=\"\" startTime=\"\"/>\n");
}
gf_isom_box_dump_done("ChapterListBox", a, trace);
return GF_OK;
}
GF_Err pdin_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_ProgressiveDownloadBox *p = (GF_ProgressiveDownloadBox *)a;
gf_isom_box_dump_start(a, "ProgressiveDownloadBox", trace);
fprintf(trace, ">\n");
if (p->size) {
for (i=0; i<p->count; i++) {
fprintf(trace, "<DownloadInfo rate=\"%d\" estimatedTime=\"%d\" />\n", p->rates[i], p->times[i]);
}
} else {
fprintf(trace, "<DownloadInfo rate=\"\" estimatedTime=\"\" />\n");
}
gf_isom_box_dump_done("ProgressiveDownloadBox", a, trace);
return GF_OK;
}
GF_Err hdlr_dump(GF_Box *a, FILE * trace)
{
GF_HandlerBox *p = (GF_HandlerBox *)a;
gf_isom_box_dump_start(a, "HandlerBox", trace);
if (p->nameUTF8 && (u32) p->nameUTF8[0] == strlen(p->nameUTF8)-1) {
fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8+1);
} else {
fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8);
}
fprintf(trace, "reserved1=\"%d\" reserved2=\"", p->reserved1);
dump_data(trace, (char *) p->reserved2, 12);
fprintf(trace, "\"");
fprintf(trace, ">\n");
gf_isom_box_dump_done("HandlerBox", a, trace);
return GF_OK;
}
GF_Err iods_dump(GF_Box *a, FILE * trace)
{
GF_ObjectDescriptorBox *p;
p = (GF_ObjectDescriptorBox *)a;
gf_isom_box_dump_start(a, "ObjectDescriptorBox", trace);
fprintf(trace, ">\n");
if (p->descriptor) {
#ifndef GPAC_DISABLE_OD_DUMP
gf_odf_dump_desc(p->descriptor, trace, 1, GF_TRUE);
#else
fprintf(trace, "<!-- Object Descriptor Dumping disabled in this build of GPAC -->\n");
#endif
} else if (p->size) {
fprintf(trace, "<!--WARNING: Object Descriptor not present-->\n");
}
gf_isom_box_dump_done("ObjectDescriptorBox", a, trace);
return GF_OK;
}
GF_Err trak_dump(GF_Box *a, FILE * trace)
{
GF_TrackBox *p;
p = (GF_TrackBox *)a;
gf_isom_box_dump_start(a, "TrackBox", trace);
fprintf(trace, ">\n");
if (p->Header) {
gf_isom_box_dump(p->Header, trace);
} else if (p->size) {
fprintf(trace, "<!--INVALID FILE: Missing Track Header-->\n");
}
if (p->References) gf_isom_box_dump(p->References, trace);
if (p->meta) gf_isom_box_dump(p->meta, trace);
if (p->editBox) gf_isom_box_dump(p->editBox, trace);
if (p->Media) gf_isom_box_dump(p->Media, trace);
if (p->groups) gf_isom_box_dump(p->groups, trace);
if (p->udta) gf_isom_box_dump(p->udta, trace);
gf_isom_box_dump_done("TrackBox", a, trace);
return GF_OK;
}
GF_Err mp4s_dump(GF_Box *a, FILE * trace)
{
GF_MPEGSampleEntryBox *p;
p = (GF_MPEGSampleEntryBox *)a;
gf_isom_box_dump_start(a, "MPEGSystemsSampleDescriptionBox", trace);
fprintf(trace, "DataReferenceIndex=\"%d\">\n", p->dataReferenceIndex);
if (p->esd) {
gf_isom_box_dump(p->esd, trace);
} else if (p->size) {
fprintf(trace, "<!--INVALID MP4 FILE: ESDBox not present in MPEG Sample Description or corrupted-->\n");
}
if (a->type == GF_ISOM_BOX_TYPE_ENCS) {
gf_isom_box_array_dump(p->protections, trace);
}
gf_isom_box_dump_done("MPEGSystemsSampleDescriptionBox", a, trace);
return GF_OK;
}
GF_Err video_sample_entry_dump(GF_Box *a, FILE * trace)
{
GF_MPEGVisualSampleEntryBox *p = (GF_MPEGVisualSampleEntryBox *)a;
const char *name;
switch (p->type) {
case GF_ISOM_SUBTYPE_AVC_H264:
case GF_ISOM_SUBTYPE_AVC2_H264:
case GF_ISOM_SUBTYPE_AVC3_H264:
case GF_ISOM_SUBTYPE_AVC4_H264:
name = "AVCSampleEntryBox";
break;
case GF_ISOM_SUBTYPE_MVC_H264:
name = "MVCSampleEntryBox";
break;
case GF_ISOM_SUBTYPE_SVC_H264:
name = "SVCSampleEntryBox";
break;
case GF_ISOM_SUBTYPE_HVC1:
case GF_ISOM_SUBTYPE_HEV1:
case GF_ISOM_SUBTYPE_HVC2:
case GF_ISOM_SUBTYPE_HEV2:
name = "HEVCSampleEntryBox";
break;
case GF_ISOM_SUBTYPE_LHV1:
case GF_ISOM_SUBTYPE_LHE1:
name = "LHEVCSampleEntryBox";
break;
case GF_ISOM_SUBTYPE_3GP_H263:
name = "H263SampleDescriptionBox";
break;
default:
name = "MPEGVisualSampleDescriptionBox";
}
gf_isom_box_dump_start(a, name, trace);
fprintf(trace, " DataReferenceIndex=\"%d\" Width=\"%d\" Height=\"%d\"", p->dataReferenceIndex, p->Width, p->Height);
//dump reserved info
fprintf(trace, " XDPI=\"%d\" YDPI=\"%d\" BitDepth=\"%d\"", p->horiz_res, p->vert_res, p->bit_depth);
if (strlen((const char*)p->compressor_name) )
fprintf(trace, " CompressorName=\"%s\"\n", p->compressor_name+1);
fprintf(trace, ">\n");
if (p->esd) {
gf_isom_box_dump(p->esd, trace);
} else {
if (p->hevc_config) gf_isom_box_dump(p->hevc_config, trace);
if (p->avc_config) gf_isom_box_dump(p->avc_config, trace);
if (p->ipod_ext) gf_isom_box_dump(p->ipod_ext, trace);
if (p->descr) gf_isom_box_dump(p->descr, trace);
if (p->svc_config) gf_isom_box_dump(p->svc_config, trace);
if (p->mvc_config) gf_isom_box_dump(p->mvc_config, trace);
if (p->lhvc_config) gf_isom_box_dump(p->lhvc_config, trace);
if (p->cfg_3gpp) gf_isom_box_dump(p->cfg_3gpp, trace);
}
if (a->type == GF_ISOM_BOX_TYPE_ENCV) {
gf_isom_box_array_dump(p->protections, trace);
}
if (p->pasp) gf_isom_box_dump(p->pasp, trace);
if (p->rvcc) gf_isom_box_dump(p->rvcc, trace);
if (p->rinf) gf_isom_box_dump(p->rinf, trace);
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
void base_audio_entry_dump(GF_AudioSampleEntryBox *p, FILE * trace)
{
fprintf(trace, " DataReferenceIndex=\"%d\" SampleRate=\"%d\"", p->dataReferenceIndex, p->samplerate_hi);
fprintf(trace, " Channels=\"%d\" BitsPerSample=\"%d\"", p->channel_count, p->bitspersample);
}
GF_Err audio_sample_entry_dump(GF_Box *a, FILE * trace)
{
char *szName;
Bool is_3gpp = GF_FALSE;
GF_MPEGAudioSampleEntryBox *p = (GF_MPEGAudioSampleEntryBox *)a;
switch (p->type) {
case GF_ISOM_SUBTYPE_3GP_AMR:
szName = "AMRSampleDescriptionBox";
is_3gpp = GF_TRUE;
break;
case GF_ISOM_SUBTYPE_3GP_AMR_WB:
szName = "AMR_WB_SampleDescriptionBox";
is_3gpp = GF_TRUE;
break;
case GF_ISOM_SUBTYPE_3GP_EVRC:
szName = "EVRCSampleDescriptionBox";
is_3gpp = GF_TRUE;
break;
case GF_ISOM_SUBTYPE_3GP_QCELP:
szName = "QCELPSampleDescriptionBox";
is_3gpp = GF_TRUE;
break;
case GF_ISOM_SUBTYPE_3GP_SMV:
szName = "SMVSampleDescriptionBox";
is_3gpp = GF_TRUE;
break;
case GF_ISOM_BOX_TYPE_MP4A:
szName = "MPEGAudioSampleDescriptionBox";
break;
case GF_ISOM_BOX_TYPE_AC3:
szName = "AC3SampleEntryBox";
break;
case GF_ISOM_BOX_TYPE_EC3:
szName = "EC3SampleEntryBox";
break;
default:
szName = "AudioSampleDescriptionBox";
break;
}
gf_isom_box_dump_start(a, szName, trace);
base_audio_entry_dump((GF_AudioSampleEntryBox *)p, trace);
fprintf(trace, ">\n");
if (p->esd) {
gf_isom_box_dump(p->esd, trace);
} else if (p->cfg_3gpp) {
gf_isom_box_dump(p->cfg_3gpp, trace);
} else if (p->cfg_ac3) {
if (p->size)
gf_isom_box_dump(p->cfg_ac3, trace);
} else if (p->size) {
if (is_3gpp) {
fprintf(trace, "<!-- INVALID 3GPP FILE: Config not present in Sample Description-->\n");
} else {
fprintf(trace, "<!--INVALID MP4 FILE: ESDBox not present in MPEG Sample Description or corrupted-->\n");
}
}
if (a->type == GF_ISOM_BOX_TYPE_ENCA) {
gf_isom_box_array_dump(p->protections, trace);
}
gf_isom_box_dump_done(szName, a, trace);
return GF_OK;
}
GF_Err gnrm_dump(GF_Box *a, FILE * trace)
{
GF_GenericSampleEntryBox *p = (GF_GenericSampleEntryBox *)a;
if (p->EntryType)
a->type = p->EntryType;
gf_isom_box_dump_start(a, "SampleDescriptionBox", trace);
fprintf(trace, "DataReferenceIndex=\"%d\" ExtensionDataSize=\"%d\">\n", p->dataReferenceIndex, p->data_size);
a->type = GF_ISOM_BOX_TYPE_GNRM;
gf_isom_box_dump_done("SampleDescriptionBox", a, trace);
return GF_OK;
}
GF_Err gnrv_dump(GF_Box *a, FILE * trace)
{
GF_GenericVisualSampleEntryBox *p = (GF_GenericVisualSampleEntryBox *)a;
if (p->EntryType)
a->type = p->EntryType;
gf_isom_box_dump_start(a, "VisualSampleDescriptionBox", trace);
fprintf(trace, "DataReferenceIndex=\"%d\" Version=\"%d\" Revision=\"%d\" Vendor=\"%d\" TemporalQuality=\"%d\" SpacialQuality=\"%d\" Width=\"%d\" Height=\"%d\" HorizontalResolution=\"%d\" VerticalResolution=\"%d\" CompressorName=\"%s\" BitDepth=\"%d\">\n",
p->dataReferenceIndex, p->version, p->revision, p->vendor, p->temporal_quality, p->spatial_quality, p->Width, p->Height, p->horiz_res, p->vert_res, p->compressor_name+1, p->bit_depth);
a->type = GF_ISOM_BOX_TYPE_GNRV;
gf_isom_box_dump_done("VisualSampleDescriptionBox", a, trace);
return GF_OK;
}
GF_Err gnra_dump(GF_Box *a, FILE * trace)
{
GF_GenericAudioSampleEntryBox *p = (GF_GenericAudioSampleEntryBox *)a;
if (p->EntryType)
a->type = p->EntryType;
gf_isom_box_dump_start(a, "AudioSampleDescriptionBox", trace);
fprintf(trace, "DataReferenceIndex=\"%d\" Version=\"%d\" Revision=\"%d\" Vendor=\"%d\" ChannelCount=\"%d\" BitsPerSample=\"%d\" Samplerate=\"%d\">\n",
p->dataReferenceIndex, p->version, p->revision, p->vendor, p->channel_count, p->bitspersample, p->samplerate_hi);
a->type = GF_ISOM_BOX_TYPE_GNRA;
gf_isom_box_dump_done("AudioSampleDescriptionBox", a, trace);
return GF_OK;
}
GF_Err edts_dump(GF_Box *a, FILE * trace)
{
GF_EditBox *p;
p = (GF_EditBox *)a;
gf_isom_box_dump_start(a, "EditBox", trace);
fprintf(trace, ">\n");
if (p->size)
gf_isom_box_dump_ex(p->editList, trace, GF_ISOM_BOX_TYPE_ELST);
gf_isom_box_dump_done("EditBox", a, trace);
return GF_OK;
}
GF_Err udta_dump(GF_Box *a, FILE * trace)
{
GF_UserDataBox *p;
GF_UserDataMap *map;
u32 i;
p = (GF_UserDataBox *)a;
gf_isom_box_dump_start(a, "UserDataBox", trace);
fprintf(trace, ">\n");
i=0;
while ((map = (GF_UserDataMap *)gf_list_enum(p->recordList, &i))) {
gf_isom_box_array_dump(map->other_boxes, trace);
}
gf_isom_box_dump_done("UserDataBox", a, trace);
return GF_OK;
}
GF_Err dref_dump(GF_Box *a, FILE * trace)
{
// GF_DataReferenceBox *p = (GF_DataReferenceBox *)a;
gf_isom_box_dump_start(a, "DataReferenceBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("DataReferenceBox", a, trace);
return GF_OK;
}
GF_Err stsd_dump(GF_Box *a, FILE * trace)
{
// GF_SampleDescriptionBox *p = (GF_SampleDescriptionBox *)a;
gf_isom_box_dump_start(a, "SampleDescriptionBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("SampleDescriptionBox", a, trace);
return GF_OK;
}
GF_Err stts_dump(GF_Box *a, FILE * trace)
{
GF_TimeToSampleBox *p;
u32 i, nb_samples;
p = (GF_TimeToSampleBox *)a;
gf_isom_box_dump_start(a, "TimeToSampleBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries);
nb_samples = 0;
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<TimeToSampleEntry SampleDelta=\"%d\" SampleCount=\"%d\"/>\n", p->entries[i].sampleDelta, p->entries[i].sampleCount);
nb_samples += p->entries[i].sampleCount;
}
if (p->size)
fprintf(trace, "<!-- counted %d samples in STTS entries -->\n", nb_samples);
else
fprintf(trace, "<TimeToSampleEntry SampleDelta=\"\" SampleCount=\"\"/>\n");
gf_isom_box_dump_done("TimeToSampleBox", a, trace);
return GF_OK;
}
GF_Err ctts_dump(GF_Box *a, FILE * trace)
{
GF_CompositionOffsetBox *p;
u32 i, nb_samples;
p = (GF_CompositionOffsetBox *)a;
gf_isom_box_dump_start(a, "CompositionOffsetBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries);
nb_samples = 0;
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<CompositionOffsetEntry CompositionOffset=\"%d\" SampleCount=\"%d\"/>\n", p->entries[i].decodingOffset, p->entries[i].sampleCount);
nb_samples += p->entries[i].sampleCount;
}
if (p->size)
fprintf(trace, "<!-- counted %d samples in CTTS entries -->\n", nb_samples);
else
fprintf(trace, "<CompositionOffsetEntry CompositionOffset=\"\" SampleCount=\"\"/>\n");
gf_isom_box_dump_done("CompositionOffsetBox", a, trace);
return GF_OK;
}
GF_Err cslg_dump(GF_Box *a, FILE * trace)
{
GF_CompositionToDecodeBox *p;
p = (GF_CompositionToDecodeBox *)a;
gf_isom_box_dump_start(a, "CompositionToDecodeBox", trace);
fprintf(trace, "compositionToDTSShift=\"%d\" leastDecodeToDisplayDelta=\"%d\" compositionStartTime=\"%d\" compositionEndTime=\"%d\">\n", p->leastDecodeToDisplayDelta, p->greatestDecodeToDisplayDelta, p->compositionStartTime, p->compositionEndTime);
gf_isom_box_dump_done("CompositionToDecodeBox", a, trace);
return GF_OK;
}
GF_Err ccst_dump(GF_Box *a, FILE * trace)
{
GF_CodingConstraintsBox *p = (GF_CodingConstraintsBox *)a;
gf_isom_box_dump_start(a, "CodingConstraintsBox", trace);
fprintf(trace, "all_ref_pics_intra=\"%d\" intra_pred_used=\"%d\" max_ref_per_pic=\"%d\" reserved=\"%d\">\n", p->all_ref_pics_intra, p->intra_pred_used, p->max_ref_per_pic, p->reserved);
gf_isom_box_dump_done("CodingConstraintsBox", a, trace);
return GF_OK;
}
GF_Err stsh_dump(GF_Box *a, FILE * trace)
{
GF_ShadowSyncBox *p;
u32 i;
GF_StshEntry *t;
p = (GF_ShadowSyncBox *)a;
gf_isom_box_dump_start(a, "SyncShadowBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", gf_list_count(p->entries));
i=0;
while ((t = (GF_StshEntry *)gf_list_enum(p->entries, &i))) {
fprintf(trace, "<SyncShadowEntry ShadowedSample=\"%d\" SyncSample=\"%d\"/>\n", t->shadowedSampleNumber, t->syncSampleNumber);
}
if (!p->size) {
fprintf(trace, "<SyncShadowEntry ShadowedSample=\"\" SyncSample=\"\"/>\n");
}
gf_isom_box_dump_done("SyncShadowBox", a, trace);
return GF_OK;
}
GF_Err elst_dump(GF_Box *a, FILE * trace)
{
GF_EditListBox *p;
u32 i;
GF_EdtsEntry *t;
p = (GF_EditListBox *)a;
gf_isom_box_dump_start(a, "EditListBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", gf_list_count(p->entryList));
i=0;
while ((t = (GF_EdtsEntry *)gf_list_enum(p->entryList, &i))) {
fprintf(trace, "<EditListEntry Duration=\""LLD"\" MediaTime=\""LLD"\" MediaRate=\"%u\"/>\n", LLD_CAST t->segmentDuration, LLD_CAST t->mediaTime, t->mediaRate);
}
if (!p->size) {
fprintf(trace, "<EditListEntry Duration=\"\" MediaTime=\"\" MediaRate=\"\"/>\n");
}
gf_isom_box_dump_done("EditListBox", a, trace);
return GF_OK;
}
GF_Err stsc_dump(GF_Box *a, FILE * trace)
{
GF_SampleToChunkBox *p;
u32 i, nb_samples;
p = (GF_SampleToChunkBox *)a;
gf_isom_box_dump_start(a, "SampleToChunkBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries);
nb_samples = 0;
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<SampleToChunkEntry FirstChunk=\"%d\" SamplesPerChunk=\"%d\" SampleDescriptionIndex=\"%d\"/>\n", p->entries[i].firstChunk, p->entries[i].samplesPerChunk, p->entries[i].sampleDescriptionIndex);
if (i+1<p->nb_entries) {
nb_samples += (p->entries[i+1].firstChunk - p->entries[i].firstChunk) * p->entries[i].samplesPerChunk;
} else {
nb_samples += p->entries[i].samplesPerChunk;
}
}
if (p->size)
fprintf(trace, "<!-- counted %d samples in STSC entries (could be less than sample count) -->\n", nb_samples);
else
fprintf(trace, "<SampleToChunkEntry FirstChunk=\"\" SamplesPerChunk=\"\" SampleDescriptionIndex=\"\"/>\n");
gf_isom_box_dump_done("SampleToChunkBox", a, trace);
return GF_OK;
}
GF_Err stsz_dump(GF_Box *a, FILE * trace)
{
GF_SampleSizeBox *p;
u32 i;
p = (GF_SampleSizeBox *)a;
if (a->type == GF_ISOM_BOX_TYPE_STSZ) {
gf_isom_box_dump_start(a, "SampleSizeBox", trace);
}
else {
gf_isom_box_dump_start(a, "CompactSampleSizeBox", trace);
}
fprintf(trace, "SampleCount=\"%d\"", p->sampleCount);
if (a->type == GF_ISOM_BOX_TYPE_STSZ) {
if (p->sampleSize) {
fprintf(trace, " ConstantSampleSize=\"%d\"", p->sampleSize);
}
} else {
fprintf(trace, " SampleSizeBits=\"%d\"", p->sampleSize);
}
fprintf(trace, ">\n");
if ((a->type != GF_ISOM_BOX_TYPE_STSZ) || !p->sampleSize) {
if (!p->sizes && p->size) {
fprintf(trace, "<!--WARNING: No Sample Size indications-->\n");
} else {
for (i=0; i<p->sampleCount; i++) {
fprintf(trace, "<SampleSizeEntry Size=\"%d\"/>\n", p->sizes[i]);
}
}
}
if (!p->size) {
fprintf(trace, "<SampleSizeEntry Size=\"\"/>\n");
}
gf_isom_box_dump_done((a->type == GF_ISOM_BOX_TYPE_STSZ) ? "SampleSizeBox" : "CompactSampleSizeBox", a, trace);
return GF_OK;
}
GF_Err stco_dump(GF_Box *a, FILE * trace)
{
GF_ChunkOffsetBox *p;
u32 i;
p = (GF_ChunkOffsetBox *)a;
gf_isom_box_dump_start(a, "ChunkOffsetBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries);
if (!p->offsets && p->size) {
fprintf(trace, "<!--Warning: No Chunk Offsets indications-->\n");
} else {
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<ChunkEntry offset=\"%u\"/>\n", p->offsets[i]);
}
}
if (!p->size) {
fprintf(trace, "<ChunkEntry offset=\"\"/>\n");
}
gf_isom_box_dump_done("ChunkOffsetBox", a, trace);
return GF_OK;
}
GF_Err stss_dump(GF_Box *a, FILE * trace)
{
GF_SyncSampleBox *p;
u32 i;
p = (GF_SyncSampleBox *)a;
gf_isom_box_dump_start(a, "SyncSampleBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries);
if (!p->sampleNumbers && p->size) {
fprintf(trace, "<!--Warning: No Key Frames indications-->\n");
} else {
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<SyncSampleEntry sampleNumber=\"%u\"/>\n", p->sampleNumbers[i]);
}
}
if (!p->size) {
fprintf(trace, "<SyncSampleEntry sampleNumber=\"\"/>\n");
}
gf_isom_box_dump_done("SyncSampleBox", a, trace);
return GF_OK;
}
GF_Err stdp_dump(GF_Box *a, FILE * trace)
{
GF_DegradationPriorityBox *p;
u32 i;
p = (GF_DegradationPriorityBox *)a;
gf_isom_box_dump_start(a, "DegradationPriorityBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries);
if (!p->priorities && p->size) {
fprintf(trace, "<!--Warning: No Degradation Priority indications-->\n");
} else {
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<DegradationPriorityEntry DegradationPriority=\"%d\"/>\n", p->priorities[i]);
}
}
if (!p->size) {
fprintf(trace, "<DegradationPriorityEntry DegradationPriority=\"\"/>\n");
}
gf_isom_box_dump_done("DegradationPriorityBox", a, trace);
return GF_OK;
}
GF_Err sdtp_dump(GF_Box *a, FILE * trace)
{
GF_SampleDependencyTypeBox *p;
u32 i;
p = (GF_SampleDependencyTypeBox*)a;
gf_isom_box_dump_start(a, "SampleDependencyTypeBox", trace);
fprintf(trace, "SampleCount=\"%d\">\n", p->sampleCount);
if (!p->sample_info && p->size) {
fprintf(trace, "<!--Warning: No sample dependencies indications-->\n");
} else {
for (i=0; i<p->sampleCount; i++) {
u8 flag = p->sample_info[i];
fprintf(trace, "<SampleDependencyEntry ");
switch ( (flag >> 4) & 3) {
case 0:
fprintf(trace, "dependsOnOther=\"unknown\" ");
break;
case 1:
fprintf(trace, "dependsOnOther=\"yes\" ");
break;
case 2:
fprintf(trace, "dependsOnOther=\"no\" ");
break;
case 3:
fprintf(trace, "dependsOnOther=\"RESERVED\" ");
break;
}
switch ( (flag >> 2) & 3) {
case 0:
fprintf(trace, "dependedOn=\"unknown\" ");
break;
case 1:
fprintf(trace, "dependedOn=\"yes\" ");
break;
case 2:
fprintf(trace, "dependedOn=\"no\" ");
break;
case 3:
fprintf(trace, "dependedOn=\"RESERVED\" ");
break;
}
switch ( flag & 3) {
case 0:
fprintf(trace, "hasRedundancy=\"unknown\" ");
break;
case 1:
fprintf(trace, "hasRedundancy=\"yes\" ");
break;
case 2:
fprintf(trace, "hasRedundancy=\"no\" ");
break;
case 3:
fprintf(trace, "hasRedundancy=\"RESERVED\" ");
break;
}
fprintf(trace, " />\n");
}
}
if (!p->size) {
fprintf(trace, "<SampleDependencyEntry dependsOnOther=\"unknown|yes|no|RESERVED\" dependedOn=\"unknown|yes|no|RESERVED\" hasRedundancy=\"unknown|yes|no|RESERVED\"/>\n");
}
gf_isom_box_dump_done("SampleDependencyTypeBox", a, trace);
return GF_OK;
}
GF_Err co64_dump(GF_Box *a, FILE * trace)
{
GF_ChunkLargeOffsetBox *p;
u32 i;
p = (GF_ChunkLargeOffsetBox *)a;
gf_isom_box_dump_start(a, "ChunkLargeOffsetBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries);
if (!p->offsets && p->size) {
fprintf(trace, "<!-- Warning: No Chunk Offsets indications/>\n");
} else {
for (i=0; i<p->nb_entries; i++)
fprintf(trace, "<ChunkOffsetEntry offset=\""LLU"\"/>\n", LLU_CAST p->offsets[i]);
}
if (!p->size) {
fprintf(trace, "<ChunkOffsetEntry offset=\"\"/>\n");
}
gf_isom_box_dump_done("ChunkLargeOffsetBox", a, trace);
return GF_OK;
}
GF_Err esds_dump(GF_Box *a, FILE * trace)
{
GF_ESDBox *p;
p = (GF_ESDBox *)a;
gf_isom_box_dump_start(a, "MPEG4ESDescriptorBox", trace);
fprintf(trace, ">\n");
if (p->desc) {
#ifndef GPAC_DISABLE_OD_DUMP
gf_odf_dump_desc((GF_Descriptor *) p->desc, trace, 1, GF_TRUE);
#else
fprintf(trace, "<!-- Object Descriptor Dumping disabled in this build of GPAC -->\n");
#endif
} else if (p->size) {
fprintf(trace, "<!--INVALID MP4 FILE: ESD not present in MPEG Sample Description or corrupted-->\n");
}
gf_isom_box_dump_done("MPEG4ESDescriptorBox", a, trace);
return GF_OK;
}
GF_Err minf_dump(GF_Box *a, FILE * trace)
{
GF_MediaInformationBox *p;
p = (GF_MediaInformationBox *)a;
gf_isom_box_dump_start(a, "MediaInformationBox", trace);
fprintf(trace, ">\n");
if (p->size)
gf_isom_box_dump_ex(p->InfoHeader, trace, GF_ISOM_BOX_TYPE_NMHD);
if (p->size)
gf_isom_box_dump_ex(p->dataInformation, trace, GF_ISOM_BOX_TYPE_DINF);
if (p->size)
gf_isom_box_dump_ex(p->sampleTable, trace, GF_ISOM_BOX_TYPE_STBL);
gf_isom_box_dump_done("MediaInformationBox", a, trace);
return GF_OK;
}
GF_Err tkhd_dump(GF_Box *a, FILE * trace)
{
GF_TrackHeaderBox *p;
p = (GF_TrackHeaderBox *)a;
gf_isom_box_dump_start(a, "TrackHeaderBox", trace);
fprintf(trace, "CreationTime=\""LLD"\" ModificationTime=\""LLD"\" TrackID=\"%u\" Duration=\""LLD"\"",
LLD_CAST p->creationTime, LLD_CAST p->modificationTime, p->trackID, LLD_CAST p->duration);
if (p->alternate_group) fprintf(trace, " AlternateGroupID=\"%d\"", p->alternate_group);
if (p->volume) {
fprintf(trace, " Volume=\"%.2f\"", (Float)p->volume / 256);
} else if (p->width || p->height) {
fprintf(trace, " Width=\"%.2f\" Height=\"%.2f\"", (Float)p->width / 65536, (Float)p->height / 65536);
if (p->layer) fprintf(trace, " Layer=\"%d\"", p->layer);
}
fprintf(trace, ">\n");
if (p->width || p->height) {
fprintf(trace, "<Matrix m11=\"0x%.8x\" m12=\"0x%.8x\" m13=\"0x%.8x\" ", p->matrix[0], p->matrix[1], p->matrix[2]);
fprintf(trace, "m21=\"0x%.8x\" m22=\"0x%.8x\" m23=\"0x%.8x\" ", p->matrix[3], p->matrix[4], p->matrix[5]);
fprintf(trace, "m31=\"0x%.8x\" m32=\"0x%.8x\" m33=\"0x%.8x\"/>\n", p->matrix[6], p->matrix[7], p->matrix[8]);
}
gf_isom_box_dump_done("TrackHeaderBox", a, trace);
return GF_OK;
}
GF_Err tref_dump(GF_Box *a, FILE * trace)
{
// GF_TrackReferenceBox *p = (GF_TrackReferenceBox *)a;
gf_isom_box_dump_start(a, "TrackReferenceBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("TrackReferenceBox", a, trace);
return GF_OK;
}
GF_Err mdia_dump(GF_Box *a, FILE * trace)
{
GF_MediaBox *p = (GF_MediaBox *)a;
gf_isom_box_dump_start(a, "MediaBox", trace);
fprintf(trace, ">\n");
if (p->size)
gf_isom_box_dump_ex(p->mediaHeader, trace, GF_ISOM_BOX_TYPE_MDHD);
if (p->size)
gf_isom_box_dump_ex(p->handler, trace,GF_ISOM_BOX_TYPE_HDLR);
if (p->size)
gf_isom_box_dump_ex(p->information, trace, GF_ISOM_BOX_TYPE_MINF);
gf_isom_box_dump_done("MediaBox", a, trace);
return GF_OK;
}
GF_Err mfra_dump(GF_Box *a, FILE * trace)
{
GF_MovieFragmentRandomAccessBox *p = (GF_MovieFragmentRandomAccessBox *)a;
u32 i, count;
GF_TrackFragmentRandomAccessBox *tfra;
gf_isom_box_dump_start(a, "MovieFragmentRandomAccessBox", trace);
fprintf(trace, ">\n");
count = gf_list_count(p->tfra_list);
for (i=0; i<count; i++) {
tfra = (GF_TrackFragmentRandomAccessBox *)gf_list_get(p->tfra_list, i);
gf_isom_box_dump_ex(tfra, trace, GF_ISOM_BOX_TYPE_TFRA);
}
gf_isom_box_dump_done("MovieFragmentRandomAccessBox", a, trace);
return GF_OK;
}
GF_Err tfra_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_TrackFragmentRandomAccessBox *p = (GF_TrackFragmentRandomAccessBox *)a;
gf_isom_box_dump_start(a, "TrackFragmentRandomAccessBox", trace);
fprintf(trace, "TrackId=\"%u\" number_of_entries=\"%u\">\n", p->track_id, p->nb_entries);
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<RandomAccessEntry time=\""LLU"\" moof_offset=\""LLU"\" traf=\"%u\" trun=\"%u\" sample=\"%u\"/>\n",
p->entries[i].time, p->entries[i].moof_offset,
p->entries[i].traf_number, p->entries[i].trun_number, p->entries[i].sample_number);
}
if (!p->size) {
fprintf(trace, "<RandomAccessEntry time=\"\" moof_offset=\"\" traf=\"\" trun=\"\" sample=\"\"/>\n");
}
gf_isom_box_dump_done("TrackFragmentRandomAccessBox", a, trace);
return GF_OK;
}
GF_Err mfro_dump(GF_Box *a, FILE * trace)
{
GF_MovieFragmentRandomAccessOffsetBox *p = (GF_MovieFragmentRandomAccessOffsetBox *)a;
gf_isom_box_dump_start(a, "MovieFragmentRandomAccessOffsetBox", trace);
fprintf(trace, "container_size=\"%d\" >\n", p->container_size);
gf_isom_box_dump_done("MovieFragmentRandomAccessOffsetBox", a, trace);
return GF_OK;
}
GF_Err elng_dump(GF_Box *a, FILE * trace)
{
GF_ExtendedLanguageBox *p = (GF_ExtendedLanguageBox *)a;
gf_isom_box_dump_start(a, "ExtendedLanguageBox", trace);
fprintf(trace, "LanguageCode=\"%s\">\n", p->extended_language);
gf_isom_box_dump_done("ExtendedLanguageBox", a, trace);
return GF_OK;
}
GF_Err unkn_dump(GF_Box *a, FILE * trace)
{
GF_UnknownBox *u = (GF_UnknownBox *)a;
u->type = u->original_4cc;
gf_isom_box_dump_start(a, "UnknownBox", trace);
u->type = GF_ISOM_BOX_TYPE_UNKNOWN;
if (u->dataSize<100)
dump_data_attribute(trace, "data", u->data, u->dataSize);
fprintf(trace, ">\n");
gf_isom_box_dump_done("UnknownBox", a, trace);
return GF_OK;
}
GF_Err uuid_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "UUIDBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("UUIDBox", a, trace);
return GF_OK;
}
GF_Err void_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "VoidBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("VoidBox", a, trace);
return GF_OK;
}
GF_Err ftyp_dump(GF_Box *a, FILE * trace)
{
GF_FileTypeBox *p;
u32 i;
p = (GF_FileTypeBox *)a;
gf_isom_box_dump_start(a, (a->type == GF_ISOM_BOX_TYPE_FTYP ? "FileTypeBox" : "SegmentTypeBox"), trace);
fprintf(trace, "MajorBrand=\"%s\" MinorVersion=\"%d\">\n", gf_4cc_to_str(p->majorBrand), p->minorVersion);
for (i=0; i<p->altCount; i++) {
fprintf(trace, "<BrandEntry AlternateBrand=\"%s\"/>\n", gf_4cc_to_str(p->altBrand[i]));
}
if (!p->type) {
fprintf(trace, "<BrandEntry AlternateBrand=\"4CC\"/>\n");
}
gf_isom_box_dump_done((a->type == GF_ISOM_BOX_TYPE_FTYP ? "FileTypeBox" : "SegmentTypeBox"), a, trace);
return GF_OK;
}
GF_Err padb_dump(GF_Box *a, FILE * trace)
{
GF_PaddingBitsBox *p;
u32 i;
p = (GF_PaddingBitsBox *)a;
gf_isom_box_dump_start(a, "PaddingBitsBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->SampleCount);
for (i=0; i<p->SampleCount; i+=1) {
fprintf(trace, "<PaddingBitsEntry PaddingBits=\"%d\"/>\n", p->padbits[i]);
}
if (!p->size) {
fprintf(trace, "<PaddingBitsEntry PaddingBits=\"\"/>\n");
}
gf_isom_box_dump_done("PaddingBitsBox", a, trace);
return GF_OK;
}
GF_Err stsf_dump(GF_Box *a, FILE * trace)
{
GF_SampleFragmentBox *p;
GF_StsfEntry *ent;
u32 i, j, count;
p = (GF_SampleFragmentBox *)a;
count = gf_list_count(p->entryList);
gf_isom_box_dump_start(a, "SampleFragmentBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", count);
for (i=0; i<count; i++) {
ent = (GF_StsfEntry *)gf_list_get(p->entryList, i);
fprintf(trace, "<SampleFragmentEntry SampleNumber=\"%d\" FragmentCount=\"%d\">\n", ent->SampleNumber, ent->fragmentCount);
for (j=0; j<ent->fragmentCount; j++) fprintf(trace, "<FragmentSizeEntry size=\"%d\"/>\n", ent->fragmentSizes[j]);
fprintf(trace, "</SampleFragmentEntry>\n");
}
if (!p->size) {
fprintf(trace, "<SampleFragmentEntry SampleNumber=\"\" FragmentCount=\"\">\n");
fprintf(trace, "<FragmentSizeEntry size=\"\"/>\n");
fprintf(trace, "</SampleFragmentEntry>\n");
}
gf_isom_box_dump_done("SampleFragmentBox", a, trace);
return GF_OK;
}
GF_Err gppc_dump(GF_Box *a, FILE * trace)
{
GF_3GPPConfigBox *p = (GF_3GPPConfigBox *)a;
const char *name = gf_4cc_to_str(p->cfg.vendor);
switch (p->cfg.type) {
case GF_ISOM_SUBTYPE_3GP_AMR:
case GF_ISOM_SUBTYPE_3GP_AMR_WB:
gf_isom_box_dump_start(a, "AMRConfigurationBox", trace);
fprintf(trace, "Vendor=\"%s\" Version=\"%d\"", name, p->cfg.decoder_version);
fprintf(trace, " FramesPerSample=\"%d\" SupportedModes=\"%x\" ModeRotating=\"%d\"", p->cfg.frames_per_sample, p->cfg.AMR_mode_set, p->cfg.AMR_mode_change_period);
fprintf(trace, ">\n");
gf_isom_box_dump_done("AMRConfigurationBox", a, trace);
break;
case GF_ISOM_SUBTYPE_3GP_EVRC:
gf_isom_box_dump_start(a, "EVRCConfigurationBox", trace);
fprintf(trace, "Vendor=\"%s\" Version=\"%d\" FramesPerSample=\"%d\" >\n", name, p->cfg.decoder_version, p->cfg.frames_per_sample);
gf_isom_box_dump_done("EVRCConfigurationBox", a, trace);
break;
case GF_ISOM_SUBTYPE_3GP_QCELP:
gf_isom_box_dump_start(a, "QCELPConfigurationBox", trace);
fprintf(trace, "Vendor=\"%s\" Version=\"%d\" FramesPerSample=\"%d\" >\n", name, p->cfg.decoder_version, p->cfg.frames_per_sample);
gf_isom_box_dump_done("QCELPConfigurationBox", a, trace);
break;
case GF_ISOM_SUBTYPE_3GP_SMV:
gf_isom_box_dump_start(a, "SMVConfigurationBox", trace);
fprintf(trace, "Vendor=\"%s\" Version=\"%d\" FramesPerSample=\"%d\" >\n", name, p->cfg.decoder_version, p->cfg.frames_per_sample);
gf_isom_box_dump_done("SMVConfigurationBox", a, trace);
break;
case GF_ISOM_SUBTYPE_3GP_H263:
gf_isom_box_dump_start(a, "H263ConfigurationBox", trace);
fprintf(trace, "Vendor=\"%s\" Version=\"%d\"", name, p->cfg.decoder_version);
fprintf(trace, " Profile=\"%d\" Level=\"%d\"", p->cfg.H263_profile, p->cfg.H263_level);
fprintf(trace, ">\n");
gf_isom_box_dump_done("H263ConfigurationBox", a, trace);
break;
default:
break;
}
return GF_OK;
}
GF_Err avcc_dump(GF_Box *a, FILE * trace)
{
u32 i, count;
GF_AVCConfigurationBox *p = (GF_AVCConfigurationBox *) a;
const char *name = (p->type==GF_ISOM_BOX_TYPE_MVCC) ? "MVC" : (p->type==GF_ISOM_BOX_TYPE_SVCC) ? "SVC" : "AVC";
char boxname[256];
sprintf(boxname, "%sConfigurationBox", name);
gf_isom_box_dump_start(a, boxname, trace);
fprintf(trace, ">\n");
fprintf(trace, "<%sDecoderConfigurationRecord", name);
if (! p->config) {
if (p->size) {
fprintf(trace, ">\n");
fprintf(trace, "<!-- INVALID AVC ENTRY : no AVC/SVC config record -->\n");
} else {
fprintf(trace, " configurationVersion=\"\" AVCProfileIndication=\"\" profile_compatibility=\"\" AVCLevelIndication=\"\" nal_unit_size=\"\" complete_representation=\"\"");
fprintf(trace, " chroma_format=\"\" luma_bit_depth=\"\" chroma_bit_depth=\"\"");
fprintf(trace, ">\n");
fprintf(trace, "<SequenceParameterSet size=\"\" content=\"\"/>\n");
fprintf(trace, "<PictureParameterSet size=\"\" content=\"\"/>\n");
fprintf(trace, "<SequenceParameterSetExtensions size=\"\" content=\"\"/>\n");
}
fprintf(trace, "</%sDecoderConfigurationRecord>\n", name);
gf_isom_box_dump_done(boxname, a, trace);
return GF_OK;
}
fprintf(trace, " configurationVersion=\"%d\" AVCProfileIndication=\"%d\" profile_compatibility=\"%d\" AVCLevelIndication=\"%d\" nal_unit_size=\"%d\"", p->config->configurationVersion, p->config->AVCProfileIndication, p->config->profile_compatibility, p->config->AVCLevelIndication, p->config->nal_unit_size);
if ((p->type==GF_ISOM_BOX_TYPE_SVCC) || (p->type==GF_ISOM_BOX_TYPE_MVCC) )
fprintf(trace, " complete_representation=\"%d\"", p->config->complete_representation);
if (p->type==GF_ISOM_BOX_TYPE_AVCC) {
if (gf_avc_is_rext_profile(p->config->AVCProfileIndication)) {
fprintf(trace, " chroma_format=\"%s\" luma_bit_depth=\"%d\" chroma_bit_depth=\"%d\"", gf_avc_hevc_get_chroma_format_name(p->config->chroma_format), p->config->luma_bit_depth, p->config->chroma_bit_depth);
}
}
fprintf(trace, ">\n");
count = gf_list_count(p->config->sequenceParameterSets);
for (i=0; i<count; i++) {
GF_AVCConfigSlot *c = (GF_AVCConfigSlot *)gf_list_get(p->config->sequenceParameterSets, i);
fprintf(trace, "<SequenceParameterSet size=\"%d\" content=\"", c->size);
dump_data(trace, c->data, c->size);
fprintf(trace, "\"/>\n");
}
count = gf_list_count(p->config->pictureParameterSets);
for (i=0; i<count; i++) {
GF_AVCConfigSlot *c = (GF_AVCConfigSlot *)gf_list_get(p->config->pictureParameterSets, i);
fprintf(trace, "<PictureParameterSet size=\"%d\" content=\"", c->size);
dump_data(trace, c->data, c->size);
fprintf(trace, "\"/>\n");
}
if (p->config->sequenceParameterSetExtensions) {
count = gf_list_count(p->config->sequenceParameterSetExtensions);
for (i=0; i<count; i++) {
GF_AVCConfigSlot *c = (GF_AVCConfigSlot *)gf_list_get(p->config->sequenceParameterSetExtensions, i);
fprintf(trace, "<SequenceParameterSetExtensions size=\"%d\" content=\"", c->size);
dump_data(trace, c->data, c->size);
fprintf(trace, "\"/>\n");
}
}
fprintf(trace, "</%sDecoderConfigurationRecord>\n", name);
gf_isom_box_dump_done(boxname, a, trace);
return GF_OK;
}
GF_Err hvcc_dump(GF_Box *a, FILE * trace)
{
u32 i, count;
const char *name = (a->type==GF_ISOM_BOX_TYPE_HVCC) ? "HEVC" : "L-HEVC";
char boxname[256];
GF_HEVCConfigurationBox *p = (GF_HEVCConfigurationBox *) a;
sprintf(boxname, "%sConfigurationBox", name);
gf_isom_box_dump_start(a, boxname, trace);
fprintf(trace, ">\n");
if (! p->config) {
if (p->size) {
fprintf(trace, "<!-- INVALID HEVC ENTRY: no HEVC/SHVC config record -->\n");
} else {
fprintf(trace, "<%sDecoderConfigurationRecord nal_unit_size=\"\" configurationVersion=\"\" ", name);
if (a->type==GF_ISOM_BOX_TYPE_HVCC) {
fprintf(trace, "profile_space=\"\" tier_flag=\"\" profile_idc=\"\" general_profile_compatibility_flags=\"\" progressive_source_flag=\"\" interlaced_source_flag=\"\" non_packed_constraint_flag=\"\" frame_only_constraint_flag=\"\" constraint_indicator_flags=\"\" level_idc=\"\" ");
}
fprintf(trace, "min_spatial_segmentation_idc=\"\" parallelismType=\"\" ");
if (a->type==GF_ISOM_BOX_TYPE_HVCC)
fprintf(trace, "chroma_format=\"\" luma_bit_depth=\"\" chroma_bit_depth=\"\" avgFrameRate=\"\" constantFrameRate=\"\" numTemporalLayers=\"\" temporalIdNested=\"\"");
fprintf(trace, ">\n");
fprintf(trace, "<ParameterSetArray nalu_type=\"\" complete_set=\"\">\n");
fprintf(trace, "<ParameterSet size=\"\" content=\"\"/>\n");
fprintf(trace, "</ParameterSetArray>\n");
fprintf(trace, "</%sDecoderConfigurationRecord>\n", name);
}
fprintf(trace, "</%sConfigurationBox>\n", name);
return GF_OK;
}
fprintf(trace, "<%sDecoderConfigurationRecord nal_unit_size=\"%d\" ", name, p->config->nal_unit_size);
fprintf(trace, "configurationVersion=\"%u\" ", p->config->configurationVersion);
if (a->type==GF_ISOM_BOX_TYPE_HVCC) {
fprintf(trace, "profile_space=\"%u\" ", p->config->profile_space);
fprintf(trace, "tier_flag=\"%u\" ", p->config->tier_flag);
fprintf(trace, "profile_idc=\"%u\" ", p->config->profile_idc);
fprintf(trace, "general_profile_compatibility_flags=\"%X\" ", p->config->general_profile_compatibility_flags);
fprintf(trace, "progressive_source_flag=\"%u\" ", p->config->progressive_source_flag);
fprintf(trace, "interlaced_source_flag=\"%u\" ", p->config->interlaced_source_flag);
fprintf(trace, "non_packed_constraint_flag=\"%u\" ", p->config->non_packed_constraint_flag);
fprintf(trace, "frame_only_constraint_flag=\"%u\" ", p->config->frame_only_constraint_flag);
fprintf(trace, "constraint_indicator_flags=\""LLX"\" ", p->config->constraint_indicator_flags);
fprintf(trace, "level_idc=\"%d\" ", p->config->level_idc);
}
fprintf(trace, "min_spatial_segmentation_idc=\"%u\" ", p->config->min_spatial_segmentation_idc);
fprintf(trace, "parallelismType=\"%u\" ", p->config->parallelismType);
if (a->type==GF_ISOM_BOX_TYPE_HVCC)
fprintf(trace, "chroma_format=\"%s\" luma_bit_depth=\"%u\" chroma_bit_depth=\"%u\" avgFrameRate=\"%u\" constantFrameRate=\"%u\" numTemporalLayers=\"%u\" temporalIdNested=\"%u\"",
gf_avc_hevc_get_chroma_format_name(p->config->chromaFormat), p->config->luma_bit_depth, p->config->chroma_bit_depth, p->config->avgFrameRate, p->config->constantFrameRate, p->config->numTemporalLayers, p->config->temporalIdNested);
fprintf(trace, ">\n");
count = gf_list_count(p->config->param_array);
for (i=0; i<count; i++) {
u32 nalucount, j;
GF_HEVCParamArray *ar = (GF_HEVCParamArray*)gf_list_get(p->config->param_array, i);
fprintf(trace, "<ParameterSetArray nalu_type=\"%d\" complete_set=\"%d\">\n", ar->type, ar->array_completeness);
nalucount = gf_list_count(ar->nalus);
for (j=0; j<nalucount; j++) {
GF_AVCConfigSlot *c = (GF_AVCConfigSlot *)gf_list_get(ar->nalus, j);
fprintf(trace, "<ParameterSet size=\"%d\" content=\"", c->size);
dump_data(trace, c->data, c->size);
fprintf(trace, "\"/>\n");
}
fprintf(trace, "</ParameterSetArray>\n");
}
fprintf(trace, "</%sDecoderConfigurationRecord>\n", name);
gf_isom_box_dump_done(boxname, a, trace);
return GF_OK;
}
GF_Err m4ds_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_Descriptor *desc;
GF_MPEG4ExtensionDescriptorsBox *p = (GF_MPEG4ExtensionDescriptorsBox *) a;
gf_isom_box_dump_start(a, "MPEG4ExtensionDescriptorsBox", trace);
fprintf(trace, ">\n");
i=0;
while ((desc = (GF_Descriptor *)gf_list_enum(p->descriptors, &i))) {
#ifndef GPAC_DISABLE_OD_DUMP
gf_odf_dump_desc(desc, trace, 1, GF_TRUE);
#else
fprintf(trace, "<!-- Object Descriptor Dumping disabled in this build of GPAC -->\n");
#endif
}
gf_isom_box_dump_done("MPEG4ExtensionDescriptorsBox", a, trace);
return GF_OK;
}
GF_Err btrt_dump(GF_Box *a, FILE * trace)
{
GF_BitRateBox *p = (GF_BitRateBox*)a;
gf_isom_box_dump_start(a, "BitRateBox", trace);
fprintf(trace, "BufferSizeDB=\"%d\" avgBitRate=\"%d\" maxBitRate=\"%d\">\n", p->bufferSizeDB, p->avgBitrate, p->maxBitrate);
gf_isom_box_dump_done("BitRateBox", a, trace);
return GF_OK;
}
GF_Err ftab_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_FontTableBox *p = (GF_FontTableBox *)a;
gf_isom_box_dump_start(a, "FontTableBox", trace);
fprintf(trace, ">\n");
for (i=0; i<p->entry_count; i++) {
fprintf(trace, "<FontRecord ID=\"%d\" name=\"%s\"/>\n", p->fonts[i].fontID, p->fonts[i].fontName ? p->fonts[i].fontName : "NULL");
}
if (!p->size) {
fprintf(trace, "<FontRecord ID=\"\" name=\"\"/>\n");
}
gf_isom_box_dump_done("FontTableBox", a, trace);
return GF_OK;
}
static void tx3g_dump_rgba8(FILE * trace, char *name, u32 col)
{
fprintf(trace, "%s=\"%x %x %x %x\"", name, (col>>16)&0xFF, (col>>8)&0xFF, (col)&0xFF, (col>>24)&0xFF);
}
static void tx3g_dump_rgb16(FILE * trace, char *name, char col[6])
{
fprintf(trace, "%s=\"%x %x %x\"", name, *((u16*)col), *((u16*)(col+1)), *((u16*)(col+2)));
}
static void tx3g_dump_box(FILE * trace, GF_BoxRecord *rec)
{
fprintf(trace, "<BoxRecord top=\"%d\" left=\"%d\" bottom=\"%d\" right=\"%d\"/>\n", rec->top, rec->left, rec->bottom, rec->right);
}
static void tx3g_dump_style(FILE * trace, GF_StyleRecord *rec)
{
fprintf(trace, "<StyleRecord startChar=\"%d\" endChar=\"%d\" fontID=\"%d\" styles=\"", rec->startCharOffset, rec->endCharOffset, rec->fontID);
if (!rec->style_flags) {
fprintf(trace, "Normal");
} else {
if (rec->style_flags & 1) fprintf(trace, "Bold ");
if (rec->style_flags & 2) fprintf(trace, "Italic ");
if (rec->style_flags & 4) fprintf(trace, "Underlined ");
}
fprintf(trace, "\" fontSize=\"%d\" ", rec->font_size);
tx3g_dump_rgba8(trace, "textColor", rec->text_color);
fprintf(trace, "/>\n");
}
GF_Err tx3g_dump(GF_Box *a, FILE * trace)
{
GF_Tx3gSampleEntryBox *p = (GF_Tx3gSampleEntryBox *)a;
gf_isom_box_dump_start(a, "Tx3gSampleEntryBox", trace);
fprintf(trace, "dataReferenceIndex=\"%d\" displayFlags=\"%x\" horizontal-justification=\"%d\" vertical-justification=\"%d\" ",
p->dataReferenceIndex, p->displayFlags, p->horizontal_justification, p->vertical_justification);
tx3g_dump_rgba8(trace, "backgroundColor", p->back_color);
fprintf(trace, ">\n");
fprintf(trace, "<DefaultBox>\n");
tx3g_dump_box(trace, &p->default_box);
gf_isom_box_dump_done("DefaultBox", a, trace);
fprintf(trace, "<DefaultStyle>\n");
tx3g_dump_style(trace, &p->default_style);
fprintf(trace, "</DefaultStyle>\n");
if (p->size) {
gf_isom_box_dump_ex(p->font_table, trace, GF_ISOM_BOX_TYPE_FTAB);
}
gf_isom_box_dump_done("Tx3gSampleEntryBox", a, trace);
return GF_OK;
}
GF_Err text_dump(GF_Box *a, FILE * trace)
{
GF_TextSampleEntryBox *p = (GF_TextSampleEntryBox *)a;
gf_isom_box_dump_start(a, "TextSampleEntryBox", trace);
fprintf(trace, "dataReferenceIndex=\"%d\" displayFlags=\"%x\" textJustification=\"%d\" ",
p->dataReferenceIndex, p->displayFlags, p->textJustification);
if (p->textName)
fprintf(trace, "textName=\"%s\" ", p->textName);
tx3g_dump_rgb16(trace, "background-color", p->background_color);
tx3g_dump_rgb16(trace, " foreground-color", p->foreground_color);
fprintf(trace, ">\n");
fprintf(trace, "<DefaultBox>\n");
tx3g_dump_box(trace, &p->default_box);
gf_isom_box_dump_done("DefaultBox", a, trace);
gf_isom_box_dump_done("TextSampleEntryBox", a, trace);
return GF_OK;
}
GF_Err styl_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_TextStyleBox*p = (GF_TextStyleBox*)a;
gf_isom_box_dump_start(a, "TextStyleBox", trace);
fprintf(trace, ">\n");
for (i=0; i<p->entry_count; i++) tx3g_dump_style(trace, &p->styles[i]);
if (!p->size) {
fprintf(trace, "<StyleRecord startChar=\"\" endChar=\"\" fontID=\"\" styles=\"Normal|Bold|Italic|Underlined\" fontSize=\"\" textColor=\"\" />\n");
}
gf_isom_box_dump_done("TextStyleBox", a, trace);
return GF_OK;
}
GF_Err hlit_dump(GF_Box *a, FILE * trace)
{
GF_TextHighlightBox*p = (GF_TextHighlightBox*)a;
gf_isom_box_dump_start(a, "TextHighlightBox", trace);
fprintf(trace, "startcharoffset=\"%d\" endcharoffset=\"%d\">\n", p->startcharoffset, p->endcharoffset);
gf_isom_box_dump_done("TextHighlightBox", a, trace);
return GF_OK;
}
GF_Err hclr_dump(GF_Box *a, FILE * trace)
{
GF_TextHighlightColorBox*p = (GF_TextHighlightColorBox*)a;
gf_isom_box_dump_start(a, "TextHighlightColorBox", trace);
tx3g_dump_rgba8(trace, "highlight_color", p->hil_color);
fprintf(trace, ">\n");
gf_isom_box_dump_done("TextHighlightColorBox", a, trace);
return GF_OK;
}
GF_Err krok_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_TextKaraokeBox*p = (GF_TextKaraokeBox*)a;
gf_isom_box_dump_start(a, "TextKaraokeBox", trace);
fprintf(trace, "highlight_starttime=\"%d\">\n", p->highlight_starttime);
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<KaraokeRecord highlight_endtime=\"%d\" start_charoffset=\"%d\" end_charoffset=\"%d\"/>\n", p->records[i].highlight_endtime, p->records[i].start_charoffset, p->records[i].end_charoffset);
}
if (!p->size) {
fprintf(trace, "<KaraokeRecord highlight_endtime=\"\" start_charoffset=\"\" end_charoffset=\"\"/>\n");
}
gf_isom_box_dump_done("TextKaraokeBox", a, trace);
return GF_OK;
}
GF_Err dlay_dump(GF_Box *a, FILE * trace)
{
GF_TextScrollDelayBox*p = (GF_TextScrollDelayBox*)a;
gf_isom_box_dump_start(a, "TextScrollDelayBox", trace);
fprintf(trace, "scroll_delay=\"%d\">\n", p->scroll_delay);
gf_isom_box_dump_done("TextScrollDelayBox", a, trace);
return GF_OK;
}
GF_Err href_dump(GF_Box *a, FILE * trace)
{
GF_TextHyperTextBox*p = (GF_TextHyperTextBox*)a;
gf_isom_box_dump_start(a, "TextHyperTextBox", trace);
fprintf(trace, "startcharoffset=\"%d\" endcharoffset=\"%d\" URL=\"%s\" altString=\"%s\">\n", p->startcharoffset, p->endcharoffset, p->URL ? p->URL : "NULL", p->URL_hint ? p->URL_hint : "NULL");
gf_isom_box_dump_done("TextHyperTextBox", a, trace);
return GF_OK;
}
GF_Err tbox_dump(GF_Box *a, FILE * trace)
{
GF_TextBoxBox*p = (GF_TextBoxBox*)a;
gf_isom_box_dump_start(a, "TextBoxBox", trace);
fprintf(trace, ">\n");
tx3g_dump_box(trace, &p->box);
gf_isom_box_dump_done("TextBoxBox", a, trace);
return GF_OK;
}
GF_Err blnk_dump(GF_Box *a, FILE * trace)
{
GF_TextBlinkBox*p = (GF_TextBlinkBox*)a;
gf_isom_box_dump_start(a, "TextBlinkBox", trace);
fprintf(trace, "start_charoffset=\"%d\" end_charoffset=\"%d\">\n", p->startcharoffset, p->endcharoffset);
gf_isom_box_dump_done("TextBlinkBox", a, trace);
return GF_OK;
}
GF_Err twrp_dump(GF_Box *a, FILE * trace)
{
GF_TextWrapBox*p = (GF_TextWrapBox*)a;
gf_isom_box_dump_start(a, "TextWrapBox", trace);
fprintf(trace, "wrap_flag=\"%s\">\n", p->wrap_flag ? ( (p->wrap_flag>1) ? "Reserved" : "Automatic" ) : "No Wrap");
gf_isom_box_dump_done("TextWrapBox", a, trace);
return GF_OK;
}
GF_Err meta_dump(GF_Box *a, FILE * trace)
{
GF_MetaBox *p;
p = (GF_MetaBox *)a;
gf_isom_box_dump_start(a, "MetaBox", trace);
fprintf(trace, ">\n");
if (p->handler) gf_isom_box_dump(p->handler, trace);
if (p->primary_resource) gf_isom_box_dump(p->primary_resource, trace);
if (p->file_locations) gf_isom_box_dump(p->file_locations, trace);
if (p->item_locations) gf_isom_box_dump(p->item_locations, trace);
if (p->protections) gf_isom_box_dump(p->protections, trace);
if (p->item_infos) gf_isom_box_dump(p->item_infos, trace);
if (p->IPMP_control) gf_isom_box_dump(p->IPMP_control, trace);
if (p->item_refs) gf_isom_box_dump(p->item_refs, trace);
if (p->item_props) gf_isom_box_dump(p->item_props, trace);
gf_isom_box_dump_done("MetaBox", a, trace);
return GF_OK;
}
GF_Err xml_dump(GF_Box *a, FILE * trace)
{
GF_XMLBox *p = (GF_XMLBox *)a;
gf_isom_box_dump_start(a, "XMLBox", trace);
fprintf(trace, ">\n");
fprintf(trace, "<![CDATA[\n");
if (p->xml)
gf_fwrite(p->xml, strlen(p->xml), 1, trace);
fprintf(trace, "]]>\n");
gf_isom_box_dump_done("XMLBox", a, trace);
return GF_OK;
}
GF_Err bxml_dump(GF_Box *a, FILE * trace)
{
GF_BinaryXMLBox *p = (GF_BinaryXMLBox *)a;
gf_isom_box_dump_start(a, "BinaryXMLBox", trace);
fprintf(trace, "binarySize=\"%d\">\n", p->data_length);
gf_isom_box_dump_done("BinaryXMLBox", a, trace);
return GF_OK;
}
GF_Err pitm_dump(GF_Box *a, FILE * trace)
{
GF_PrimaryItemBox *p = (GF_PrimaryItemBox *)a;
gf_isom_box_dump_start(a, "PrimaryItemBox", trace);
fprintf(trace, "item_ID=\"%d\">\n", p->item_ID);
gf_isom_box_dump_done("PrimaryItemBox", a, trace);
return GF_OK;
}
GF_Err ipro_dump(GF_Box *a, FILE * trace)
{
GF_ItemProtectionBox *p = (GF_ItemProtectionBox *)a;
gf_isom_box_dump_start(a, "ItemProtectionBox", trace);
fprintf(trace, ">\n");
gf_isom_box_array_dump(p->protection_information, trace);
gf_isom_box_dump_done("ItemProtectionBox", a, trace);
return GF_OK;
}
GF_Err infe_dump(GF_Box *a, FILE * trace)
{
GF_ItemInfoEntryBox *p = (GF_ItemInfoEntryBox *)a;
gf_isom_box_dump_start(a, "ItemInfoEntryBox", trace);
fprintf(trace, "item_ID=\"%d\" item_protection_index=\"%d\" item_name=\"%s\" content_type=\"%s\" content_encoding=\"%s\" item_type=\"%s\">\n", p->item_ID, p->item_protection_index, p->item_name, p->content_type, p->content_encoding, gf_4cc_to_str(p->item_type));
gf_isom_box_dump_done("ItemInfoEntryBox", a, trace);
return GF_OK;
}
GF_Err iinf_dump(GF_Box *a, FILE * trace)
{
GF_ItemInfoBox *p = (GF_ItemInfoBox *)a;
gf_isom_box_dump_start(a, "ItemInfoBox", trace);
fprintf(trace, ">\n");
gf_isom_box_array_dump(p->item_infos, trace);
gf_isom_box_dump_done("ItemInfoBox", a, trace);
return GF_OK;
}
GF_Err iloc_dump(GF_Box *a, FILE * trace)
{
u32 i, j, count, count2;
GF_ItemLocationBox *p = (GF_ItemLocationBox*)a;
gf_isom_box_dump_start(a, "ItemLocationBox", trace);
fprintf(trace, "offset_size=\"%d\" length_size=\"%d\" base_offset_size=\"%d\" index_size=\"%d\">\n", p->offset_size, p->length_size, p->base_offset_size, p->index_size);
count = gf_list_count(p->location_entries);
for (i=0; i<count; i++) {
GF_ItemLocationEntry *ie = (GF_ItemLocationEntry *)gf_list_get(p->location_entries, i);
count2 = gf_list_count(ie->extent_entries);
fprintf(trace, "<ItemLocationEntry item_ID=\"%d\" data_reference_index=\"%d\" base_offset=\""LLD"\" construction_method=\"%d\">\n", ie->item_ID, ie->data_reference_index, LLD_CAST ie->base_offset, ie->construction_method);
for (j=0; j<count2; j++) {
GF_ItemExtentEntry *iee = (GF_ItemExtentEntry *)gf_list_get(ie->extent_entries, j);
fprintf(trace, "<ItemExtentEntry extent_offset=\""LLD"\" extent_length=\""LLD"\" extent_index=\""LLD"\" />\n", LLD_CAST iee->extent_offset, LLD_CAST iee->extent_length, LLD_CAST iee->extent_index);
}
fprintf(trace, "</ItemLocationEntry>\n");
}
if (!p->size) {
fprintf(trace, "<ItemLocationEntry item_ID=\"\" data_reference_index=\"\" base_offset=\"\" construction_method=\"\">\n");
fprintf(trace, "<ItemExtentEntry extent_offset=\"\" extent_length=\"\" extent_index=\"\" />\n");
fprintf(trace, "</ItemLocationEntry>\n");
}
gf_isom_box_dump_done("ItemLocationBox", a, trace);
return GF_OK;
}
GF_Err iref_dump(GF_Box *a, FILE * trace)
{
GF_ItemReferenceBox *p = (GF_ItemReferenceBox *)a;
gf_isom_box_dump_start(a, "ItemReferenceBox", trace);
fprintf(trace, ">\n");
gf_isom_box_array_dump(p->references, trace);
gf_isom_box_dump_done("ItemReferenceBox", a, trace);
return GF_OK;
}
GF_Err hinf_dump(GF_Box *a, FILE * trace)
{
// GF_HintInfoBox *p = (GF_HintInfoBox *)a;
gf_isom_box_dump_start(a, "HintInfoBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("HintInfoBox", a, trace);
return GF_OK;
}
GF_Err trpy_dump(GF_Box *a, FILE * trace)
{
GF_TRPYBox *p = (GF_TRPYBox *)a;
gf_isom_box_dump_start(a, "LargeTotalRTPBytesBox", trace);
fprintf(trace, "RTPBytesSent=\""LLD"\">\n", LLD_CAST p->nbBytes);
gf_isom_box_dump_done("LargeTotalRTPBytesBox", a, trace);
return GF_OK;
}
GF_Err totl_dump(GF_Box *a, FILE * trace)
{
GF_TOTLBox *p;
p = (GF_TOTLBox *)a;
gf_isom_box_dump_start(a, "TotalRTPBytesBox", trace);
fprintf(trace, "RTPBytesSent=\"%d\">\n", p->nbBytes);
gf_isom_box_dump_done("TotalRTPBytesBox", a, trace);
return GF_OK;
}
GF_Err nump_dump(GF_Box *a, FILE * trace)
{
GF_NUMPBox *p;
p = (GF_NUMPBox *)a;
gf_isom_box_dump_start(a, "LargeTotalPacketBox", trace);
fprintf(trace, "PacketsSent=\""LLD"\">\n", LLD_CAST p->nbPackets);
gf_isom_box_dump_done("LargeTotalPacketBox", a, trace);
return GF_OK;
}
GF_Err npck_dump(GF_Box *a, FILE * trace)
{
GF_NPCKBox *p;
p = (GF_NPCKBox *)a;
gf_isom_box_dump_start(a, "TotalPacketBox", trace);
fprintf(trace, "packetsSent=\"%d\">\n", p->nbPackets);
gf_isom_box_dump_done("TotalPacketBox", a, trace);
return GF_OK;
}
GF_Err tpyl_dump(GF_Box *a, FILE * trace)
{
GF_NTYLBox *p;
p = (GF_NTYLBox *)a;
gf_isom_box_dump_start(a, "LargeTotalMediaBytesBox", trace);
fprintf(trace, "BytesSent=\""LLD"\">\n", LLD_CAST p->nbBytes);
gf_isom_box_dump_done("LargeTotalMediaBytesBox", a, trace);
return GF_OK;
}
GF_Err tpay_dump(GF_Box *a, FILE * trace)
{
GF_TPAYBox *p;
p = (GF_TPAYBox *)a;
gf_isom_box_dump_start(a, "TotalMediaBytesBox", trace);
fprintf(trace, "BytesSent=\"%d\">\n", p->nbBytes);
gf_isom_box_dump_done("TotalMediaBytesBox", a, trace);
return GF_OK;
}
GF_Err maxr_dump(GF_Box *a, FILE * trace)
{
GF_MAXRBox *p;
p = (GF_MAXRBox *)a;
gf_isom_box_dump_start(a, "MaxDataRateBox", trace);
fprintf(trace, "MaxDataRate=\"%d\" Granularity=\"%d\">\n", p->maxDataRate, p->granularity);
gf_isom_box_dump_done("MaxDataRateBox", a, trace);
return GF_OK;
}
GF_Err dmed_dump(GF_Box *a, FILE * trace)
{
GF_DMEDBox *p;
p = (GF_DMEDBox *)a;
gf_isom_box_dump_start(a, "BytesFromMediaTrackBox", trace);
fprintf(trace, "BytesSent=\""LLD"\">\n", LLD_CAST p->nbBytes);
gf_isom_box_dump_done("BytesFromMediaTrackBox", a, trace);
return GF_OK;
}
GF_Err dimm_dump(GF_Box *a, FILE * trace)
{
GF_DIMMBox *p;
p = (GF_DIMMBox *)a;
gf_isom_box_dump_start(a, "ImmediateDataBytesBox", trace);
fprintf(trace, "BytesSent=\""LLD"\">\n", LLD_CAST p->nbBytes);
gf_isom_box_dump_done("ImmediateDataBytesBox", a, trace);
return GF_OK;
}
GF_Err drep_dump(GF_Box *a, FILE * trace)
{
GF_DREPBox *p;
p = (GF_DREPBox *)a;
gf_isom_box_dump_start(a, "RepeatedDataBytesBox", trace);
fprintf(trace, "RepeatedBytes=\""LLD"\">\n", LLD_CAST p->nbBytes);
gf_isom_box_dump_done("RepeatedDataBytesBox", a, trace);
return GF_OK;
}
GF_Err tssy_dump(GF_Box *a, FILE * trace)
{
GF_TimeStampSynchronyBox *p = (GF_TimeStampSynchronyBox *)a;
gf_isom_box_dump_start(a, "TimeStampSynchronyBox", trace);
fprintf(trace, "timestamp_sync=\"%d\">\n", p->timestamp_sync);
gf_isom_box_dump_done("TimeStampSynchronyBox", a, trace);
return GF_OK;
}
GF_Err rssr_dump(GF_Box *a, FILE * trace)
{
GF_ReceivedSsrcBox *p = (GF_ReceivedSsrcBox *)a;
gf_isom_box_dump_start(a, "ReceivedSsrcBox", trace);
fprintf(trace, "SSRC=\"%d\">\n", p->ssrc);
gf_isom_box_dump_done("ReceivedSsrcBox", a, trace);
return GF_OK;
}
GF_Err tmin_dump(GF_Box *a, FILE * trace)
{
GF_TMINBox *p;
p = (GF_TMINBox *)a;
gf_isom_box_dump_start(a, "MinTransmissionTimeBox", trace);
fprintf(trace, "MinimumTransmitTime=\"%d\">\n", p->minTime);
gf_isom_box_dump_done("MinTransmissionTimeBox", a, trace);
return GF_OK;
}
GF_Err tmax_dump(GF_Box *a, FILE * trace)
{
GF_TMAXBox *p;
p = (GF_TMAXBox *)a;
gf_isom_box_dump_start(a, "MaxTransmissionTimeBox", trace);
fprintf(trace, "MaximumTransmitTime=\"%d\">\n", p->maxTime);
gf_isom_box_dump_done("MaxTransmissionTimeBox", a, trace);
return GF_OK;
}
GF_Err pmax_dump(GF_Box *a, FILE * trace)
{
GF_PMAXBox *p;
p = (GF_PMAXBox *)a;
gf_isom_box_dump_start(a, "MaxPacketSizeBox", trace);
fprintf(trace, "MaximumSize=\"%d\">\n", p->maxSize);
gf_isom_box_dump_done("MaxPacketSizeBox", a, trace);
return GF_OK;
}
GF_Err dmax_dump(GF_Box *a, FILE * trace)
{
GF_DMAXBox *p;
p = (GF_DMAXBox *)a;
gf_isom_box_dump_start(a, "MaxPacketDurationBox", trace);
fprintf(trace, "MaximumDuration=\"%d\">\n", p->maxDur);
gf_isom_box_dump_done("MaxPacketDurationBox", a, trace);
return GF_OK;
}
GF_Err payt_dump(GF_Box *a, FILE * trace)
{
GF_PAYTBox *p;
p = (GF_PAYTBox *)a;
gf_isom_box_dump_start(a, "PayloadTypeBox", trace);
fprintf(trace, "PayloadID=\"%d\" PayloadString=\"%s\">\n", p->payloadCode, p->payloadString);
gf_isom_box_dump_done("PayloadTypeBox", a, trace);
return GF_OK;
}
GF_Err name_dump(GF_Box *a, FILE * trace)
{
GF_NameBox *p;
p = (GF_NameBox *)a;
gf_isom_box_dump_start(a, "NameBox", trace);
fprintf(trace, "Name=\"%s\">\n", p->string);
gf_isom_box_dump_done("NameBox", a, trace);
return GF_OK;
}
GF_Err rely_dump(GF_Box *a, FILE * trace)
{
GF_RelyHintBox *p;
p = (GF_RelyHintBox *)a;
gf_isom_box_dump_start(a, "RelyTransmissionBox", trace);
fprintf(trace, "Prefered=\"%d\" required=\"%d\">\n", p->prefered, p->required);
gf_isom_box_dump_done("RelyTransmissionBox", a, trace);
return GF_OK;
}
GF_Err snro_dump(GF_Box *a, FILE * trace)
{
GF_SeqOffHintEntryBox *p;
p = (GF_SeqOffHintEntryBox *)a;
gf_isom_box_dump_start(a, "PacketSequenceOffsetBox", trace);
fprintf(trace, "SeqNumOffset=\"%d\">\n", p->SeqOffset);
gf_isom_box_dump_done("PacketSequenceOffsetBox", a, trace);
return GF_OK;
}
GF_Err tims_dump(GF_Box *a, FILE * trace)
{
GF_TSHintEntryBox *p;
p = (GF_TSHintEntryBox *)a;
gf_isom_box_dump_start(a, "RTPTimeScaleBox", trace);
fprintf(trace, "TimeScale=\"%d\">\n", p->timeScale);
gf_isom_box_dump_done("RTPTimeScaleBox", a, trace);
return GF_OK;
}
GF_Err tsro_dump(GF_Box *a, FILE * trace)
{
GF_TimeOffHintEntryBox *p;
p = (GF_TimeOffHintEntryBox *)a;
gf_isom_box_dump_start(a, "TimeStampOffsetBox", trace);
fprintf(trace, "TimeStampOffset=\"%d\">\n", p->TimeOffset);
gf_isom_box_dump_done("TimeStampOffsetBox", a, trace);
return GF_OK;
}
GF_Err ghnt_dump(GF_Box *a, FILE * trace)
{
char *name;
GF_HintSampleEntryBox *p;
p = (GF_HintSampleEntryBox *)a;
if (a->type == GF_ISOM_BOX_TYPE_RTP_STSD) {
name = "RTPHintSampleEntryBox";
} else if (a->type == GF_ISOM_BOX_TYPE_SRTP_STSD) {
name = "SRTPHintSampleEntryBox";
} else if (a->type == GF_ISOM_BOX_TYPE_FDP_STSD) {
name = "FDPHintSampleEntryBox";
} else if (a->type == GF_ISOM_BOX_TYPE_RRTP_STSD) {
name = "RTPReceptionHintSampleEntryBox";
} else if (a->type == GF_ISOM_BOX_TYPE_RTCP_STSD) {
name = "RTCPReceptionHintSampleEntryBox";
} else {
name = "GenericHintSampleEntryBox";
}
gf_isom_box_dump_start(a, name, trace);
fprintf(trace, "DataReferenceIndex=\"%d\" HintTrackVersion=\"%d\" LastCompatibleVersion=\"%d\"", p->dataReferenceIndex, p->HintTrackVersion, p->LastCompatibleVersion);
if ((a->type == GF_ISOM_BOX_TYPE_RTP_STSD) || (a->type == GF_ISOM_BOX_TYPE_SRTP_STSD) || (a->type == GF_ISOM_BOX_TYPE_RRTP_STSD) || (a->type == GF_ISOM_BOX_TYPE_RTCP_STSD)) {
fprintf(trace, " MaxPacketSize=\"%d\"", p->MaxPacketSize);
} else if (a->type == GF_ISOM_BOX_TYPE_FDP_STSD) {
fprintf(trace, " partition_entry_ID=\"%d\" FEC_overhead=\"%d\"", p->partition_entry_ID, p->FEC_overhead);
}
fprintf(trace, ">\n");
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
GF_Err hnti_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "HintTrackInfoBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("HintTrackInfoBox", NULL, trace);
return GF_OK;
}
GF_Err sdp_dump(GF_Box *a, FILE * trace)
{
GF_SDPBox *p = (GF_SDPBox *)a;
gf_isom_box_dump_start(a, "SDPBox", trace);
fprintf(trace, ">\n");
if (p->sdpText)
fprintf(trace, "<!-- sdp text: %s -->\n", p->sdpText);
gf_isom_box_dump_done("SDPBox", a, trace);
return GF_OK;
}
GF_Err rtp_hnti_dump(GF_Box *a, FILE * trace)
{
GF_RTPBox *p = (GF_RTPBox *)a;
gf_isom_box_dump_start(a, "RTPMovieHintInformationBox", trace);
fprintf(trace, "descriptionformat=\"%s\">\n", gf_4cc_to_str(p->subType));
if (p->sdpText)
fprintf(trace, "<!-- sdp text: %s -->\n", p->sdpText);
gf_isom_box_dump_done("RTPMovieHintInformationBox", a, trace);
return GF_OK;
}
GF_Err rtpo_dump(GF_Box *a, FILE * trace)
{
GF_RTPOBox *p;
p = (GF_RTPOBox *)a;
gf_isom_box_dump_start(a, "RTPTimeOffsetBox", trace);
fprintf(trace, "PacketTimeOffset=\"%d\">\n", p->timeOffset);
gf_isom_box_dump_done("RTPTimeOffsetBox", a, trace);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
GF_Err mvex_dump(GF_Box *a, FILE * trace)
{
GF_MovieExtendsBox *p;
p = (GF_MovieExtendsBox *)a;
gf_isom_box_dump_start(a, "MovieExtendsBox", trace);
fprintf(trace, ">\n");
if (p->mehd) gf_isom_box_dump(p->mehd, trace);
gf_isom_box_array_dump(p->TrackExList, trace);
gf_isom_box_array_dump(p->TrackExPropList, trace);
gf_isom_box_dump_done("MovieExtendsBox", a, trace);
return GF_OK;
}
GF_Err mehd_dump(GF_Box *a, FILE * trace)
{
GF_MovieExtendsHeaderBox *p = (GF_MovieExtendsHeaderBox*)a;
gf_isom_box_dump_start(a, "MovieExtendsHeaderBox", trace);
fprintf(trace, "fragmentDuration=\""LLD"\" >\n", LLD_CAST p->fragment_duration);
gf_isom_box_dump_done("MovieExtendsHeaderBox", a, trace);
return GF_OK;
}
void sample_flags_dump(const char *name, u32 sample_flags, FILE * trace)
{
fprintf(trace, "<%s", name);
fprintf(trace, " IsLeading=\"%d\"", GF_ISOM_GET_FRAG_LEAD(sample_flags) );
fprintf(trace, " SampleDependsOn=\"%d\"", GF_ISOM_GET_FRAG_DEPENDS(sample_flags) );
fprintf(trace, " SampleIsDependedOn=\"%d\"", GF_ISOM_GET_FRAG_DEPENDED(sample_flags) );
fprintf(trace, " SampleHasRedundancy=\"%d\"", GF_ISOM_GET_FRAG_REDUNDANT(sample_flags) );
fprintf(trace, " SamplePadding=\"%d\"", GF_ISOM_GET_FRAG_PAD(sample_flags) );
fprintf(trace, " SampleSync=\"%d\"", GF_ISOM_GET_FRAG_SYNC(sample_flags));
fprintf(trace, " SampleDegradationPriority=\"%d\"", GF_ISOM_GET_FRAG_DEG(sample_flags));
fprintf(trace, "/>\n");
}
GF_Err trex_dump(GF_Box *a, FILE * trace)
{
GF_TrackExtendsBox *p;
p = (GF_TrackExtendsBox *)a;
gf_isom_box_dump_start(a, "TrackExtendsBox", trace);
fprintf(trace, "TrackID=\"%d\"", p->trackID);
fprintf(trace, " SampleDescriptionIndex=\"%d\" SampleDuration=\"%d\" SampleSize=\"%d\"", p->def_sample_desc_index, p->def_sample_duration, p->def_sample_size);
fprintf(trace, ">\n");
sample_flags_dump("DefaultSampleFlags", p->def_sample_flags, trace);
gf_isom_box_dump_done("TrackExtendsBox", a, trace);
return GF_OK;
}
GF_Err trep_dump(GF_Box *a, FILE * trace)
{
GF_TrackExtensionPropertiesBox *p = (GF_TrackExtensionPropertiesBox*)a;
gf_isom_box_dump_start(a, "TrackExtensionPropertiesBox", trace);
fprintf(trace, "TrackID=\"%d\">\n", p->trackID);
gf_isom_box_dump_done("TrackExtensionPropertiesBox", a, trace);
return GF_OK;
}
GF_Err moof_dump(GF_Box *a, FILE * trace)
{
GF_MovieFragmentBox *p;
p = (GF_MovieFragmentBox *)a;
gf_isom_box_dump_start(a, "MovieFragmentBox", trace);
fprintf(trace, "TrackFragments=\"%d\">\n", gf_list_count(p->TrackList));
if (p->mfhd) gf_isom_box_dump(p->mfhd, trace);
gf_isom_box_array_dump(p->TrackList, trace);
gf_isom_box_dump_done("MovieFragmentBox", a, trace);
return GF_OK;
}
GF_Err mfhd_dump(GF_Box *a, FILE * trace)
{
GF_MovieFragmentHeaderBox *p;
p = (GF_MovieFragmentHeaderBox *)a;
gf_isom_box_dump_start(a, "MovieFragmentHeaderBox", trace);
fprintf(trace, "FragmentSequenceNumber=\"%d\">\n", p->sequence_number);
gf_isom_box_dump_done("MovieFragmentHeaderBox", a, trace);
return GF_OK;
}
GF_Err traf_dump(GF_Box *a, FILE * trace)
{
GF_TrackFragmentBox *p;
p = (GF_TrackFragmentBox *)a;
gf_isom_box_dump_start(a, "TrackFragmentBox", trace);
fprintf(trace, ">\n");
if (p->tfhd) gf_isom_box_dump(p->tfhd, trace);
if (p->sdtp) gf_isom_box_dump(p->sdtp, trace);
if (p->tfdt) gf_isom_box_dump(p->tfdt, trace);
if (p->sub_samples) gf_isom_box_array_dump(p->sub_samples, trace);
if (p->sampleGroupsDescription) gf_isom_box_array_dump(p->sampleGroupsDescription, trace);
if (p->sampleGroups) gf_isom_box_array_dump(p->sampleGroups, trace);
gf_isom_box_array_dump(p->TrackRuns, trace);
if (p->sai_sizes) gf_isom_box_array_dump(p->sai_sizes, trace);
if (p->sai_offsets) gf_isom_box_array_dump(p->sai_offsets, trace);
if (p->sample_encryption) gf_isom_box_dump(p->sample_encryption, trace);
gf_isom_box_dump_done("TrackFragmentBox", a, trace);
return GF_OK;
}
static void frag_dump_sample_flags(FILE * trace, u32 flags)
{
fprintf(trace, " SamplePadding=\"%d\" Sync=\"%d\" DegradationPriority=\"%d\" IsLeading=\"%d\" DependsOn=\"%d\" IsDependedOn=\"%d\" HasRedundancy=\"%d\"",
GF_ISOM_GET_FRAG_PAD(flags), GF_ISOM_GET_FRAG_SYNC(flags), GF_ISOM_GET_FRAG_DEG(flags),
GF_ISOM_GET_FRAG_LEAD(flags), GF_ISOM_GET_FRAG_DEPENDS(flags), GF_ISOM_GET_FRAG_DEPENDED(flags), GF_ISOM_GET_FRAG_REDUNDANT(flags));
}
GF_Err tfhd_dump(GF_Box *a, FILE * trace)
{
GF_TrackFragmentHeaderBox *p;
p = (GF_TrackFragmentHeaderBox *)a;
gf_isom_box_dump_start(a, "TrackFragmentHeaderBox", trace);
fprintf(trace, "TrackID=\"%u\"", p->trackID);
if (p->flags & GF_ISOM_TRAF_BASE_OFFSET) {
fprintf(trace, " BaseDataOffset=\""LLU"\"", p->base_data_offset);
} else {
fprintf(trace, " BaseDataOffset=\"%s\"", (p->flags & GF_ISOM_MOOF_BASE_OFFSET) ? "moof" : "moof-or-previous-traf");
}
if (p->flags & GF_ISOM_TRAF_SAMPLE_DESC)
fprintf(trace, " SampleDescriptionIndex=\"%u\"", p->sample_desc_index);
if (p->flags & GF_ISOM_TRAF_SAMPLE_DUR)
fprintf(trace, " SampleDuration=\"%u\"", p->def_sample_duration);
if (p->flags & GF_ISOM_TRAF_SAMPLE_SIZE)
fprintf(trace, " SampleSize=\"%u\"", p->def_sample_size);
if (p->flags & GF_ISOM_TRAF_SAMPLE_FLAGS) {
frag_dump_sample_flags(trace, p->def_sample_flags);
}
fprintf(trace, ">\n");
gf_isom_box_dump_done("TrackFragmentHeaderBox", a, trace);
return GF_OK;
}
GF_Err tfxd_dump(GF_Box *a, FILE * trace)
{
GF_MSSTimeExtBox *ptr = (GF_MSSTimeExtBox*)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "MSSTimeExtensionBox", trace);
fprintf(trace, "AbsoluteTime=\""LLU"\" FragmentDuration=\""LLU"\">\n", ptr->absolute_time_in_track_timescale, ptr->fragment_duration_in_track_timescale);
fprintf(trace, "<FullBoxInfo Version=\"%d\" Flags=\"%d\"/>\n", ptr->version, ptr->flags);
gf_isom_box_dump_done("MSSTimeExtensionBox", a, trace);
return GF_OK;
}
GF_Err trun_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_TrunEntry *ent;
GF_TrackFragmentRunBox *p;
p = (GF_TrackFragmentRunBox *)a;
gf_isom_box_dump_start(a, "TrackRunBox", trace);
fprintf(trace, "SampleCount=\"%d\"", p->sample_count);
if (p->flags & GF_ISOM_TRUN_DATA_OFFSET)
fprintf(trace, " DataOffset=\"%d\"", p->data_offset);
fprintf(trace, ">\n");
if (p->flags & GF_ISOM_TRUN_FIRST_FLAG) {
sample_flags_dump("FirstSampleFlags", p->first_sample_flags, trace);
}
if (p->flags & (GF_ISOM_TRUN_DURATION|GF_ISOM_TRUN_SIZE|GF_ISOM_TRUN_CTS_OFFSET|GF_ISOM_TRUN_FLAGS)) {
i=0;
while ((ent = (GF_TrunEntry *)gf_list_enum(p->entries, &i))) {
fprintf(trace, "<TrackRunEntry");
if (p->flags & GF_ISOM_TRUN_DURATION)
fprintf(trace, " Duration=\"%u\"", ent->Duration);
if (p->flags & GF_ISOM_TRUN_SIZE)
fprintf(trace, " Size=\"%u\"", ent->size);
if (p->flags & GF_ISOM_TRUN_CTS_OFFSET)
{
if (p->version == 0)
fprintf(trace, " CTSOffset=\"%u\"", (u32) ent->CTS_Offset);
else
fprintf(trace, " CTSOffset=\"%d\"", ent->CTS_Offset);
}
if (p->flags & GF_ISOM_TRUN_FLAGS) {
frag_dump_sample_flags(trace, ent->flags);
}
fprintf(trace, "/>\n");
}
} else if (p->size) {
fprintf(trace, "<!-- all default values used -->\n");
} else {
fprintf(trace, "<TrackRunEntry Duration=\"\" Size=\"\" CTSOffset=\"\"");
frag_dump_sample_flags(trace, 0);
fprintf(trace, "/>\n");
}
gf_isom_box_dump_done("TrackRunBox", a, trace);
return GF_OK;
}
#endif
#ifndef GPAC_DISABLE_ISOM_HINTING
GF_Err DTE_Dump(GF_List *dte, FILE * trace)
{
GF_GenericDTE *p;
GF_ImmediateDTE *i_p;
GF_SampleDTE *s_p;
GF_StreamDescDTE *sd_p;
u32 i, count;
count = gf_list_count(dte);
for (i=0; i<count; i++) {
p = (GF_GenericDTE *)gf_list_get(dte, i);
switch (p->source) {
case 0:
fprintf(trace, "<EmptyDataEntry/>\n");
break;
case 1:
i_p = (GF_ImmediateDTE *) p;
fprintf(trace, "<ImmediateDataEntry DataSize=\"%d\"/>\n", i_p->dataLength);
break;
case 2:
s_p = (GF_SampleDTE *) p;
fprintf(trace, "<SampleDataEntry DataSize=\"%d\" SampleOffset=\"%d\" SampleNumber=\"%d\" TrackReference=\"%d\"/>\n",
s_p->dataLength, s_p->byteOffset, s_p->sampleNumber, s_p->trackRefIndex);
break;
case 3:
sd_p = (GF_StreamDescDTE *) p;
fprintf(trace, "<SampleDescriptionEntry DataSize=\"%d\" DescriptionOffset=\"%d\" StreamDescriptionindex=\"%d\" TrackReference=\"%d\"/>\n",
sd_p->dataLength, sd_p->byteOffset, sd_p->streamDescIndex, sd_p->trackRefIndex);
break;
default:
fprintf(trace, "<UnknownTableEntry/>\n");
break;
}
}
return GF_OK;
}
GF_EXPORT
GF_Err gf_isom_dump_hint_sample(GF_ISOFile *the_file, u32 trackNumber, u32 SampleNum, FILE * trace)
{
GF_ISOSample *tmp;
GF_HintSampleEntryBox *entry;
u32 descIndex, count, count2, i;
GF_Err e=GF_OK;
GF_BitStream *bs;
GF_HintSample *s;
GF_TrackBox *trak;
GF_RTPPacket *pck;
char *szName;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !IsHintTrack(trak)) return GF_BAD_PARAM;
tmp = gf_isom_get_sample(the_file, trackNumber, SampleNum, &descIndex);
if (!tmp) return GF_BAD_PARAM;
e = Media_GetSampleDesc(trak->Media, descIndex, (GF_SampleEntryBox **) &entry, &count);
if (e) {
gf_isom_sample_del(&tmp);
return e;
}
//check we can read the sample
switch (entry->type) {
case GF_ISOM_BOX_TYPE_RTP_STSD:
case GF_ISOM_BOX_TYPE_SRTP_STSD:
case GF_ISOM_BOX_TYPE_RRTP_STSD:
szName = "RTP";
break;
case GF_ISOM_BOX_TYPE_RTCP_STSD:
szName = "RCTP";
break;
case GF_ISOM_BOX_TYPE_FDP_STSD:
szName = "FDP";
break;
default:
gf_isom_sample_del(&tmp);
return GF_NOT_SUPPORTED;
}
bs = gf_bs_new(tmp->data, tmp->dataLength, GF_BITSTREAM_READ);
s = gf_isom_hint_sample_new(entry->type);
s->trackID = trak->Header->trackID;
s->sampleNumber = SampleNum;
gf_isom_hint_sample_read(s, bs, tmp->dataLength);
gf_bs_del(bs);
count = gf_list_count(s->packetTable);
fprintf(trace, "<%sHintSample SampleNumber=\"%d\" DecodingTime=\""LLD"\" RandomAccessPoint=\"%d\" PacketCount=\"%u\" reserved=\"%u\">\n", szName, SampleNum, LLD_CAST tmp->DTS, tmp->IsRAP, s->packetCount, s->reserved);
if (s->hint_subtype==GF_ISOM_BOX_TYPE_FDP_STSD) {
e = gf_isom_box_dump((GF_Box*) s, trace);
goto err_exit;
}
if (s->packetCount != count) {
fprintf(trace, "<!-- WARNING: Broken %s hint sample, %d entries indicated but only %d parsed -->\n", szName, s->packetCount, count);
}
for (i=0; i<count; i++) {
pck = (GF_RTPPacket *)gf_list_get(s->packetTable, i);
if (pck->hint_subtype==GF_ISOM_BOX_TYPE_RTCP_STSD) {
GF_RTCPPacket *rtcp_pck = (GF_RTCPPacket *) pck;
fprintf(trace, "<RTCPHintPacket PacketNumber=\"%d\" V=\"%d\" P=\"%d\" Count=\"%d\" PayloadType=\"%d\" ",
i+1, rtcp_pck->Version, rtcp_pck->Padding, rtcp_pck->Count, rtcp_pck->PayloadType);
if (rtcp_pck->data) dump_data_attribute(trace, "payload", (char*)rtcp_pck->data, rtcp_pck->length);
fprintf(trace, ">\n");
fprintf(trace, "</RTCPHintPacket>\n");
} else {
fprintf(trace, "<RTPHintPacket PacketNumber=\"%d\" P=\"%d\" X=\"%d\" M=\"%d\" PayloadType=\"%d\"",
i+1, pck->P_bit, pck->X_bit, pck->M_bit, pck->payloadType);
fprintf(trace, " SequenceNumber=\"%d\" RepeatedPacket=\"%d\" DropablePacket=\"%d\" RelativeTransmissionTime=\"%d\" FullPacketSize=\"%d\">\n",
pck->SequenceNumber, pck->R_bit, pck->B_bit, pck->relativeTransTime, gf_isom_hint_rtp_length(pck));
//TLV is made of Boxes
count2 = gf_list_count(pck->TLV);
if (count2) {
fprintf(trace, "<PrivateExtensionTable EntryCount=\"%d\">\n", count2);
gf_isom_box_array_dump(pck->TLV, trace);
fprintf(trace, "</PrivateExtensionTable>\n");
}
//DTE is made of NON boxes
count2 = gf_list_count(pck->DataTable);
if (count2) {
fprintf(trace, "<PacketDataTable EntryCount=\"%d\">\n", count2);
DTE_Dump(pck->DataTable, trace);
fprintf(trace, "</PacketDataTable>\n");
}
fprintf(trace, "</RTPHintPacket>\n");
}
}
err_exit:
fprintf(trace, "</%sHintSample>\n", szName);
gf_isom_sample_del(&tmp);
gf_isom_hint_sample_del(s);
return e;
}
#endif /*GPAC_DISABLE_ISOM_HINTING*/
static void tx3g_dump_box_nobox(FILE * trace, GF_BoxRecord *rec)
{
fprintf(trace, "<TextBox top=\"%d\" left=\"%d\" bottom=\"%d\" right=\"%d\"/>\n", rec->top, rec->left, rec->bottom, rec->right);
}
static void tx3g_print_char_offsets(FILE * trace, u32 start, u32 end, u32 *shift_offset, u32 so_count)
{
u32 i;
if (shift_offset) {
for (i=0; i<so_count; i++) {
if (start>shift_offset[i]) {
start --;
break;
}
}
for (i=0; i<so_count; i++) {
if (end>shift_offset[i]) {
end --;
break;
}
}
}
if (start || end) fprintf(trace, "fromChar=\"%d\" toChar=\"%d\" ", start, end);
}
static void tx3g_dump_style_nobox(FILE * trace, GF_StyleRecord *rec, u32 *shift_offset, u32 so_count)
{
fprintf(trace, "<Style ");
if (rec->startCharOffset || rec->endCharOffset)
tx3g_print_char_offsets(trace, rec->startCharOffset, rec->endCharOffset, shift_offset, so_count);
fprintf(trace, "styles=\"");
if (!rec->style_flags) {
fprintf(trace, "Normal");
} else {
if (rec->style_flags & 1) fprintf(trace, "Bold ");
if (rec->style_flags & 2) fprintf(trace, "Italic ");
if (rec->style_flags & 4) fprintf(trace, "Underlined ");
}
fprintf(trace, "\" fontID=\"%d\" fontSize=\"%d\" ", rec->fontID, rec->font_size);
tx3g_dump_rgba8(trace, "color", rec->text_color);
fprintf(trace, "/>\n");
}
static char *tx3g_format_time(u64 ts, u32 timescale, char *szDur, Bool is_srt)
{
u32 h, m, s, ms;
ts = (u32) (ts*1000 / timescale);
h = (u32) (ts / 3600000);
m = (u32) (ts/ 60000) - h*60;
s = (u32) (ts/1000) - h*3600 - m*60;
ms = (u32) (ts) - h*3600000 - m*60000 - s*1000;
if (is_srt) {
sprintf(szDur, "%02d:%02d:%02d,%03d", h, m, s, ms);
} else {
sprintf(szDur, "%02d:%02d:%02d.%03d", h, m, s, ms);
}
return szDur;
}
static GF_Err gf_isom_dump_ttxt_track(GF_ISOFile *the_file, u32 track, FILE *dump, Bool box_dump)
{
u32 i, j, count, di, nb_descs, shift_offset[20], so_count;
u64 last_DTS;
size_t len;
GF_Box *a;
Bool has_scroll;
char szDur[100];
GF_Tx3gSampleEntryBox *txt;
GF_TrackBox *trak = gf_isom_get_track_from_file(the_file, track);
if (!trak) return GF_BAD_PARAM;
switch (trak->Media->handler->handlerType) {
case GF_ISOM_MEDIA_TEXT:
case GF_ISOM_MEDIA_SUBT:
break;
default:
return GF_BAD_PARAM;
}
txt = (GF_Tx3gSampleEntryBox *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, 0);
switch (txt->type) {
case GF_ISOM_BOX_TYPE_TX3G:
case GF_ISOM_BOX_TYPE_TEXT:
break;
case GF_ISOM_BOX_TYPE_STPP:
case GF_ISOM_BOX_TYPE_SBTT:
default:
return GF_BAD_PARAM;
}
if (box_dump) {
fprintf(dump, "<TextTrack trackID=\"%d\" version=\"1.1\">\n", gf_isom_get_track_id(the_file, track) );
} else {
fprintf(dump, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
fprintf(dump, "<!-- GPAC 3GPP Text Stream -->\n");
fprintf(dump, "<TextStream version=\"1.1\">\n");
}
fprintf(dump, "<TextStreamHeader width=\"%d\" height=\"%d\" layer=\"%d\" translation_x=\"%d\" translation_y=\"%d\">\n", trak->Header->width >> 16 , trak->Header->height >> 16, trak->Header->layer, trak->Header->matrix[6] >> 16, trak->Header->matrix[7] >> 16);
nb_descs = gf_list_count(trak->Media->information->sampleTable->SampleDescription->other_boxes);
for (i=0; i<nb_descs; i++) {
GF_Tx3gSampleEntryBox *txt = (GF_Tx3gSampleEntryBox *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, i);
if (box_dump) {
gf_isom_box_dump((GF_Box*) txt, dump);
} else if (txt->type==GF_ISOM_BOX_TYPE_TX3G) {
fprintf(dump, "<TextSampleDescription horizontalJustification=\"");
switch (txt->horizontal_justification) {
case 1:
fprintf(dump, "center");
break;
case -1:
fprintf(dump, "right");
break;
default:
fprintf(dump, "left");
break;
}
fprintf(dump, "\" verticalJustification=\"");
switch (txt->vertical_justification) {
case 1:
fprintf(dump, "center");
break;
case -1:
fprintf(dump, "bottom");
break;
default:
fprintf(dump, "top");
break;
}
fprintf(dump, "\" ");
tx3g_dump_rgba8(dump, "backColor", txt->back_color);
fprintf(dump, " verticalText=\"%s\"", (txt->displayFlags & GF_TXT_VERTICAL) ? "yes" : "no");
fprintf(dump, " fillTextRegion=\"%s\"", (txt->displayFlags & GF_TXT_FILL_REGION) ? "yes" : "no");
fprintf(dump, " continuousKaraoke=\"%s\"", (txt->displayFlags & GF_TXT_KARAOKE) ? "yes" : "no");
has_scroll = GF_FALSE;
if (txt->displayFlags & GF_TXT_SCROLL_IN) {
has_scroll = GF_TRUE;
if (txt->displayFlags & GF_TXT_SCROLL_OUT) fprintf(dump, " scroll=\"InOut\"");
else fprintf(dump, " scroll=\"In\"");
} else if (txt->displayFlags & GF_TXT_SCROLL_OUT) {
has_scroll = GF_TRUE;
fprintf(dump, " scroll=\"Out\"");
} else {
fprintf(dump, " scroll=\"None\"");
}
if (has_scroll) {
u32 mode = (txt->displayFlags & GF_TXT_SCROLL_DIRECTION)>>7;
switch (mode) {
case GF_TXT_SCROLL_CREDITS:
fprintf(dump, " scrollMode=\"Credits\"");
break;
case GF_TXT_SCROLL_MARQUEE:
fprintf(dump, " scrollMode=\"Marquee\"");
break;
case GF_TXT_SCROLL_DOWN:
fprintf(dump, " scrollMode=\"Down\"");
break;
case GF_TXT_SCROLL_RIGHT:
fprintf(dump, " scrollMode=\"Right\"");
break;
default:
fprintf(dump, " scrollMode=\"Unknown\"");
break;
}
}
fprintf(dump, ">\n");
fprintf(dump, "<FontTable>\n");
if (txt->font_table) {
for (j=0; j<txt->font_table->entry_count; j++) {
fprintf(dump, "<FontTableEntry fontName=\"%s\" fontID=\"%d\"/>\n", txt->font_table->fonts[j].fontName, txt->font_table->fonts[j].fontID);
}
}
fprintf(dump, "</FontTable>\n");
if ((txt->default_box.bottom == txt->default_box.top) || (txt->default_box.right == txt->default_box.left)) {
txt->default_box.top = txt->default_box.left = 0;
txt->default_box.right = trak->Header->width / 65536;
txt->default_box.bottom = trak->Header->height / 65536;
}
tx3g_dump_box_nobox(dump, &txt->default_box);
tx3g_dump_style_nobox(dump, &txt->default_style, NULL, 0);
fprintf(dump, "</TextSampleDescription>\n");
} else {
GF_TextSampleEntryBox *text = (GF_TextSampleEntryBox *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, i);
fprintf(dump, "<TextSampleDescription horizontalJustification=\"");
switch (text->textJustification) {
case 1:
fprintf(dump, "center");
break;
case -1:
fprintf(dump, "right");
break;
default:
fprintf(dump, "left");
break;
}
fprintf(dump, "\"");
tx3g_dump_rgb16(dump, " backColor", text->background_color);
if ((text->default_box.bottom == text->default_box.top) || (text->default_box.right == text->default_box.left)) {
text->default_box.top = text->default_box.left = 0;
text->default_box.right = trak->Header->width / 65536;
text->default_box.bottom = trak->Header->height / 65536;
}
if (text->displayFlags & GF_TXT_SCROLL_IN) {
if (text->displayFlags & GF_TXT_SCROLL_OUT) fprintf(dump, " scroll=\"InOut\"");
else fprintf(dump, " scroll=\"In\"");
} else if (text->displayFlags & GF_TXT_SCROLL_OUT) {
fprintf(dump, " scroll=\"Out\"");
} else {
fprintf(dump, " scroll=\"None\"");
}
fprintf(dump, ">\n");
tx3g_dump_box_nobox(dump, &text->default_box);
fprintf(dump, "</TextSampleDescription>\n");
}
}
fprintf(dump, "</TextStreamHeader>\n");
last_DTS = 0;
count = gf_isom_get_sample_count(the_file, track);
for (i=0; i<count; i++) {
GF_BitStream *bs;
GF_TextSample *txt;
GF_ISOSample *s = gf_isom_get_sample(the_file, track, i+1, &di);
if (!s) continue;
fprintf(dump, "<TextSample sampleTime=\"%s\" sampleDescriptionIndex=\"%d\"", tx3g_format_time(s->DTS, trak->Media->mediaHeader->timeScale, szDur, GF_FALSE), di);
bs = gf_bs_new(s->data, s->dataLength, GF_BITSTREAM_READ);
txt = gf_isom_parse_texte_sample(bs);
gf_bs_del(bs);
if (!box_dump) {
if (txt->highlight_color) {
fprintf(dump, " ");
tx3g_dump_rgba8(dump, "highlightColor", txt->highlight_color->hil_color);
}
if (txt->scroll_delay) {
Double delay = txt->scroll_delay->scroll_delay;
delay /= trak->Media->mediaHeader->timeScale;
fprintf(dump, " scrollDelay=\"%g\"", delay);
}
if (txt->wrap) fprintf(dump, " wrap=\"%s\"", (txt->wrap->wrap_flag==0x01) ? "Automatic" : "None");
}
so_count = 0;
fprintf(dump, " xml:space=\"preserve\">");
if (!txt->len) {
last_DTS = (u32) trak->Media->mediaHeader->duration;
} else {
unsigned short utf16Line[10000];
last_DTS = s->DTS;
/*UTF16*/
if ((txt->len>2) && ((unsigned char) txt->text[0] == (unsigned char) 0xFE) && ((unsigned char) txt->text[1] == (unsigned char) 0xFF)) {
/*copy 2 more chars because the lib always add 2 '0' at the end for UTF16 end of string*/
memcpy((char *) utf16Line, txt->text+2, sizeof(char) * (txt->len));
len = gf_utf8_wcslen((const u16*)utf16Line);
} else {
char *str;
str = txt->text;
len = gf_utf8_mbstowcs((u16*)utf16Line, 10000, (const char **) &str);
}
if (len != (size_t) -1) {
utf16Line[len] = 0;
for (j=0; j<len; j++) {
if ((utf16Line[j]=='\n') || (utf16Line[j]=='\r') || (utf16Line[j]==0x85) || (utf16Line[j]==0x2028) || (utf16Line[j]==0x2029) ) {
fprintf(dump, "\n");
if ((utf16Line[j]=='\r') && (utf16Line[j+1]=='\n')) {
shift_offset[so_count] = j;
so_count++;
j++;
}
}
else {
switch (utf16Line[j]) {
case '\'':
fprintf(dump, "'");
break;
case '\"':
fprintf(dump, """);
break;
case '&':
fprintf(dump, "&");
break;
case '>':
fprintf(dump, ">");
break;
case '<':
fprintf(dump, "<");
break;
default:
if (utf16Line[j] < 128) {
fprintf(dump, "%c", (u8) utf16Line[j]);
} else {
fprintf(dump, "&#%d;", utf16Line[j]);
}
break;
}
}
}
}
}
if (box_dump) {
if (txt->highlight_color)
gf_isom_box_dump((GF_Box*) txt->highlight_color, dump);
if (txt->scroll_delay)
gf_isom_box_dump((GF_Box*) txt->scroll_delay, dump);
if (txt->wrap)
gf_isom_box_dump((GF_Box*) txt->wrap, dump);
if (txt->box)
gf_isom_box_dump((GF_Box*) txt->box, dump);
if (txt->styles)
gf_isom_box_dump((GF_Box*) txt->styles, dump);
} else {
if (txt->box) tx3g_dump_box_nobox(dump, &txt->box->box);
if (txt->styles) {
for (j=0; j<txt->styles->entry_count; j++) {
tx3g_dump_style_nobox(dump, &txt->styles->styles[j], shift_offset, so_count);
}
}
}
j=0;
while ((a = (GF_Box *)gf_list_enum(txt->others, &j))) {
if (box_dump) {
gf_isom_box_dump((GF_Box*) a, dump);
continue;
}
switch (a->type) {
case GF_ISOM_BOX_TYPE_HLIT:
fprintf(dump, "<Highlight ");
tx3g_print_char_offsets(dump, ((GF_TextHighlightBox *)a)->startcharoffset, ((GF_TextHighlightBox *)a)->endcharoffset, shift_offset, so_count);
fprintf(dump, "/>\n");
break;
case GF_ISOM_BOX_TYPE_HREF:
{
GF_TextHyperTextBox *ht = (GF_TextHyperTextBox *)a;
fprintf(dump, "<HyperLink ");
tx3g_print_char_offsets(dump, ht->startcharoffset, ht->endcharoffset, shift_offset, so_count);
fprintf(dump, "URL=\"%s\" URLToolTip=\"%s\"/>\n", ht->URL ? ht->URL : "", ht->URL_hint ? ht->URL_hint : "");
}
break;
case GF_ISOM_BOX_TYPE_BLNK:
fprintf(dump, "<Blinking ");
tx3g_print_char_offsets(dump, ((GF_TextBlinkBox *)a)->startcharoffset, ((GF_TextBlinkBox *)a)->endcharoffset, shift_offset, so_count);
fprintf(dump, "/>\n");
break;
case GF_ISOM_BOX_TYPE_KROK:
{
u32 k;
Double t;
GF_TextKaraokeBox *krok = (GF_TextKaraokeBox *)a;
t = krok->highlight_starttime;
t /= trak->Media->mediaHeader->timeScale;
fprintf(dump, "<Karaoke startTime=\"%g\">\n", t);
for (k=0; k<krok->nb_entries; k++) {
t = krok->records[k].highlight_endtime;
t /= trak->Media->mediaHeader->timeScale;
fprintf(dump, "<KaraokeRange ");
tx3g_print_char_offsets(dump, krok->records[k].start_charoffset, krok->records[k].end_charoffset, shift_offset, so_count);
fprintf(dump, "endTime=\"%g\"/>\n", t);
}
fprintf(dump, "</Karaoke>\n");
}
break;
}
}
fprintf(dump, "</TextSample>\n");
gf_isom_sample_del(&s);
gf_isom_delete_text_sample(txt);
gf_set_progress("TTXT Extract", i, count);
}
if (last_DTS < trak->Media->mediaHeader->duration) {
fprintf(dump, "<TextSample sampleTime=\"%s\" text=\"\" />\n", tx3g_format_time(trak->Media->mediaHeader->duration, trak->Media->mediaHeader->timeScale, szDur, GF_FALSE));
}
if (box_dump) {
fprintf(dump, "</TextTrack>\n");
} else {
fprintf(dump, "</TextStream>\n");
}
if (count) gf_set_progress("TTXT Extract", count, count);
return GF_OK;
}
static GF_Err gf_isom_dump_srt_track(GF_ISOFile *the_file, u32 track, FILE *dump)
{
u32 i, j, k, count, di, len, ts, cur_frame;
u64 start, end;
GF_Tx3gSampleEntryBox *txtd;
GF_BitStream *bs;
char szDur[100];
GF_TrackBox *trak = gf_isom_get_track_from_file(the_file, track);
if (!trak) return GF_BAD_PARAM;
switch (trak->Media->handler->handlerType) {
case GF_ISOM_MEDIA_TEXT:
case GF_ISOM_MEDIA_SUBT:
break;
default:
return GF_BAD_PARAM;
}
ts = trak->Media->mediaHeader->timeScale;
cur_frame = 0;
end = 0;
count = gf_isom_get_sample_count(the_file, track);
for (i=0; i<count; i++) {
GF_TextSample *txt;
GF_ISOSample *s = gf_isom_get_sample(the_file, track, i+1, &di);
if (!s) continue;
start = s->DTS;
if (s->dataLength==2) {
gf_isom_sample_del(&s);
continue;
}
if (i+1<count) {
GF_ISOSample *next = gf_isom_get_sample_info(the_file, track, i+2, NULL, NULL);
if (next) {
end = next->DTS;
gf_isom_sample_del(&next);
}
} else {
end = gf_isom_get_media_duration(the_file, track) ;
}
cur_frame++;
fprintf(dump, "%d\n", cur_frame);
tx3g_format_time(start, ts, szDur, GF_TRUE);
fprintf(dump, "%s --> ", szDur);
tx3g_format_time(end, ts, szDur, GF_TRUE);
fprintf(dump, "%s\n", szDur);
bs = gf_bs_new(s->data, s->dataLength, GF_BITSTREAM_READ);
txt = gf_isom_parse_texte_sample(bs);
gf_bs_del(bs);
txtd = (GF_Tx3gSampleEntryBox *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, di-1);
if (!txt->len) {
fprintf(dump, "\n");
} else {
u32 styles, char_num, new_styles, color, new_color;
u16 utf16Line[10000];
/*UTF16*/
if ((txt->len>2) && ((unsigned char) txt->text[0] == (unsigned char) 0xFE) && ((unsigned char) txt->text[1] == (unsigned char) 0xFF)) {
memcpy(utf16Line, txt->text+2, sizeof(char)*txt->len);
( ((char *)utf16Line)[txt->len] ) = 0;
len = txt->len;
} else {
u8 *str = (u8 *) (txt->text);
size_t res = gf_utf8_mbstowcs(utf16Line, 10000, (const char **) &str);
if (res==(size_t)-1) return GF_NON_COMPLIANT_BITSTREAM;
len = (u32) res;
utf16Line[len] = 0;
}
char_num = 0;
styles = 0;
new_styles = txtd->default_style.style_flags;
color = new_color = txtd->default_style.text_color;
for (j=0; j<len; j++) {
Bool is_new_line;
if (txt->styles) {
new_styles = txtd->default_style.style_flags;
new_color = txtd->default_style.text_color;
for (k=0; k<txt->styles->entry_count; k++) {
if (txt->styles->styles[k].startCharOffset>char_num) continue;
if (txt->styles->styles[k].endCharOffset<char_num+1) continue;
if (txt->styles->styles[k].style_flags & (GF_TXT_STYLE_ITALIC | GF_TXT_STYLE_BOLD | GF_TXT_STYLE_UNDERLINED)) {
new_styles = txt->styles->styles[k].style_flags;
new_color = txt->styles->styles[k].text_color;
break;
}
}
}
if (new_styles != styles) {
if ((new_styles & GF_TXT_STYLE_BOLD) && !(styles & GF_TXT_STYLE_BOLD)) fprintf(dump, "<b>");
if ((new_styles & GF_TXT_STYLE_ITALIC) && !(styles & GF_TXT_STYLE_ITALIC)) fprintf(dump, "<i>");
if ((new_styles & GF_TXT_STYLE_UNDERLINED) && !(styles & GF_TXT_STYLE_UNDERLINED)) fprintf(dump, "<u>");
if ((styles & GF_TXT_STYLE_UNDERLINED) && !(new_styles & GF_TXT_STYLE_UNDERLINED)) fprintf(dump, "</u>");
if ((styles & GF_TXT_STYLE_ITALIC) && !(new_styles & GF_TXT_STYLE_ITALIC)) fprintf(dump, "</i>");
if ((styles & GF_TXT_STYLE_BOLD) && !(new_styles & GF_TXT_STYLE_BOLD)) fprintf(dump, "</b>");
styles = new_styles;
}
if (new_color != color) {
if (new_color ==txtd->default_style.text_color) {
fprintf(dump, "</font>");
} else {
fprintf(dump, "<font color=\"%s\">", gf_color_get_name(new_color) );
}
color = new_color;
}
/*not sure if styles must be reseted at line breaks in srt...*/
is_new_line = GF_FALSE;
if ((utf16Line[j]=='\n') || (utf16Line[j]=='\r') ) {
if ((utf16Line[j]=='\r') && (utf16Line[j+1]=='\n')) j++;
fprintf(dump, "\n");
is_new_line = GF_TRUE;
}
if (!is_new_line) {
size_t sl;
char szChar[30];
s16 swT[2], *swz;
swT[0] = utf16Line[j];
swT[1] = 0;
swz= (s16 *)swT;
sl = gf_utf8_wcstombs(szChar, 30, (const unsigned short **) &swz);
if (sl == (size_t)-1) sl=0;
szChar[(u32) sl]=0;
fprintf(dump, "%s", szChar);
}
char_num++;
}
new_styles = 0;
if (new_styles != styles) {
if (styles & GF_TXT_STYLE_UNDERLINED) fprintf(dump, "</u>");
if (styles & GF_TXT_STYLE_ITALIC) fprintf(dump, "</i>");
if (styles & GF_TXT_STYLE_BOLD) fprintf(dump, "</b>");
// styles = 0;
}
if (color != txtd->default_style.text_color) {
fprintf(dump, "</font>");
// color = txtd->default_style.text_color;
}
fprintf(dump, "\n");
}
gf_isom_sample_del(&s);
gf_isom_delete_text_sample(txt);
fprintf(dump, "\n");
gf_set_progress("SRT Extract", i, count);
}
if (count) gf_set_progress("SRT Extract", i, count);
return GF_OK;
}
static GF_Err gf_isom_dump_svg_track(GF_ISOFile *the_file, u32 track, FILE *dump)
{
char nhmlFileName[1024];
FILE *nhmlFile;
u32 i, count, di, ts, cur_frame;
u64 start, end;
GF_BitStream *bs;
GF_TrackBox *trak = gf_isom_get_track_from_file(the_file, track);
if (!trak) return GF_BAD_PARAM;
switch (trak->Media->handler->handlerType) {
case GF_ISOM_MEDIA_TEXT:
case GF_ISOM_MEDIA_SUBT:
break;
default:
return GF_BAD_PARAM;
}
strcpy(nhmlFileName, the_file->fileName);
strcat(nhmlFileName, ".nhml");
nhmlFile = gf_fopen(nhmlFileName, "wt");
fprintf(nhmlFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
fprintf(nhmlFile, "<NHNTStream streamType=\"3\" objectTypeIndication=\"10\" timeScale=\"%d\" baseMediaFile=\"file.svg\" inRootOD=\"yes\">\n", trak->Media->mediaHeader->timeScale);
fprintf(nhmlFile, "<NHNTSample isRAP=\"yes\" DTS=\"0\" xmlFrom=\"doc.start\" xmlTo=\"text_1.start\"/>\n");
ts = trak->Media->mediaHeader->timeScale;
cur_frame = 0;
end = 0;
fprintf(dump, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
fprintf(dump, "<svg version=\"1.2\" baseProfile=\"tiny\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"%d\" height=\"%d\" fill=\"black\">\n", trak->Header->width >> 16 , trak->Header->height >> 16);
fprintf(dump, "<g transform=\"translate(%d, %d)\" text-anchor=\"middle\">\n", (trak->Header->width >> 16)/2 , (trak->Header->height >> 16)/2);
count = gf_isom_get_sample_count(the_file, track);
for (i=0; i<count; i++) {
GF_TextSample *txt;
GF_ISOSample *s = gf_isom_get_sample(the_file, track, i+1, &di);
if (!s) continue;
start = s->DTS;
if (s->dataLength==2) {
gf_isom_sample_del(&s);
continue;
}
if (i+1<count) {
GF_ISOSample *next = gf_isom_get_sample_info(the_file, track, i+2, NULL, NULL);
if (next) {
end = next->DTS;
gf_isom_sample_del(&next);
}
}
cur_frame++;
bs = gf_bs_new(s->data, s->dataLength, GF_BITSTREAM_READ);
txt = gf_isom_parse_texte_sample(bs);
gf_bs_del(bs);
if (!txt->len) continue;
fprintf(dump, " <text id=\"text_%d\" display=\"none\">%s\n", cur_frame, txt->text);
fprintf(dump, " <set attributeName=\"display\" to=\"inline\" begin=\"%g\" end=\"%g\"/>\n", ((s64)start*1.0)/ts, ((s64)end*1.0)/ts);
fprintf(dump, " <discard begin=\"%g\"/>\n", ((s64)end*1.0)/ts);
fprintf(dump, " </text>\n");
gf_isom_sample_del(&s);
gf_isom_delete_text_sample(txt);
fprintf(dump, "\n");
gf_set_progress("SRT Extract", i, count);
if (i == count - 2) {
fprintf(nhmlFile, "<NHNTSample isRAP=\"no\" DTS=\"%f\" xmlFrom=\"text_%d.start\" xmlTo=\"doc.end\"/>\n", ((s64)start*1.0), cur_frame);
} else {
fprintf(nhmlFile, "<NHNTSample isRAP=\"no\" DTS=\"%f\" xmlFrom=\"text_%d.start\" xmlTo=\"text_%d.start\"/>\n", ((s64)start*1.0), cur_frame, cur_frame+1);
}
}
fprintf(dump, "</g>\n");
fprintf(dump, "</svg>\n");
fprintf(nhmlFile, "</NHNTStream>\n");
gf_fclose(nhmlFile);
if (count) gf_set_progress("SRT Extract", i, count);
return GF_OK;
}
GF_EXPORT
GF_Err gf_isom_text_dump(GF_ISOFile *the_file, u32 track, FILE *dump, GF_TextDumpType dump_type)
{
switch (dump_type) {
case GF_TEXTDUMPTYPE_SVG:
return gf_isom_dump_svg_track(the_file, track, dump);
case GF_TEXTDUMPTYPE_SRT:
return gf_isom_dump_srt_track(the_file, track, dump);
case GF_TEXTDUMPTYPE_TTXT:
case GF_TEXTDUMPTYPE_TTXT_BOXES:
return gf_isom_dump_ttxt_track(the_file, track, dump, (dump_type==GF_TEXTDUMPTYPE_TTXT_BOXES) ? GF_TRUE : GF_FALSE);
default:
return GF_BAD_PARAM;
}
}
/* ISMA 1.0 Encryption and Authentication V 1.0 dump */
GF_Err sinf_dump(GF_Box *a, FILE * trace)
{
GF_ProtectionSchemeInfoBox *p;
p = (GF_ProtectionSchemeInfoBox *)a;
gf_isom_box_dump_start(a, "ProtectionSchemeInfoBox", trace);
fprintf(trace, ">\n");
if (p->size)
gf_isom_box_dump_ex(p->original_format, trace, GF_ISOM_BOX_TYPE_FRMA);
if (p->size)
gf_isom_box_dump_ex(p->scheme_type, trace, GF_ISOM_BOX_TYPE_SCHM);
if (p->size)
gf_isom_box_dump_ex(p->info, trace, GF_ISOM_BOX_TYPE_SCHI);
gf_isom_box_dump_done("ProtectionSchemeInfoBox", a, trace);
return GF_OK;
}
GF_Err frma_dump(GF_Box *a, FILE * trace)
{
GF_OriginalFormatBox *p;
p = (GF_OriginalFormatBox *)a;
gf_isom_box_dump_start(a, "OriginalFormatBox", trace);
fprintf(trace, "data_format=\"%s\">\n", gf_4cc_to_str(p->data_format));
gf_isom_box_dump_done("OriginalFormatBox", a, trace);
return GF_OK;
}
GF_Err schm_dump(GF_Box *a, FILE * trace)
{
GF_SchemeTypeBox *p;
p = (GF_SchemeTypeBox *)a;
gf_isom_box_dump_start(a, "SchemeTypeBox", trace);
fprintf(trace, "scheme_type=\"%s\" scheme_version=\"%d\" ", gf_4cc_to_str(p->scheme_type), p->scheme_version);
if (p->URI) fprintf(trace, "scheme_uri=\"%s\"", p->URI);
fprintf(trace, ">\n");
gf_isom_box_dump_done("SchemeTypeBox", a, trace);
return GF_OK;
}
GF_Err schi_dump(GF_Box *a, FILE * trace)
{
GF_SchemeInformationBox *p;
p = (GF_SchemeInformationBox *)a;
gf_isom_box_dump_start(a, "SchemeInformationBox", trace);
fprintf(trace, ">\n");
if (p->ikms) gf_isom_box_dump(p->ikms, trace);
if (p->isfm) gf_isom_box_dump(p->isfm, trace);
if (p->islt) gf_isom_box_dump(p->islt, trace);
if (p->odkm) gf_isom_box_dump(p->odkm, trace);
if (p->tenc) gf_isom_box_dump(p->tenc, trace);
if (p->adkm) gf_isom_box_dump(p->adkm, trace);
gf_isom_box_dump_done("SchemeInformationBox", a, trace);
return GF_OK;
}
GF_Err iKMS_dump(GF_Box *a, FILE * trace)
{
GF_ISMAKMSBox *p;
p = (GF_ISMAKMSBox *)a;
gf_isom_box_dump_start(a, "KMSBox", trace);
fprintf(trace, "kms_URI=\"%s\">\n", p->URI);
gf_isom_box_dump_done("KMSBox", a, trace);
return GF_OK;
}
GF_Err iSFM_dump(GF_Box *a, FILE * trace)
{
GF_ISMASampleFormatBox *p;
const char *name = (a->type==GF_ISOM_BOX_TYPE_ISFM) ? "ISMASampleFormat" : "OMADRMAUFormatBox";
p = (GF_ISMASampleFormatBox *)a;
gf_isom_box_dump_start(a, name, trace);
fprintf(trace, "selective_encryption=\"%d\" key_indicator_length=\"%d\" IV_length=\"%d\">\n", p->selective_encryption, p->key_indicator_length, p->IV_length);
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
GF_Err iSLT_dump(GF_Box *a, FILE * trace)
{
GF_ISMACrypSaltBox *p = (GF_ISMACrypSaltBox *)a;
gf_isom_box_dump_start(a, "ISMACrypSaltBox", trace);
fprintf(trace, "salt=\""LLU"\">\n", p->salt);
gf_isom_box_dump_done("ISMACrypSaltBox", a, trace);
return GF_OK;
}
GF_EXPORT
GF_Err gf_isom_dump_ismacryp_protection(GF_ISOFile *the_file, u32 trackNumber, FILE * trace)
{
u32 i, count;
GF_SampleEntryBox *entry;
GF_Err e;
GF_TrackBox *trak;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak) return GF_BAD_PARAM;
fprintf(trace, "<ISMACrypSampleDescriptions>\n");
count = gf_isom_get_sample_description_count(the_file, trackNumber);
for (i=0; i<count; i++) {
e = Media_GetSampleDesc(trak->Media, i+1, (GF_SampleEntryBox **) &entry, NULL);
if (e) return e;
switch (entry->type) {
case GF_ISOM_BOX_TYPE_ENCA:
case GF_ISOM_BOX_TYPE_ENCV:
case GF_ISOM_BOX_TYPE_ENCT:
case GF_ISOM_BOX_TYPE_ENCS:
break;
default:
continue;
}
gf_isom_box_dump(entry, trace);
}
fprintf(trace, "</ISMACrypSampleDescriptions>\n");
return GF_OK;
}
GF_EXPORT
GF_Err gf_isom_dump_ismacryp_sample(GF_ISOFile *the_file, u32 trackNumber, u32 SampleNum, FILE * trace)
{
GF_ISOSample *samp;
GF_ISMASample *isma_samp;
u32 descIndex;
samp = gf_isom_get_sample(the_file, trackNumber, SampleNum, &descIndex);
if (!samp) return GF_BAD_PARAM;
isma_samp = gf_isom_get_ismacryp_sample(the_file, trackNumber, samp, descIndex);
if (!isma_samp) {
gf_isom_sample_del(&samp);
return GF_NOT_SUPPORTED;
}
fprintf(trace, "<ISMACrypSample SampleNumber=\"%d\" DataSize=\"%d\" CompositionTime=\""LLD"\" ", SampleNum, isma_samp->dataLength, LLD_CAST (samp->DTS+samp->CTS_Offset) );
if (samp->CTS_Offset) fprintf(trace, "DecodingTime=\""LLD"\" ", LLD_CAST samp->DTS);
if (gf_isom_has_sync_points(the_file, trackNumber)) fprintf(trace, "RandomAccessPoint=\"%s\" ", samp->IsRAP ? "Yes" : "No");
fprintf(trace, "IsEncrypted=\"%s\" ", (isma_samp->flags & GF_ISOM_ISMA_IS_ENCRYPTED) ? "Yes" : "No");
if (isma_samp->flags & GF_ISOM_ISMA_IS_ENCRYPTED) {
fprintf(trace, "IV=\""LLD"\" ", LLD_CAST isma_samp->IV);
if (isma_samp->key_indicator) dump_data_attribute(trace, "KeyIndicator", (char*)isma_samp->key_indicator, isma_samp->KI_length);
}
fprintf(trace, "/>\n");
gf_isom_sample_del(&samp);
gf_isom_ismacryp_delete_sample(isma_samp);
return GF_OK;
}
/* end of ISMA 1.0 Encryption and Authentication V 1.0 */
/* Apple extensions */
GF_Err ilst_item_dump(GF_Box *a, FILE * trace)
{
GF_BitStream *bs;
u32 val;
Bool no_dump = GF_FALSE;
char *name = "UnknownBox";
GF_ListItemBox *itune = (GF_ListItemBox *)a;
switch (itune->type) {
case GF_ISOM_BOX_TYPE_0xA9NAM:
name = "NameBox";
break;
case GF_ISOM_BOX_TYPE_0xA9CMT:
name = "CommentBox";
break;
case GF_ISOM_BOX_TYPE_0xA9DAY:
name = "CreatedBox";
break;
case GF_ISOM_BOX_TYPE_0xA9ART:
name = "ArtistBox";
break;
case GF_ISOM_BOX_TYPE_0xA9TRK:
name = "TrackBox";
break;
case GF_ISOM_BOX_TYPE_0xA9ALB:
name = "AlbumBox";
break;
case GF_ISOM_BOX_TYPE_0xA9COM:
name = "CompositorBox";
break;
case GF_ISOM_BOX_TYPE_0xA9WRT:
name = "WriterBox";
break;
case GF_ISOM_BOX_TYPE_0xA9TOO:
name = "ToolBox";
break;
case GF_ISOM_BOX_TYPE_0xA9CPY:
name = "CopyrightBox";
break;
case GF_ISOM_BOX_TYPE_0xA9DES:
name = "DescriptionBox";
break;
case GF_ISOM_BOX_TYPE_0xA9GEN:
case GF_ISOM_BOX_TYPE_GNRE:
name = "GenreBox";
break;
case GF_ISOM_BOX_TYPE_aART:
name = "AlbumArtistBox";
break;
case GF_ISOM_BOX_TYPE_PGAP:
name = "GapelessBox";
break;
case GF_ISOM_BOX_TYPE_DISK:
name = "DiskBox";
break;
case GF_ISOM_BOX_TYPE_TRKN:
name = "TrackNumberBox";
break;
case GF_ISOM_BOX_TYPE_TMPO:
name = "TempoBox";
break;
case GF_ISOM_BOX_TYPE_CPIL:
name = "CompilationBox";
break;
case GF_ISOM_BOX_TYPE_COVR:
name = "CoverArtBox";
no_dump = GF_TRUE;
break;
case GF_ISOM_BOX_TYPE_iTunesSpecificInfo:
name = "iTunesSpecificBox";
no_dump = GF_TRUE;
break;
case GF_ISOM_BOX_TYPE_0xA9GRP:
name = "GroupBox";
break;
case GF_ISOM_ITUNE_ENCODER:
name = "EncoderBox";
break;
}
gf_isom_box_dump_start(a, name, trace);
if (!no_dump) {
switch (itune->type) {
case GF_ISOM_BOX_TYPE_DISK:
case GF_ISOM_BOX_TYPE_TRKN:
bs = gf_bs_new(itune->data->data, itune->data->dataSize, GF_BITSTREAM_READ);
gf_bs_read_int(bs, 16);
val = gf_bs_read_int(bs, 16);
if (itune->type==GF_ISOM_BOX_TYPE_DISK) {
fprintf(trace, " DiskNumber=\"%d\" NbDisks=\"%d\" ", val, gf_bs_read_int(bs, 16) );
} else {
fprintf(trace, " TrackNumber=\"%d\" NbTracks=\"%d\" ", val, gf_bs_read_int(bs, 16) );
}
gf_bs_del(bs);
break;
case GF_ISOM_BOX_TYPE_TMPO:
bs = gf_bs_new(itune->data->data, itune->data->dataSize, GF_BITSTREAM_READ);
fprintf(trace, " BPM=\"%d\" ", gf_bs_read_int(bs, 16) );
gf_bs_del(bs);
break;
case GF_ISOM_BOX_TYPE_CPIL:
fprintf(trace, " IsCompilation=\"%s\" ", (itune->data && itune->data->data && itune->data->data[0]) ? "yes" : "no");
break;
case GF_ISOM_BOX_TYPE_PGAP:
fprintf(trace, " IsGapeless=\"%s\" ", (itune->data && itune->data->data && itune->data->data[0]) ? "yes" : "no");
break;
default:
if (strcmp(name, "UnknownBox") && itune->data && itune->data->data) {
fprintf(trace, " value=\"");
if (itune->data && itune->data->data[0]) {
dump_data_string(trace, itune->data->data, itune->data->dataSize);
} else {
dump_data(trace, itune->data->data, itune->data->dataSize);
}
fprintf(trace, "\" ");
}
break;
}
}
fprintf(trace, ">\n");
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_ADOBE
GF_Err abst_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_AdobeBootstrapInfoBox *p = (GF_AdobeBootstrapInfoBox*)a;
gf_isom_box_dump_start(a, "AdobeBootstrapBox", trace);
fprintf(trace, "BootstrapinfoVersion=\"%u\" Profile=\"%u\" Live=\"%u\" Update=\"%u\" TimeScale=\"%u\" CurrentMediaTime=\""LLU"\" SmpteTimeCodeOffset=\""LLU"\" ",
p->bootstrapinfo_version, p->profile, p->live, p->update, p->time_scale, p->current_media_time, p->smpte_time_code_offset);
if (p->movie_identifier)
fprintf(trace, "MovieIdentifier=\"%s\" ", p->movie_identifier);
if (p->drm_data)
fprintf(trace, "DrmData=\"%s\" ", p->drm_data);
if (p->meta_data)
fprintf(trace, "MetaData=\"%s\" ", p->meta_data);
fprintf(trace, ">\n");
for (i=0; i<p->server_entry_count; i++) {
char *str = (char*)gf_list_get(p->server_entry_table, i);
fprintf(trace, "<ServerEntry>%s</ServerEntry>\n", str);
}
for (i=0; i<p->quality_entry_count; i++) {
char *str = (char*)gf_list_get(p->quality_entry_table, i);
fprintf(trace, "<QualityEntry>%s</QualityEntry>\n", str);
}
for (i=0; i<p->segment_run_table_count; i++)
gf_isom_box_dump(gf_list_get(p->segment_run_table_entries, i), trace);
for (i=0; i<p->fragment_run_table_count; i++)
gf_isom_box_dump(gf_list_get(p->fragment_run_table_entries, i), trace);
gf_isom_box_dump_done("AdobeBootstrapBox", a, trace);
return GF_OK;
}
GF_Err afra_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_AdobeFragRandomAccessBox *p = (GF_AdobeFragRandomAccessBox*)a;
gf_isom_box_dump_start(a, "AdobeFragmentRandomAccessBox", trace);
fprintf(trace, "LongIDs=\"%u\" LongOffsets=\"%u\" TimeScale=\"%u\">\n", p->long_ids, p->long_offsets, p->time_scale);
for (i=0; i<p->entry_count; i++) {
GF_AfraEntry *ae = (GF_AfraEntry *)gf_list_get(p->local_access_entries, i);
fprintf(trace, "<LocalAccessEntry Time=\""LLU"\" Offset=\""LLU"\"/>\n", ae->time, ae->offset);
}
for (i=0; i<p->global_entry_count; i++) {
GF_GlobalAfraEntry *gae = (GF_GlobalAfraEntry *)gf_list_get(p->global_access_entries, i);
fprintf(trace, "<GlobalAccessEntry Time=\""LLU"\" Segment=\"%u\" Fragment=\"%u\" AfraOffset=\""LLU"\" OffsetFromAfra=\""LLU"\"/>\n",
gae->time, gae->segment, gae->fragment, gae->afra_offset, gae->offset_from_afra);
}
gf_isom_box_dump_done("AdobeFragmentRandomAccessBox", a, trace);
return GF_OK;
}
GF_Err afrt_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_AdobeFragmentRunTableBox *p = (GF_AdobeFragmentRunTableBox*)a;
gf_isom_box_dump_start(a, "AdobeFragmentRunTableBox", trace);
fprintf(trace, "TimeScale=\"%u\">\n", p->timescale);
for (i=0; i<p->quality_entry_count; i++) {
char *str = (char*)gf_list_get(p->quality_segment_url_modifiers, i);
fprintf(trace, "<QualityEntry>%s</QualityEntry>\n", str);
}
for (i=0; i<p->fragment_run_entry_count; i++) {
GF_AdobeFragmentRunEntry *fre = (GF_AdobeFragmentRunEntry *)gf_list_get(p->fragment_run_entry_table, i);
fprintf(trace, "<FragmentRunEntry FirstFragment=\"%u\" FirstFragmentTimestamp=\""LLU"\" FirstFragmentDuration=\"%u\"", fre->first_fragment, fre->first_fragment_timestamp, fre->fragment_duration);
if (!fre->fragment_duration)
fprintf(trace, " DiscontinuityIndicator=\"%u\"", fre->discontinuity_indicator);
fprintf(trace, "/>\n");
}
gf_isom_box_dump_done("AdobeFragmentRunTableBox", a, trace);
return GF_OK;
}
GF_Err asrt_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_AdobeSegmentRunTableBox *p = (GF_AdobeSegmentRunTableBox*)a;
gf_isom_box_dump_start(a, "AdobeSegmentRunTableBox", trace);
fprintf(trace, ">\n");
for (i=0; i<p->quality_entry_count; i++) {
char *str = (char*)gf_list_get(p->quality_segment_url_modifiers, i);
fprintf(trace, "<QualityEntry>%s</QualityEntry>\n", str);
}
for (i=0; i<p->segment_run_entry_count; i++) {
GF_AdobeSegmentRunEntry *sre = (GF_AdobeSegmentRunEntry *)gf_list_get(p->segment_run_entry_table, i);
fprintf(trace, "<SegmentRunEntry FirstSegment=\"%u\" FragmentsPerSegment=\"%u\"/>\n", sre->first_segment, sre->fragment_per_segment);
}
gf_isom_box_dump_done("AdobeSegmentRunTableBox", a, trace);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_ADOBE*/
GF_Err ilst_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_Box *tag;
GF_Err e;
GF_ItemListBox *ptr;
ptr = (GF_ItemListBox *)a;
gf_isom_box_dump_start(a, "ItemListBox", trace);
fprintf(trace, ">\n");
i=0;
while ( (tag = (GF_Box*)gf_list_enum(ptr->other_boxes, &i))) {
e = ilst_item_dump(tag, trace);
if(e) return e;
}
gf_isom_box_dump_done("ItemListBox", NULL, trace);
return GF_OK;
}
GF_Err databox_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "data", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("data", a, trace);
return GF_OK;
}
GF_Err ohdr_dump(GF_Box *a, FILE * trace)
{
GF_OMADRMCommonHeaderBox *ptr = (GF_OMADRMCommonHeaderBox *)a;
gf_isom_box_dump_start(a, "OMADRMCommonHeaderBox", trace);
fprintf(trace, "EncryptionMethod=\"%d\" PaddingScheme=\"%d\" PlaintextLength=\""LLD"\" ",
ptr->EncryptionMethod, ptr->PaddingScheme, ptr->PlaintextLength);
if (ptr->RightsIssuerURL) fprintf(trace, "RightsIssuerURL=\"%s\" ", ptr->RightsIssuerURL);
if (ptr->ContentID) fprintf(trace, "ContentID=\"%s\" ", ptr->ContentID);
if (ptr->TextualHeaders) {
u32 i, offset;
char *start = ptr->TextualHeaders;
fprintf(trace, "TextualHeaders=\"");
i=offset=0;
while (i<ptr->TextualHeadersLen) {
if (start[i]==0) {
fprintf(trace, "%s ", start+offset);
offset=i+1;
}
i++;
}
fprintf(trace, "%s\" ", start+offset);
}
fprintf(trace, ">\n");
gf_isom_box_dump_done("OMADRMCommonHeaderBox", a, trace);
return GF_OK;
}
GF_Err grpi_dump(GF_Box *a, FILE * trace)
{
GF_OMADRMGroupIDBox *ptr = (GF_OMADRMGroupIDBox *)a;
gf_isom_box_dump_start(a, "OMADRMGroupIDBox", trace);
fprintf(trace, "GroupID=\"%s\" EncryptionMethod=\"%d\" GroupKey=\" ", ptr->GroupID, ptr->GKEncryptionMethod);
if (ptr->GroupKey)
dump_data(trace, ptr->GroupKey, ptr->GKLength);
fprintf(trace, "\">\n");
gf_isom_box_dump_done("OMADRMGroupIDBox", a, trace);
return GF_OK;
}
GF_Err mdri_dump(GF_Box *a, FILE * trace)
{
//GF_OMADRMMutableInformationBox *ptr = (GF_OMADRMMutableInformationBox*)a;
gf_isom_box_dump_start(a, "OMADRMMutableInformationBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("OMADRMMutableInformationBox", a, trace);
return GF_OK;
}
GF_Err odtt_dump(GF_Box *a, FILE * trace)
{
GF_OMADRMTransactionTrackingBox *ptr = (GF_OMADRMTransactionTrackingBox *)a;
gf_isom_box_dump_start(a, "OMADRMTransactionTrackingBox", trace);
fprintf(trace, "TransactionID=\"");
dump_data(trace, ptr->TransactionID, 16);
fprintf(trace, "\">\n");
gf_isom_box_dump_done("OMADRMTransactionTrackingBox", a, trace);
return GF_OK;
}
GF_Err odrb_dump(GF_Box *a, FILE * trace)
{
GF_OMADRMRightsObjectBox*ptr = (GF_OMADRMRightsObjectBox*)a;
gf_isom_box_dump_start(a, "OMADRMRightsObjectBox", trace);
fprintf(trace, "OMARightsObject=\"");
dump_data(trace, ptr->oma_ro, ptr->oma_ro_size);
fprintf(trace, "\">\n");
gf_isom_box_dump_done("OMADRMRightsObjectBox", a, trace);
return GF_OK;
}
GF_Err odkm_dump(GF_Box *a, FILE * trace)
{
GF_OMADRMKMSBox *ptr = (GF_OMADRMKMSBox*)a;
gf_isom_box_dump_start(a, "OMADRMKMSBox", trace);
fprintf(trace, ">\n");
if (ptr->hdr) gf_isom_box_dump((GF_Box *)ptr->hdr, trace);
if (ptr->fmt) gf_isom_box_dump((GF_Box *)ptr->fmt, trace);
gf_isom_box_dump_done("OMADRMKMSBox", a, trace);
return GF_OK;
}
GF_Err pasp_dump(GF_Box *a, FILE * trace)
{
GF_PixelAspectRatioBox *ptr = (GF_PixelAspectRatioBox*)a;
gf_isom_box_dump_start(a, "PixelAspectRatioBox", trace);
fprintf(trace, "hSpacing=\"%d\" vSpacing=\"%d\" >\n", ptr->hSpacing, ptr->vSpacing);
gf_isom_box_dump_done("PixelAspectRatioBox", a, trace);
return GF_OK;
}
GF_Err clap_dump(GF_Box *a, FILE * trace)
{
GF_CleanAppertureBox *ptr = (GF_CleanAppertureBox*)a;
gf_isom_box_dump_start(a, "CleanAppertureBox", trace);
fprintf(trace, "cleanApertureWidthN=\"%d\" cleanApertureWidthD=\"%d\" ", ptr->cleanApertureWidthN, ptr->cleanApertureWidthD);
fprintf(trace, "cleanApertureHeightN=\"%d\" cleanApertureHeightD=\"%d\" ", ptr->cleanApertureHeightN, ptr->cleanApertureHeightD);
fprintf(trace, "horizOffN=\"%d\" horizOffD=\"%d\" ", ptr->horizOffN, ptr->horizOffD);
fprintf(trace, "vertOffN=\"%d\" vertOffD=\"%d\"", ptr->vertOffN, ptr->vertOffD);
fprintf(trace, ">\n");
gf_isom_box_dump_done("CleanAppertureBox", a, trace);
return GF_OK;
}
GF_Err tsel_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_TrackSelectionBox *ptr = (GF_TrackSelectionBox *)a;
gf_isom_box_dump_start(a, "TrackSelectionBox", trace);
fprintf(trace, "switchGroup=\"%d\" >\n", ptr->switchGroup);
for (i=0; i<ptr->attributeListCount; i++) {
fprintf(trace, "<TrackSelectionCriteria value=\"%s\"/>\n", gf_4cc_to_str(ptr->attributeList[i]) );
}
if (!ptr->size)
fprintf(trace, "<TrackSelectionCriteria value=\"\"/>\n");
gf_isom_box_dump_done("TrackSelectionBox", a, trace);
return GF_OK;
}
GF_Err metx_dump(GF_Box *a, FILE * trace)
{
GF_MetaDataSampleEntryBox *ptr = (GF_MetaDataSampleEntryBox*)a;
const char *name;
switch (ptr->type) {
case GF_ISOM_BOX_TYPE_METX:
name = "XMLMetaDataSampleEntryBox";
break;
case GF_ISOM_BOX_TYPE_METT:
name = "TextMetaDataSampleEntryBox";
break;
case GF_ISOM_BOX_TYPE_SBTT:
name = "SubtitleSampleEntryBox";
break;
case GF_ISOM_BOX_TYPE_STXT:
name = "SimpleTextSampleEntryBox";
break;
case GF_ISOM_BOX_TYPE_STPP:
name = "XMLSubtitleSampleEntryBox";
break;
default:
name = "UnknownTextSampleEntryBox";
break;
}
gf_isom_box_dump_start(a, name, trace);
if (ptr->type==GF_ISOM_BOX_TYPE_METX) {
fprintf(trace, "namespace=\"%s\" ", ptr->xml_namespace);
if (ptr->xml_schema_loc) fprintf(trace, "schema_location=\"%s\" ", ptr->xml_schema_loc);
if (ptr->content_encoding) fprintf(trace, "content_encoding=\"%s\" ", ptr->content_encoding);
} else if (ptr->type==GF_ISOM_BOX_TYPE_STPP) {
fprintf(trace, "namespace=\"%s\" ", ptr->xml_namespace);
if (ptr->xml_schema_loc) fprintf(trace, "schema_location=\"%s\" ", ptr->xml_schema_loc);
if (ptr->mime_type) fprintf(trace, "auxiliary_mime_types=\"%s\" ", ptr->mime_type);
}
//mett, sbtt, stxt
else {
fprintf(trace, "mime_type=\"%s\" ", ptr->mime_type);
if (ptr->content_encoding) fprintf(trace, "content_encoding=\"%s\" ", ptr->content_encoding);
}
fprintf(trace, ">\n");
if ((ptr->type!=GF_ISOM_BOX_TYPE_METX) && (ptr->type!=GF_ISOM_BOX_TYPE_STPP) ) {
if (ptr->config) gf_isom_box_dump(ptr->config, trace);
}
gf_isom_box_array_dump(ptr->protections, trace);
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
GF_Err txtc_dump(GF_Box *a, FILE * trace)
{
GF_TextConfigBox *ptr = (GF_TextConfigBox*)a;
const char *name = "TextConfigBox";
gf_isom_box_dump_start(a, name, trace);
fprintf(trace, ">\n");
if (ptr->config) fprintf(trace, "<![CDATA[%s]]>", ptr->config);
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
GF_Err dims_dump(GF_Box *a, FILE * trace)
{
GF_DIMSSampleEntryBox *p = (GF_DIMSSampleEntryBox*)a;
gf_isom_box_dump_start(a, "DIMSSampleEntryBox", trace);
fprintf(trace, "dataReferenceIndex=\"%d\">\n", p->dataReferenceIndex);
if (p->config) gf_isom_box_dump(p->config, trace);
if (p->scripts) gf_isom_box_dump(p->scripts, trace);
gf_isom_box_array_dump(p->protections, trace);
gf_isom_box_dump_done("DIMSSampleEntryBox", a, trace);
return GF_OK;
}
GF_Err diST_dump(GF_Box *a, FILE * trace)
{
GF_DIMSScriptTypesBox *p = (GF_DIMSScriptTypesBox*)a;
gf_isom_box_dump_start(a, "DIMSScriptTypesBox", trace);
fprintf(trace, "types=\"%s\">\n", p->content_script_types);
gf_isom_box_dump_done("DIMSScriptTypesBox", a, trace);
return GF_OK;
}
GF_Err dimC_dump(GF_Box *a, FILE * trace)
{
GF_DIMSSceneConfigBox *p = (GF_DIMSSceneConfigBox *)a;
gf_isom_box_dump_start(a, "DIMSSceneConfigBox", trace);
fprintf(trace, "profile=\"%d\" level=\"%d\" pathComponents=\"%d\" useFullRequestHosts=\"%d\" streamType=\"%d\" containsRedundant=\"%d\" textEncoding=\"%s\" contentEncoding=\"%s\" >\n",
p->profile, p->level, p->pathComponents, p->fullRequestHost, p->streamType, p->containsRedundant, p->textEncoding, p->contentEncoding);
gf_isom_box_dump_done("DIMSSceneConfigBox", a, trace);
return GF_OK;
}
GF_Err dac3_dump(GF_Box *a, FILE * trace)
{
GF_AC3ConfigBox *p = (GF_AC3ConfigBox *)a;
if (p->cfg.is_ec3) {
u32 i;
a->type = GF_ISOM_BOX_TYPE_DEC3;
gf_isom_box_dump_start(a, "EC3SpecificBox", trace);
a->type = GF_ISOM_BOX_TYPE_DAC3;
fprintf(trace, "nb_streams=\"%d\" data_rate=\"%d\">\n", p->cfg.nb_streams, p->cfg.brcode);
for (i=0; i<p->cfg.nb_streams; i++) {
fprintf(trace, "<EC3StreamConfig fscod=\"%d\" bsid=\"%d\" bsmod=\"%d\" acmod=\"%d\" lfon=\"%d\" num_sub_dep=\"%d\" chan_loc=\"%d\"/>\n",
p->cfg.streams[i].fscod, p->cfg.streams[i].bsid, p->cfg.streams[i].bsmod, p->cfg.streams[i].acmod, p->cfg.streams[i].lfon, p->cfg.streams[i].nb_dep_sub, p->cfg.streams[i].chan_loc);
}
gf_isom_box_dump_done("EC3SpecificBox", a, trace);
} else {
gf_isom_box_dump_start(a, "AC3SpecificBox", trace);
fprintf(trace, "fscod=\"%d\" bsid=\"%d\" bsmod=\"%d\" acmod=\"%d\" lfon=\"%d\" bit_rate_code=\"%d\">\n",
p->cfg.streams[0].fscod, p->cfg.streams[0].bsid, p->cfg.streams[0].bsmod, p->cfg.streams[0].acmod, p->cfg.streams[0].lfon, p->cfg.brcode);
gf_isom_box_dump_done("AC3SpecificBox", a, trace);
}
return GF_OK;
}
GF_Err lsrc_dump(GF_Box *a, FILE * trace)
{
GF_LASERConfigurationBox *p = (GF_LASERConfigurationBox *)a;
gf_isom_box_dump_start(a, "LASeRConfigurationBox", trace);
dump_data_attribute(trace, "LASeRHeader", p->hdr, p->hdr_size);
fprintf(trace, ">");
gf_isom_box_dump_done("LASeRConfigurationBox", a, trace);
return GF_OK;
}
GF_Err lsr1_dump(GF_Box *a, FILE * trace)
{
GF_LASeRSampleEntryBox *p = (GF_LASeRSampleEntryBox*)a;
gf_isom_box_dump_start(a, "LASeRSampleEntryBox", trace);
fprintf(trace, "DataReferenceIndex=\"%d\">\n", p->dataReferenceIndex);
if (p->lsr_config) gf_isom_box_dump(p->lsr_config, trace);
if (p->descr) gf_isom_box_dump(p->descr, trace);
gf_isom_box_dump_done("LASeRSampleEntryBox", a, trace);
return GF_OK;
}
GF_Err sidx_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SegmentIndexBox *p = (GF_SegmentIndexBox *)a;
gf_isom_box_dump_start(a, "SegmentIndexBox", trace);
fprintf(trace, "reference_ID=\"%d\" timescale=\"%d\" earliest_presentation_time=\""LLD"\" first_offset=\""LLD"\" ", p->reference_ID, p->timescale, p->earliest_presentation_time, p->first_offset);
fprintf(trace, ">\n");
for (i=0; i<p->nb_refs; i++) {
fprintf(trace, "<Reference type=\"%d\" size=\"%d\" duration=\"%d\" startsWithSAP=\"%d\" SAP_type=\"%d\" SAPDeltaTime=\"%d\"/>\n", p->refs[i].reference_type, p->refs[i].reference_size, p->refs[i].subsegment_duration, p->refs[i].starts_with_SAP, p->refs[i].SAP_type, p->refs[i].SAP_delta_time);
}
if (!p->size) {
fprintf(trace, "<Reference type=\"\" size=\"\" duration=\"\" startsWithSAP=\"\" SAP_type=\"\" SAPDeltaTime=\"\"/>\n");
}
gf_isom_box_dump_done("SegmentIndexBox", a, trace);
return GF_OK;
}
GF_Err ssix_dump(GF_Box *a, FILE * trace)
{
u32 i, j;
GF_SubsegmentIndexBox *p = (GF_SubsegmentIndexBox *)a;
gf_isom_box_dump_start(a, "SubsegmentIndexBox", trace);
fprintf(trace, "subsegment_count=\"%d\" >\n", p->subsegment_count);
for (i = 0; i < p->subsegment_count; i++) {
fprintf(trace, "<Subsegment range_count=\"%d\">\n", p->subsegments[i].range_count);
for (j = 0; j < p->subsegments[i].range_count; j++) {
fprintf(trace, "<Range level=\"%d\" range_size=\"%d\"/>\n", p->subsegments[i].levels[j], p->subsegments[i].range_sizes[j]);
}
fprintf(trace, "</Subsegment>\n");
}
if (!p->size) {
fprintf(trace, "<Subsegment range_count=\"\">\n");
fprintf(trace, "<Range level=\"\" range_size=\"\"/>\n");
fprintf(trace, "</Subsegment>\n");
}
gf_isom_box_dump_done("SubsegmentIndexBox", a, trace);
return GF_OK;
}
GF_Err leva_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_LevelAssignmentBox *p = (GF_LevelAssignmentBox *)a;
gf_isom_box_dump_start(a, "LevelAssignmentBox", trace);
fprintf(trace, "level_count=\"%d\" >\n", p->level_count);
for (i = 0; i < p->level_count; i++) {
fprintf(trace, "<Assignement track_id=\"%d\" padding_flag=\"%d\" assignement_type=\"%d\" grouping_type=\"%s\" grouping_type_parameter=\"%d\" sub_track_id=\"%d\" />\n", p->levels[i].track_id, p->levels[i].padding_flag, p->levels[i].type, gf_4cc_to_str(p->levels[i].grouping_type) , p->levels[i].grouping_type_parameter, p->levels[i].sub_track_id);
}
if (!p->size) {
fprintf(trace, "<Assignement track_id=\"\" padding_flag=\"\" assignement_type=\"\" grouping_type=\"\" grouping_type_parameter=\"\" sub_track_id=\"\" />\n");
}
gf_isom_box_dump_done("LevelAssignmentBox", a, trace);
return GF_OK;
}
GF_Err strk_dump(GF_Box *a, FILE * trace)
{
GF_SubTrackBox *p = (GF_SubTrackBox *)a;
gf_isom_box_dump_start(a, "SubTrackBox", trace);
fprintf(trace, ">\n");
if (p->info) {
gf_isom_box_dump(p->info, trace);
}
gf_isom_box_dump_done("SubTrackBox", a, trace);
return GF_OK;
}
GF_Err stri_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SubTrackInformationBox *p = (GF_SubTrackInformationBox *)a;
gf_isom_box_dump_start(a, "SubTrackInformationBox", trace);
fprintf(trace, "switch_group=\"%d\" alternate_group=\"%d\" sub_track_id=\"%d\">\n", p->switch_group, p->alternate_group, p->sub_track_id);
for (i = 0; i < p->attribute_count; i++) {
fprintf(trace, "<SubTrackInformationAttribute value=\"%s\"/>\n", gf_4cc_to_str(p->attribute_list[i]) );
}
if (!p->size)
fprintf(trace, "<SubTrackInformationAttribute value=\"\"/>\n");
gf_isom_box_dump_done("SubTrackInformationBox", a, trace);
return GF_OK;
}
GF_Err stsg_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SubTrackSampleGroupBox *p = (GF_SubTrackSampleGroupBox *)a;
gf_isom_box_dump_start(a, "SubTrackSampleGroupBox", trace);
if (p->grouping_type)
fprintf(trace, "grouping_type=\"%s\"", gf_4cc_to_str(p->grouping_type) );
fprintf(trace, ">\n");
for (i = 0; i < p->nb_groups; i++) {
fprintf(trace, "<SubTrackSampleGroupBoxEntry group_description_index=\"%d\"/>\n", p->group_description_index[i]);
}
if (!p->size)
fprintf(trace, "<SubTrackSampleGroupBoxEntry group_description_index=\"\"/>\n");
gf_isom_box_dump_done("SubTrackSampleGroupBox", a, trace);
return GF_OK;
}
GF_Err pcrb_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_PcrInfoBox *p = (GF_PcrInfoBox *)a;
gf_isom_box_dump_start(a, "MPEG2TSPCRInfoBox", trace);
fprintf(trace, "subsegment_count=\"%d\">\n", p->subsegment_count);
for (i=0; i<p->subsegment_count; i++) {
fprintf(trace, "<PCRInfo PCR=\""LLU"\" />\n", p->pcr_values[i]);
}
if (!p->size) {
fprintf(trace, "<PCRInfo PCR=\"\" />\n");
}
gf_isom_box_dump_done("MPEG2TSPCRInfoBox", a, trace);
return GF_OK;
}
GF_Err subs_dump(GF_Box *a, FILE * trace)
{
u32 entry_count, i, j;
u16 subsample_count;
GF_SubSampleInfoEntry *pSamp;
GF_SubSampleEntry *pSubSamp;
GF_SubSampleInformationBox *ptr = (GF_SubSampleInformationBox *) a;
if (!a) return GF_BAD_PARAM;
entry_count = gf_list_count(ptr->Samples);
gf_isom_box_dump_start(a, "SubSampleInformationBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", entry_count);
for (i=0; i<entry_count; i++) {
pSamp = (GF_SubSampleInfoEntry*) gf_list_get(ptr->Samples, i);
subsample_count = gf_list_count(pSamp->SubSamples);
fprintf(trace, "<SampleEntry SampleDelta=\"%d\" SubSampleCount=\"%d\">\n", pSamp->sample_delta, subsample_count);
for (j=0; j<subsample_count; j++) {
pSubSamp = (GF_SubSampleEntry*) gf_list_get(pSamp->SubSamples, j);
fprintf(trace, "<SubSample Size=\"%u\" Priority=\"%u\" Discardable=\"%d\" Reserved=\"%08X\"/>\n", pSubSamp->subsample_size, pSubSamp->subsample_priority, pSubSamp->discardable, pSubSamp->reserved);
}
fprintf(trace, "</SampleEntry>\n");
}
if (!ptr->size) {
fprintf(trace, "<SampleEntry SampleDelta=\"\" SubSampleCount=\"\">\n");
fprintf(trace, "<SubSample Size=\"\" Priority=\"\" Discardable=\"\" Reserved=\"\"/>\n");
fprintf(trace, "</SampleEntry>\n");
}
gf_isom_box_dump_done("SubSampleInformationBox", a, trace);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
GF_Err tfdt_dump(GF_Box *a, FILE * trace)
{
GF_TFBaseMediaDecodeTimeBox *ptr = (GF_TFBaseMediaDecodeTimeBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "TrackFragmentBaseMediaDecodeTimeBox", trace);
fprintf(trace, "baseMediaDecodeTime=\""LLD"\">\n", ptr->baseMediaDecodeTime);
gf_isom_box_dump_done("TrackFragmentBaseMediaDecodeTimeBox", a, trace);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/
GF_Err rvcc_dump(GF_Box *a, FILE * trace)
{
GF_RVCConfigurationBox *ptr = (GF_RVCConfigurationBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "RVCConfigurationBox", trace);
fprintf(trace, "predefined=\"%d\"", ptr->predefined_rvc_config);
if (! ptr->predefined_rvc_config) fprintf(trace, " rvc_meta_idx=\"%d\"", ptr->rvc_meta_idx);
fprintf(trace, ">\n");
gf_isom_box_dump_done("RVCConfigurationBox", a, trace);
return GF_OK;
}
GF_Err sbgp_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SampleGroupBox *ptr = (GF_SampleGroupBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleGroupBox", trace);
if (ptr->grouping_type)
fprintf(trace, "grouping_type=\"%s\"", gf_4cc_to_str(ptr->grouping_type) );
if (ptr->version==1) {
if (isalnum(ptr->grouping_type_parameter&0xFF)) {
fprintf(trace, " grouping_type_parameter=\"%s\"", gf_4cc_to_str(ptr->grouping_type_parameter) );
} else {
fprintf(trace, " grouping_type_parameter=\"%d\"", ptr->grouping_type_parameter);
}
}
fprintf(trace, ">\n");
for (i=0; i<ptr->entry_count; i++) {
fprintf(trace, "<SampleGroupBoxEntry sample_count=\"%d\" group_description_index=\"%d\"/>\n", ptr->sample_entries[i].sample_count, ptr->sample_entries[i].group_description_index );
}
if (!ptr->size) {
fprintf(trace, "<SampleGroupBoxEntry sample_count=\"\" group_description_index=\"\"/>\n");
}
gf_isom_box_dump_done("SampleGroupBox", a, trace);
return GF_OK;
}
static void oinf_entry_dump(GF_OperatingPointsInformation *ptr, FILE * trace)
{
u32 i, count;
if (!ptr) {
fprintf(trace, "<OperatingPointsInformation scalability_mask=\"Multiview|Spatial scalability|Auxilary|unknown\" num_profile_tier_level=\"\" num_operating_points=\"\" dependency_layers=\"\">\n");
fprintf(trace, " <ProfileTierLevel general_profile_space=\"\" general_tier_flag=\"\" general_profile_idc=\"\" general_profile_compatibility_flags=\"\" general_constraint_indicator_flags=\"\" />\n");
fprintf(trace, "<OperatingPoint output_layer_set_idx=\"\" max_temporal_id=\"\" layer_count=\"\" minPicWidth=\"\" minPicHeight=\"\" maxPicWidth=\"\" maxPicHeight=\"\" maxChromaFormat=\"\" maxBitDepth=\"\" frame_rate_info_flag=\"\" bit_rate_info_flag=\"\" avgFrameRate=\"\" constantFrameRate=\"\" maxBitRate=\"\" avgBitRate=\"\"/>\n");
fprintf(trace, "<Layer dependent_layerID=\"\" num_layers_dependent_on=\"\" dependent_on_layerID=\"\" dimension_identifier=\"\"/>\n");
fprintf(trace, "</OperatingPointsInformation>\n");
return;
}
fprintf(trace, "<OperatingPointsInformation");
fprintf(trace, " scalability_mask=\"%u (", ptr->scalability_mask);
switch (ptr->scalability_mask) {
case 2:
fprintf(trace, "Multiview");
break;
case 4:
fprintf(trace, "Spatial scalability");
break;
case 8:
fprintf(trace, "Auxilary");
break;
default:
fprintf(trace, "unknown");
}
fprintf(trace, ")\" num_profile_tier_level=\"%u\"", gf_list_count(ptr->profile_tier_levels) );
fprintf(trace, " num_operating_points=\"%u\" dependency_layers=\"%u\"", gf_list_count(ptr->operating_points), gf_list_count(ptr->dependency_layers));
fprintf(trace, ">\n");
count=gf_list_count(ptr->profile_tier_levels);
for (i = 0; i < count; i++) {
LHEVC_ProfileTierLevel *ptl = (LHEVC_ProfileTierLevel *)gf_list_get(ptr->profile_tier_levels, i);
fprintf(trace, " <ProfileTierLevel general_profile_space=\"%u\" general_tier_flag=\"%u\" general_profile_idc=\"%u\" general_profile_compatibility_flags=\"%X\" general_constraint_indicator_flags=\""LLX"\" />\n", ptl->general_profile_space, ptl->general_tier_flag, ptl->general_profile_idc, ptl->general_profile_compatibility_flags, ptl->general_constraint_indicator_flags);
}
count=gf_list_count(ptr->operating_points);
for (i = 0; i < count; i++) {
LHEVC_OperatingPoint *op = (LHEVC_OperatingPoint *)gf_list_get(ptr->operating_points, i);
fprintf(trace, "<OperatingPoint output_layer_set_idx=\"%u\"", op->output_layer_set_idx);
fprintf(trace, " max_temporal_id=\"%u\" layer_count=\"%u\"", op->max_temporal_id, op->layer_count);
fprintf(trace, " minPicWidth=\"%u\" minPicHeight=\"%u\"", op->minPicWidth, op->minPicHeight);
fprintf(trace, " maxPicWidth=\"%u\" maxPicHeight=\"%u\"", op->maxPicWidth, op->maxPicHeight);
fprintf(trace, " maxChromaFormat=\"%u\" maxBitDepth=\"%u\"", op->maxChromaFormat, op->maxBitDepth);
fprintf(trace, " frame_rate_info_flag=\"%u\" bit_rate_info_flag=\"%u\"", op->frame_rate_info_flag, op->bit_rate_info_flag);
if (op->frame_rate_info_flag)
fprintf(trace, " avgFrameRate=\"%u\" constantFrameRate=\"%u\"", op->avgFrameRate, op->constantFrameRate);
if (op->bit_rate_info_flag)
fprintf(trace, " maxBitRate=\"%u\" avgBitRate=\"%u\"", op->maxBitRate, op->avgBitRate);
fprintf(trace, "/>\n");
}
count=gf_list_count(ptr->dependency_layers);
for (i = 0; i < count; i++) {
u32 j;
LHEVC_DependentLayer *dep = (LHEVC_DependentLayer *)gf_list_get(ptr->dependency_layers, i);
fprintf(trace, "<Layer dependent_layerID=\"%u\" num_layers_dependent_on=\"%u\"", dep->dependent_layerID, dep->num_layers_dependent_on);
if (dep->num_layers_dependent_on) {
fprintf(trace, " dependent_on_layerID=\"");
for (j = 0; j < dep->num_layers_dependent_on; j++)
fprintf(trace, "%d ", dep->dependent_on_layerID[j]);
fprintf(trace, "\"");
}
fprintf(trace, " dimension_identifier=\"");
for (j = 0; j < 16; j++)
if (ptr->scalability_mask & (1 << j))
fprintf(trace, "%d ", dep->dimension_identifier[j]);
fprintf(trace, "\"/>\n");
}
fprintf(trace, "</OperatingPointsInformation>\n");
return;
}
static void linf_dump(GF_LHVCLayerInformation *ptr, FILE * trace)
{
u32 i, count;
if (!ptr) {
fprintf(trace, "<LayerInformation num_layers=\"\">\n");
fprintf(trace, "<LayerInfoItem layer_id=\"\" min_temporalId=\"\" max_temporalId=\"\" sub_layer_presence_flags=\"\"/>\n");
fprintf(trace, "</LayerInformation>\n");
return;
}
count = gf_list_count(ptr->num_layers_in_track);
fprintf(trace, "<LayerInformation num_layers=\"%d\">\n", count );
for (i = 0; i < count; i++) {
LHVCLayerInfoItem *li = (LHVCLayerInfoItem *)gf_list_get(ptr->num_layers_in_track, i);
fprintf(trace, "<LayerInfoItem layer_id=\"%d\" min_temporalId=\"%d\" max_temporalId=\"%d\" sub_layer_presence_flags=\"%d\"/>\n", li->layer_id, li->min_TemporalId, li->max_TemporalId, li->sub_layer_presence_flags);
}
fprintf(trace, "</LayerInformation>\n");
return;
}
static void trif_dump(FILE * trace, char *data, u32 data_size)
{
GF_BitStream *bs;
u32 id, independent, filter_disabled;
Bool full_picture, has_dep, tile_group;
if (!data) {
fprintf(trace, "<TileRegionGroupEntry ID=\"\" tileGroup=\"\" independent=\"\" full_picture=\"\" filter_disabled=\"\" x=\"\" y=\"\" w=\"\" h=\"\">\n");
fprintf(trace, "<TileRegionDependency tileID=\"\"/>\n");
fprintf(trace, "</TileRegionGroupEntry>\n");
return;
}
bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ);
id = gf_bs_read_u16(bs);
tile_group = gf_bs_read_int(bs, 1);
fprintf(trace, "<TileRegionGroupEntry ID=\"%d\" tileGroup=\"%d\" ", id, tile_group);
if (tile_group) {
independent = gf_bs_read_int(bs, 2);
full_picture = (Bool)gf_bs_read_int(bs, 1);
filter_disabled = gf_bs_read_int(bs, 1);
has_dep = gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 2);
fprintf(trace, "independent=\"%d\" full_picture=\"%d\" filter_disabled=\"%d\" ", independent, full_picture, filter_disabled);
if (!full_picture) {
fprintf(trace, "x=\"%d\" y=\"%d\" ", gf_bs_read_u16(bs), gf_bs_read_u16(bs));
}
fprintf(trace, "w=\"%d\" h=\"%d\" ", gf_bs_read_u16(bs), gf_bs_read_u16(bs));
if (!has_dep) {
fprintf(trace, "/>\n");
} else {
u32 count = gf_bs_read_u16(bs);
fprintf(trace, ">\n");
while (count) {
count--;
fprintf(trace, "<TileRegionDependency tileID=\"%d\"/>\n", gf_bs_read_u16(bs) );
}
fprintf(trace, "</TileRegionGroupEntry>\n");
}
}
gf_bs_del(bs);
}
static void nalm_dump(FILE * trace, char *data, u32 data_size)
{
GF_BitStream *bs;
Bool rle, large_size;
u32 entry_count;
if (!data) {
fprintf(trace, "<NALUMap rle=\"\" large_size=\"\">\n");
fprintf(trace, "<NALUMapEntry NALU_startNumber=\"\" groupID=\"\"/>\n");
fprintf(trace, "</NALUMap>\n");
return;
}
bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ);
gf_bs_read_int(bs, 6);
large_size = gf_bs_read_int(bs, 1);
rle = gf_bs_read_int(bs, 1);
entry_count = gf_bs_read_int(bs, large_size ? 16 : 8);
fprintf(trace, "<NALUMap rle=\"%d\" large_size=\"%d\">\n", rle, large_size);
while (entry_count) {
u32 ID;
fprintf(trace, "<NALUMapEntry ");
if (rle) {
u32 start_num = gf_bs_read_int(bs, large_size ? 16 : 8);
fprintf(trace, "NALU_startNumber=\"%d\" ", start_num);
}
ID = gf_bs_read_u16(bs);
fprintf(trace, "groupID=\"%d\"/>\n", ID);
entry_count--;
}
gf_bs_del(bs);
fprintf(trace, "</NALUMap>\n");
return;
}
GF_Err sgpd_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SampleGroupDescriptionBox *ptr = (GF_SampleGroupDescriptionBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleGroupDescriptionBox", trace);
if (ptr->grouping_type)
fprintf(trace, "grouping_type=\"%s\"", gf_4cc_to_str(ptr->grouping_type) );
if (ptr->version==1) fprintf(trace, " default_length=\"%d\"", ptr->default_length);
if ((ptr->version>=2) && ptr->default_description_index) fprintf(trace, " default_group_index=\"%d\"", ptr->default_description_index);
fprintf(trace, ">\n");
for (i=0; i<gf_list_count(ptr->group_descriptions); i++) {
void *entry = gf_list_get(ptr->group_descriptions, i);
switch (ptr->grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
fprintf(trace, "<RollRecoveryEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance );
break;
case GF_ISOM_SAMPLE_GROUP_PROL:
fprintf(trace, "<AudioPreRollEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance );
break;
case GF_ISOM_SAMPLE_GROUP_TELE:
fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"%d\"/>\n", ((GF_TemporalLevelEntry*)entry)->level_independently_decodable);
break;
case GF_ISOM_SAMPLE_GROUP_RAP:
fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"%s\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known ? "yes" : "no");
if (((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known)
fprintf(trace, " num_leading_samples=\"%d\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples);
fprintf(trace, "/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_SYNC:
fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"%d\"/>\n", ((GF_SYNCEntry*)entry)->NALU_type);
break;
case GF_ISOM_SAMPLE_GROUP_SEIG:
fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"%d\" IV_size=\"%d\" KID=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected, ((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size);
dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->KID, 16);
if ((((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected == 1) && !((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size) {
fprintf(trace, "\" constant_IV_size=\"%d\" constant_IV=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);
dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV, ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);
}
fprintf(trace, "\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_OINF:
oinf_entry_dump(entry, trace);
break;
case GF_ISOM_SAMPLE_GROUP_LINF:
linf_dump(entry, trace);
break;
case GF_ISOM_SAMPLE_GROUP_TRIF:
trif_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
nalm_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
break;
case GF_ISOM_SAMPLE_GROUP_SAP:
fprintf(trace, "<SAPEntry dependent_flag=\"%d\" SAP_type=\"%d\" />\n", ((GF_SAPEntry*)entry)->dependent_flag, ((GF_SAPEntry*)entry)->SAP_type);
break;
default:
fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"%d\" data=\"", ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
dump_data(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
fprintf(trace, "\"/>\n");
}
}
if (!ptr->size) {
switch (ptr->grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
fprintf(trace, "<RollRecoveryEntry roll_distance=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_PROL:
fprintf(trace, "<AudioPreRollEntry roll_distance=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_TELE:
fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_RAP:
fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"yes|no\" num_leading_samples=\"\" />\n");
break;
case GF_ISOM_SAMPLE_GROUP_SYNC:
fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"\" />\n");
break;
case GF_ISOM_SAMPLE_GROUP_SEIG:
fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"\" IV_size=\"\" KID=\"\" constant_IV_size=\"\" constant_IV=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_OINF:
oinf_entry_dump(NULL, trace);
break;
case GF_ISOM_SAMPLE_GROUP_LINF:
linf_dump(NULL, trace);
break;
case GF_ISOM_SAMPLE_GROUP_TRIF:
trif_dump(trace, NULL, 0);
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
nalm_dump(trace, NULL, 0);
break;
case GF_ISOM_SAMPLE_GROUP_SAP:
fprintf(trace, "<SAPEntry dependent_flag=\"\" SAP_type=\"\" />\n");
break;
default:
fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"\" data=\"\"/>\n");
}
}
gf_isom_box_dump_done("SampleGroupDescriptionBox", a, trace);
return GF_OK;
}
GF_Err saiz_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SampleAuxiliaryInfoSizeBox *ptr = (GF_SampleAuxiliaryInfoSizeBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleAuxiliaryInfoSizeBox", trace);
fprintf(trace, "default_sample_info_size=\"%d\" sample_count=\"%d\"", ptr->default_sample_info_size, ptr->sample_count);
if (ptr->flags & 1) {
if (isalnum(ptr->aux_info_type>>24)) {
fprintf(trace, " aux_info_type=\"%s\" aux_info_type_parameter=\"%d\"", gf_4cc_to_str(ptr->aux_info_type), ptr->aux_info_type_parameter);
} else {
fprintf(trace, " aux_info_type=\"%d\" aux_info_type_parameter=\"%d\"", ptr->aux_info_type, ptr->aux_info_type_parameter);
}
}
fprintf(trace, ">\n");
if (ptr->default_sample_info_size==0) {
for (i=0; i<ptr->sample_count; i++) {
fprintf(trace, "<SAISize size=\"%d\" />\n", ptr->sample_info_size[i]);
}
}
if (!ptr->size) {
fprintf(trace, "<SAISize size=\"\" />\n");
}
gf_isom_box_dump_done("SampleAuxiliaryInfoSizeBox", a, trace);
return GF_OK;
}
GF_Err saio_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SampleAuxiliaryInfoOffsetBox *ptr = (GF_SampleAuxiliaryInfoOffsetBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleAuxiliaryInfoOffsetBox", trace);
fprintf(trace, "entry_count=\"%d\"", ptr->entry_count);
if (ptr->flags & 1) {
if (isalnum(ptr->aux_info_type>>24)) {
fprintf(trace, " aux_info_type=\"%s\" aux_info_type_parameter=\"%d\"", gf_4cc_to_str(ptr->aux_info_type), ptr->aux_info_type_parameter);
} else {
fprintf(trace, " aux_info_type=\"%d\" aux_info_type_parameter=\"%d\"", ptr->aux_info_type, ptr->aux_info_type_parameter);
}
}
fprintf(trace, ">\n");
if (ptr->version==0) {
for (i=0; i<ptr->entry_count; i++) {
fprintf(trace, "<SAIChunkOffset offset=\"%d\"/>\n", ptr->offsets[i]);
}
} else {
for (i=0; i<ptr->entry_count; i++) {
fprintf(trace, "<SAIChunkOffset offset=\""LLD"\"/>\n", ptr->offsets_large[i]);
}
}
if (!ptr->size) {
fprintf(trace, "<SAIChunkOffset offset=\"\"/>\n");
}
gf_isom_box_dump_done("SampleAuxiliaryInfoOffsetBox", a, trace);
return GF_OK;
}
GF_Err pssh_dump(GF_Box *a, FILE * trace)
{
GF_ProtectionSystemHeaderBox *ptr = (GF_ProtectionSystemHeaderBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "ProtectionSystemHeaderBox", trace);
fprintf(trace, "SystemID=\"");
dump_data_hex(trace, (char *) ptr->SystemID, 16);
fprintf(trace, "\">\n");
if (ptr->KID_count) {
u32 i;
for (i=0; i<ptr->KID_count; i++) {
fprintf(trace, " <PSSHKey KID=\"");
dump_data_hex(trace, (char *) ptr->KIDs[i], 16);
fprintf(trace, "\"/>\n");
}
}
if (ptr->private_data_size) {
fprintf(trace, " <PSSHData size=\"%d\" value=\"", ptr->private_data_size);
dump_data_hex(trace, (char *) ptr->private_data, ptr->private_data_size);
fprintf(trace, "\"/>\n");
}
if (!ptr->size) {
fprintf(trace, " <PSSHKey KID=\"\"/>\n");
fprintf(trace, " <PSSHData size=\"\" value=\"\"/>\n");
}
gf_isom_box_dump_done("ProtectionSystemHeaderBox", a, trace);
return GF_OK;
}
GF_Err tenc_dump(GF_Box *a, FILE * trace)
{
GF_TrackEncryptionBox *ptr = (GF_TrackEncryptionBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "TrackEncryptionBox", trace);
fprintf(trace, "isEncrypted=\"%d\"", ptr->isProtected);
if (ptr->Per_Sample_IV_Size)
fprintf(trace, " IV_size=\"%d\" KID=\"", ptr->Per_Sample_IV_Size);
else {
fprintf(trace, " constant_IV_size=\"%d\" constant_IV=\"", ptr->constant_IV_size);
dump_data_hex(trace, (char *) ptr->constant_IV, ptr->constant_IV_size);
fprintf(trace, "\" KID=\"");
}
dump_data_hex(trace, (char *) ptr->KID, 16);
if (ptr->version)
fprintf(trace, "\" crypt_byte_block=\"%d\" skip_byte_block=\"%d", ptr->crypt_byte_block, ptr->skip_byte_block);
fprintf(trace, "\">\n");
gf_isom_box_dump_done("TrackEncryptionBox", a, trace);
return GF_OK;
}
GF_Err piff_pssh_dump(GF_Box *a, FILE * trace)
{
GF_PIFFProtectionSystemHeaderBox *ptr = (GF_PIFFProtectionSystemHeaderBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "PIFFProtectionSystemHeaderBox", trace);
fprintf(trace, "SystemID=\"");
dump_data_hex(trace, (char *) ptr->SystemID, 16);
fprintf(trace, "\" PrivateData=\"");
dump_data_hex(trace, (char *) ptr->private_data, ptr->private_data_size);
fprintf(trace, "\">\n");
gf_isom_box_dump_done("PIFFProtectionSystemHeaderBox", a, trace);
return GF_OK;
}
GF_Err piff_tenc_dump(GF_Box *a, FILE * trace)
{
GF_PIFFTrackEncryptionBox *ptr = (GF_PIFFTrackEncryptionBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "PIFFTrackEncryptionBox", trace);
fprintf(trace, "AlgorithmID=\"%d\" IV_size=\"%d\" KID=\"", ptr->AlgorithmID, ptr->IV_size);
dump_data_hex(trace,(char *) ptr->KID, 16);
fprintf(trace, "\">\n");
gf_isom_box_dump_done("PIFFTrackEncryptionBox", a, trace);
return GF_OK;
}
GF_Err piff_psec_dump(GF_Box *a, FILE * trace)
{
u32 i, j, sample_count;
GF_SampleEncryptionBox *ptr = (GF_SampleEncryptionBox *) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "PIFFSampleEncryptionBox", trace);
sample_count = gf_list_count(ptr->samp_aux_info);
fprintf(trace, "sampleCount=\"%d\"", sample_count);
if (ptr->flags & 1) {
fprintf(trace, " AlgorithmID=\"%d\" IV_size=\"%d\" KID=\"", ptr->AlgorithmID, ptr->IV_size);
dump_data(trace, (char *) ptr->KID, 16);
fprintf(trace, "\"");
}
fprintf(trace, ">\n");
if (sample_count) {
for (i=0; i<sample_count; i++) {
GF_CENCSampleAuxInfo *cenc_sample = (GF_CENCSampleAuxInfo *)gf_list_get(ptr->samp_aux_info, i);
if (cenc_sample) {
if (!strlen((char *)cenc_sample->IV)) continue;
fprintf(trace, "<PIFFSampleEncryptionEntry IV_size=\"%u\" IV=\"", cenc_sample->IV_size);
dump_data_hex(trace, (char *) cenc_sample->IV, cenc_sample->IV_size);
if (ptr->flags & 0x2) {
fprintf(trace, "\" SubsampleCount=\"%d\"", cenc_sample->subsample_count);
fprintf(trace, ">\n");
for (j=0; j<cenc_sample->subsample_count; j++) {
fprintf(trace, "<PIFFSubSampleEncryptionEntry NumClearBytes=\"%d\" NumEncryptedBytes=\"%d\"/>\n", cenc_sample->subsamples[j].bytes_clear_data, cenc_sample->subsamples[j].bytes_encrypted_data);
}
}
fprintf(trace, "</PIFFSampleEncryptionEntry>\n");
}
}
}
if (!ptr->size) {
fprintf(trace, "<PIFFSampleEncryptionEntry IV=\"\" SubsampleCount=\"\">\n");
fprintf(trace, "<PIFFSubSampleEncryptionEntry NumClearBytes=\"\" NumEncryptedBytes=\"\"/>\n");
fprintf(trace, "</PIFFSampleEncryptionEntry>\n");
}
gf_isom_box_dump_done("PIFFSampleEncryptionBox", a, trace);
return GF_OK;
}
GF_Err senc_dump(GF_Box *a, FILE * trace)
{
u32 i, j, sample_count;
GF_SampleEncryptionBox *ptr = (GF_SampleEncryptionBox *) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleEncryptionBox", trace);
sample_count = gf_list_count(ptr->samp_aux_info);
fprintf(trace, "sampleCount=\"%d\">\n", sample_count);
//WARNING - PSEC (UUID) IS TYPECASTED TO SENC (FULL BOX) SO WE CANNOT USE USUAL FULL BOX FUNCTIONS
fprintf(trace, "<FullBoxInfo Version=\"%d\" Flags=\"0x%X\"/>\n", ptr->version, ptr->flags);
for (i=0; i<sample_count; i++) {
GF_CENCSampleAuxInfo *cenc_sample = (GF_CENCSampleAuxInfo *)gf_list_get(ptr->samp_aux_info, i);
if (cenc_sample) {
fprintf(trace, "<SampleEncryptionEntry sampleNumber=\"%d\" IV_size=\"%u\" IV=\"", i+1, cenc_sample->IV_size);
dump_data_hex(trace, (char *) cenc_sample->IV, cenc_sample->IV_size);
fprintf(trace, "\"");
if (ptr->flags & 0x2) {
fprintf(trace, " SubsampleCount=\"%d\"", cenc_sample->subsample_count);
fprintf(trace, ">\n");
for (j=0; j<cenc_sample->subsample_count; j++) {
fprintf(trace, "<SubSampleEncryptionEntry NumClearBytes=\"%d\" NumEncryptedBytes=\"%d\"/>\n", cenc_sample->subsamples[j].bytes_clear_data, cenc_sample->subsamples[j].bytes_encrypted_data);
}
} else {
fprintf(trace, ">\n");
}
fprintf(trace, "</SampleEncryptionEntry>\n");
}
}
if (!ptr->size) {
fprintf(trace, "<SampleEncryptionEntry sampleCount=\"\" IV=\"\" SubsampleCount=\"\">\n");
fprintf(trace, "<SubSampleEncryptionEntry NumClearBytes=\"\" NumEncryptedBytes=\"\"/>\n");
fprintf(trace, "</SampleEncryptionEntry>\n");
}
gf_isom_box_dump_done("SampleEncryptionBox", a, trace);
return GF_OK;
}
GF_Err prft_dump(GF_Box *a, FILE * trace)
{
Double fracs;
GF_ProducerReferenceTimeBox *ptr = (GF_ProducerReferenceTimeBox *) a;
time_t secs;
struct tm t;
secs = (ptr->ntp >> 32) - GF_NTP_SEC_1900_TO_1970;
if (secs < 0) {
if (ptr->size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("NTP time is not valid, using value 0\n"));
}
secs = 0;
}
t = *gmtime(&secs);
fracs = (Double) (ptr->ntp & 0xFFFFFFFFULL);
fracs /= 0xFFFFFFFF;
fracs *= 1000;
gf_isom_box_dump_start(a, "ProducerReferenceTimeBox", trace);
fprintf(trace, "referenceTrackID=\"%d\" timestamp=\""LLU"\" NTP=\""LLU"\" UTC=\"%d-%02d-%02dT%02d:%02d:%02d.%03dZ\">\n", ptr->refTrackID, ptr->timestamp, ptr->ntp, 1900+t.tm_year, t.tm_mon+1, t.tm_mday, t.tm_hour, t.tm_min, (u32) t.tm_sec, (u32) fracs);
gf_isom_box_dump_done("ProducerReferenceTimeBox", a, trace);
return GF_OK;
}
GF_Err adkm_dump(GF_Box *a, FILE * trace)
{
GF_AdobeDRMKeyManagementSystemBox *ptr = (GF_AdobeDRMKeyManagementSystemBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "AdobeDRMKeyManagementSystemBox", trace);
fprintf(trace, ">\n");
if (ptr->header) gf_isom_box_dump((GF_Box *)ptr->header, trace);
if (ptr->au_format) gf_isom_box_dump((GF_Box *)ptr->au_format, trace);
gf_isom_box_dump_done("AdobeDRMKeyManagementSystemBox", a, trace);
return GF_OK;
}
GF_Err ahdr_dump(GF_Box *a, FILE * trace)
{
GF_AdobeDRMHeaderBox *ptr = (GF_AdobeDRMHeaderBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "AdobeDRMHeaderBox", trace);
fprintf(trace, ">\n");
if (ptr->std_enc_params) gf_isom_box_dump((GF_Box *)ptr->std_enc_params, trace);
gf_isom_box_dump_done("AdobeDRMHeaderBox", a, trace);
return GF_OK;
}
GF_Err aprm_dump(GF_Box *a, FILE * trace)
{
GF_AdobeStdEncryptionParamsBox *ptr = (GF_AdobeStdEncryptionParamsBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "AdobeStdEncryptionParamsBox", trace);
fprintf(trace, ">\n");
if (ptr->enc_info) gf_isom_box_dump((GF_Box *)ptr->enc_info, trace);
if (ptr->key_info) gf_isom_box_dump((GF_Box *)ptr->key_info, trace);
gf_isom_box_dump_done("AdobeStdEncryptionParamsBox", a, trace);
return GF_OK;
}
GF_Err aeib_dump(GF_Box *a, FILE * trace)
{
GF_AdobeEncryptionInfoBox *ptr = (GF_AdobeEncryptionInfoBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "AdobeEncryptionInfoBox", trace);
fprintf(trace, "EncryptionAlgorithm=\"%s\" KeyLength=\"%d\">\n", ptr->enc_algo, ptr->key_length);
gf_isom_box_dump_done("AdobeEncryptionInfoBox", a, trace);
return GF_OK;
}
GF_Err akey_dump(GF_Box *a, FILE * trace)
{
GF_AdobeKeyInfoBox *ptr = (GF_AdobeKeyInfoBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "AdobeKeyInfoBox", trace);
fprintf(trace, ">\n");
if (ptr->params) gf_isom_box_dump((GF_Box *)ptr->params, trace);
gf_isom_box_dump_done("AdobeKeyInfoBox", a, trace);
return GF_OK;
}
GF_Err flxs_dump(GF_Box *a, FILE * trace)
{
GF_AdobeFlashAccessParamsBox *ptr = (GF_AdobeFlashAccessParamsBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "AdobeFlashAccessParamsBox", trace);
fprintf(trace, ">\n");
if (ptr->metadata)
fprintf(trace, "<FmrmsV2Metadata=\"%s\"/>\n", ptr->metadata);
gf_isom_box_dump_done("AdobeFlashAccessParamsBox", a, trace);
return GF_OK;
}
GF_Err adaf_dump(GF_Box *a, FILE * trace)
{
GF_AdobeDRMAUFormatBox *ptr = (GF_AdobeDRMAUFormatBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "AdobeDRMAUFormatBox ", trace);
fprintf(trace, "SelectiveEncryption=\"%d\" IV_length=\"%d\">\n", ptr->selective_enc ? 1 : 0, ptr->IV_length);
gf_isom_box_dump_done("AdobeDRMAUFormatBox", a, trace);
return GF_OK;
}
/* Image File Format dump */
GF_Err ispe_dump(GF_Box *a, FILE * trace)
{
GF_ImageSpatialExtentsPropertyBox *ptr = (GF_ImageSpatialExtentsPropertyBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "ImageSpatialExtentsPropertyBox", trace);
fprintf(trace, "image_width=\"%d\" image_height=\"%d\">\n", ptr->image_width, ptr->image_height);
gf_isom_box_dump_done("ImageSpatialExtentsPropertyBox", a, trace);
return GF_OK;
}
GF_Err colr_dump(GF_Box *a, FILE * trace)
{
GF_ColourInformationBox *ptr = (GF_ColourInformationBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "ColourInformationBox", trace);
fprintf(trace, "colour_type=\"%s\" colour_primaries=\"%d\" transfer_characteristics=\"%d\" matrix_coefficients=\"%d\" full_range_flag=\"%d\">\n", gf_4cc_to_str(ptr->colour_type), ptr->colour_primaries, ptr->transfer_characteristics, ptr->matrix_coefficients, ptr->full_range_flag);
gf_isom_box_dump_done("ColourInformationBox", a, trace);
return GF_OK;
}
GF_Err pixi_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_PixelInformationPropertyBox *ptr = (GF_PixelInformationPropertyBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "PixelInformationPropertyBox", trace);
fprintf(trace, ">\n");
for (i = 0; i < ptr->num_channels; i++) {
fprintf(trace, "<BitPerChannel bits_per_channel=\"%d\"/>\n", ptr->bits_per_channel[i]);
}
if (!ptr->size)
fprintf(trace, "<BitPerChannel bits_per_channel=\"\"/>\n");
gf_isom_box_dump_done("PixelInformationPropertyBox", a, trace);
return GF_OK;
}
GF_Err rloc_dump(GF_Box *a, FILE * trace)
{
GF_RelativeLocationPropertyBox *ptr = (GF_RelativeLocationPropertyBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "RelativeLocationPropertyBox", trace);
fprintf(trace, "horizontal_offset=\"%d\" vertical_offset=\"%d\">\n", ptr->horizontal_offset, ptr->vertical_offset);
gf_isom_box_dump_done("RelativeLocationPropertyBox", a, trace);
return GF_OK;
}
GF_Err irot_dump(GF_Box *a, FILE * trace)
{
GF_ImageRotationBox *ptr = (GF_ImageRotationBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "ImageRotationBox", trace);
fprintf(trace, "angle=\"%d\">\n", (ptr->angle*90));
gf_isom_box_dump_done("ImageRotationBox", a, trace);
return GF_OK;
}
GF_Err ipco_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "ItemPropertyContainerBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("ItemPropertyContainerBox", a, trace);
return GF_OK;
}
GF_Err iprp_dump(GF_Box *a, FILE * trace)
{
GF_ItemPropertiesBox *ptr = (GF_ItemPropertiesBox *)a;
gf_isom_box_dump_start(a, "ItemPropertiesBox", trace);
fprintf(trace, ">\n");
if (ptr->property_container) gf_isom_box_dump(ptr->property_container, trace);
if (ptr->property_association) gf_isom_box_dump(ptr->property_association, trace);
gf_isom_box_dump_done("ItemPropertiesBox", a, trace);
return GF_OK;
}
GF_Err ipma_dump(GF_Box *a, FILE * trace)
{
u32 i, j;
GF_ItemPropertyAssociationBox *ptr = (GF_ItemPropertyAssociationBox *)a;
u32 entry_count = gf_list_count(ptr->entries);
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "ItemPropertyAssociationBox", trace);
fprintf(trace, "entry_count=\"%d\">\n", entry_count);
for (i = 0; i < entry_count; i++) {
GF_ItemPropertyAssociationEntry *entry = (GF_ItemPropertyAssociationEntry *)gf_list_get(ptr->entries, i);
u32 association_count = gf_list_count(entry->essential);
fprintf(trace, "<AssociationEntry item_ID=\"%d\" association_count=\"%d\">\n", entry->item_id, association_count);
for (j = 0; j < association_count; j++) {
Bool *ess = (Bool *)gf_list_get(entry->essential, j);
u32 *prop_index = (u32 *)gf_list_get(entry->property_index, j);
fprintf(trace, "<Property index=\"%d\" essential=\"%d\"/>\n", *prop_index, *ess);
}
fprintf(trace, "</AssociationEntry>\n");
}
if (!ptr->size) {
fprintf(trace, "<AssociationEntry item_ID=\"\" association_count=\"\">\n");
fprintf(trace, "<Property index=\"\" essential=\"\"/>\n");
fprintf(trace, "</AssociationEntry>\n");
}
gf_isom_box_dump_done("ItemPropertyAssociationBox", a, trace);
return GF_OK;
}
GF_Err auxc_dump(GF_Box *a, FILE * trace)
{
GF_AuxiliaryTypePropertyBox *ptr = (GF_AuxiliaryTypePropertyBox *)a;
gf_isom_box_dump_start(a, "AuxiliaryTypePropertyBox", trace);
fprintf(trace, "aux_type=\"%s\" ", ptr->aux_urn);
dump_data_attribute(trace, "aux_subtype", ptr->data, ptr->data_size);
fprintf(trace, ">\n");
gf_isom_box_dump_done("AuxiliaryTypePropertyBox", a, trace);
return GF_OK;
}
GF_Err oinf_dump(GF_Box *a, FILE * trace)
{
GF_OINFPropertyBox *ptr = (GF_OINFPropertyBox *)a;
gf_isom_box_dump_start(a, "OperatingPointsInformationPropertyBox", trace);
fprintf(trace, ">\n");
oinf_entry_dump(ptr->oinf, trace);
gf_isom_box_dump_done("OperatingPointsInformationPropertyBox", a, trace);
return GF_OK;
}
GF_Err tols_dump(GF_Box *a, FILE * trace)
{
GF_TargetOLSPropertyBox *ptr = (GF_TargetOLSPropertyBox *)a;
gf_isom_box_dump_start(a, "TargetOLSPropertyBox", trace);
fprintf(trace, "target_ols_index=\"%d\">\n", ptr->target_ols_index);
gf_isom_box_dump_done("TargetOLSPropertyBox", a, trace);
return GF_OK;
}
GF_Err trgr_dump(GF_Box *a, FILE * trace)
{
GF_TrackGroupBox *ptr = (GF_TrackGroupBox *) a;
gf_isom_box_dump_start(a, "TrackGroupBox", trace);
fprintf(trace, ">\n");
gf_isom_box_array_dump(ptr->groups, trace);
gf_isom_box_dump_done("TrackGroupBox", a, trace);
return GF_OK;
}
GF_Err trgt_dump(GF_Box *a, FILE * trace)
{
GF_TrackGroupTypeBox *ptr = (GF_TrackGroupTypeBox *) a;
a->type = ptr->group_type;
gf_isom_box_dump_start(a, "TrackGroupTypeBox", trace);
a->type = GF_ISOM_BOX_TYPE_TRGT;
fprintf(trace, "track_group_id=\"%d\">\n", ptr->track_group_id);
gf_isom_box_dump_done("TrackGroupTypeBox", a, trace);
return GF_OK;
}
GF_Err grpl_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "GroupListBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("GroupListBox", a, trace);
return GF_OK;
}
GF_Err grptype_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_EntityToGroupTypeBox *ptr = (GF_EntityToGroupTypeBox *) a;
a->type = ptr->grouping_type;
gf_isom_box_dump_start(a, "EntityToGroupTypeBox", trace);
a->type = GF_ISOM_BOX_TYPE_GRPT;
fprintf(trace, "group_id=\"%d\">\n", ptr->group_id);
for (i=0; i<ptr->entity_id_count ; i++)
fprintf(trace, "<EntityToGroupTypeBoxEntry EntityID=\"%d\"/>\n", ptr->entity_ids[i]);
if (!ptr->size)
fprintf(trace, "<EntityToGroupTypeBoxEntry EntityID=\"\"/>\n");
gf_isom_box_dump_done("EntityToGroupTypeBox", a, trace);
return GF_OK;
}
GF_Err stvi_dump(GF_Box *a, FILE * trace)
{
GF_StereoVideoBox *ptr = (GF_StereoVideoBox *) a;
gf_isom_box_dump_start(a, "StereoVideoBox", trace);
fprintf(trace, "single_view_allowed=\"%d\" stereo_scheme=\"%d\" ", ptr->single_view_allowed, ptr->stereo_scheme);
dump_data_attribute(trace, "stereo_indication_type", ptr->stereo_indication_type, ptr->sit_len);
fprintf(trace, ">\n");
gf_isom_box_dump_done("StereoVideoBox", a, trace);
return GF_OK;
}
GF_Err def_cont_box_dump(GF_Box *a, FILE *trace)
{
char *name = "SubTrackDefinitionBox"; //only one using generic box container for now
gf_isom_box_dump_start(a, name, trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
GF_Err fiin_dump(GF_Box *a, FILE * trace)
{
FDItemInformationBox *ptr = (FDItemInformationBox *) a;
gf_isom_box_dump_start(a, "FDItemInformationBox", trace);
fprintf(trace, ">\n");
if (ptr->partition_entries)
gf_isom_box_array_dump(ptr->partition_entries, trace);
if (ptr->session_info)
gf_isom_box_dump(ptr->session_info, trace);
if (ptr->group_id_to_name)
gf_isom_box_dump(ptr->group_id_to_name, trace);
gf_isom_box_dump_done("FDItemInformationBox", a, trace);
return GF_OK;
}
GF_Err fecr_dump(GF_Box *a, FILE * trace)
{
u32 i;
char *box_name;
FECReservoirBox *ptr = (FECReservoirBox *) a;
if (a->type==GF_ISOM_BOX_TYPE_FIRE) {
box_name = "FILEReservoirBox";
} else {
box_name = "FECReservoirBox";
}
gf_isom_box_dump_start(a, box_name, trace);
fprintf(trace, ">\n");
for (i=0; i<ptr->nb_entries; i++) {
fprintf(trace, "<%sEntry itemID=\"%d\" symbol_count=\"%d\"/>\n", box_name, ptr->entries[i].item_id, ptr->entries[i].symbol_count);
}
if (!ptr->size) {
fprintf(trace, "<%sEntry itemID=\"\" symbol_count=\"\"/>\n", box_name);
}
gf_isom_box_dump_done(box_name, a, trace);
return GF_OK;
}
GF_Err gitn_dump(GF_Box *a, FILE * trace)
{
u32 i;
GroupIdToNameBox *ptr = (GroupIdToNameBox *) a;
gf_isom_box_dump_start(a, "GroupIdToNameBox", trace);
fprintf(trace, ">\n");
for (i=0; i<ptr->nb_entries; i++) {
fprintf(trace, "<GroupIdToNameBoxEntry groupID=\"%d\" name=\"%s\"/>\n", ptr->entries[i].group_id, ptr->entries[i].name);
}
if (!ptr->size) {
fprintf(trace, "<GroupIdToNameBoxEntryEntry groupID=\"\" name=\"\"/>\n");
}
gf_isom_box_dump_done("GroupIdToNameBox", a, trace);
return GF_OK;
}
GF_Err paen_dump(GF_Box *a, FILE * trace)
{
FDPartitionEntryBox *ptr = (FDPartitionEntryBox *) a;
gf_isom_box_dump_start(a, "FDPartitionEntryBox", trace);
fprintf(trace, ">\n");
if (ptr->blocks_and_symbols)
gf_isom_box_dump(ptr->blocks_and_symbols, trace);
if (ptr->FEC_symbol_locations)
gf_isom_box_dump(ptr->FEC_symbol_locations, trace);
if (ptr->FEC_symbol_locations)
gf_isom_box_dump(ptr->FEC_symbol_locations, trace);
gf_isom_box_dump_done("FDPartitionEntryBox", a, trace);
return GF_OK;
}
GF_Err fpar_dump(GF_Box *a, FILE * trace)
{
u32 i;
FilePartitionBox *ptr = (FilePartitionBox *) a;
gf_isom_box_dump_start(a, "FilePartitionBox", trace);
fprintf(trace, "itemID=\"%d\" FEC_encoding_ID=\"%d\" FEC_instance_ID=\"%d\" max_source_block_length=\"%d\" encoding_symbol_length=\"%d\" max_number_of_encoding_symbols=\"%d\" ", ptr->itemID, ptr->FEC_encoding_ID, ptr->FEC_instance_ID, ptr->max_source_block_length, ptr->encoding_symbol_length, ptr->max_number_of_encoding_symbols);
if (ptr->scheme_specific_info)
dump_data_attribute(trace, "scheme_specific_info", (char*)ptr->scheme_specific_info, (u32)strlen(ptr->scheme_specific_info) );
fprintf(trace, ">\n");
for (i=0; i<ptr->nb_entries; i++) {
fprintf(trace, "<FilePartitionBoxEntry block_count=\"%d\" block_size=\"%d\"/>\n", ptr->entries[i].block_count, ptr->entries[i].block_size);
}
if (!ptr->size) {
fprintf(trace, "<FilePartitionBoxEntry block_count=\"\" block_size=\"\"/>\n");
}
gf_isom_box_dump_done("FilePartitionBox", a, trace);
return GF_OK;
}
GF_Err segr_dump(GF_Box *a, FILE * trace)
{
u32 i, k;
FDSessionGroupBox *ptr = (FDSessionGroupBox *) a;
gf_isom_box_dump_start(a, "FDSessionGroupBox", trace);
fprintf(trace, ">\n");
for (i=0; i<ptr->num_session_groups; i++) {
fprintf(trace, "<FDSessionGroupBoxEntry groupIDs=\"");
for (k=0; k<ptr->session_groups[i].nb_groups; k++) {
fprintf(trace, "%d ", ptr->session_groups[i].group_ids[k]);
}
fprintf(trace, "\" channels=\"");
for (k=0; k<ptr->session_groups[i].nb_channels; k++) {
fprintf(trace, "%d ", ptr->session_groups[i].channels[k]);
}
fprintf(trace, "\"/>\n");
}
if (!ptr->size) {
fprintf(trace, "<FDSessionGroupBoxEntry groupIDs=\"\" channels=\"\"/>\n");
}
gf_isom_box_dump_done("FDSessionGroupBox", a, trace);
return GF_OK;
}
GF_Err srpp_dump(GF_Box *a, FILE * trace)
{
GF_SRTPProcessBox *ptr = (GF_SRTPProcessBox *) a;
gf_isom_box_dump_start(a, "SRTPProcessBox", trace);
fprintf(trace, "encryption_algorithm_rtp=\"%d\" encryption_algorithm_rtcp=\"%d\" integrity_algorithm_rtp=\"%d\" integrity_algorithm_rtcp=\"%d\">\n", ptr->encryption_algorithm_rtp, ptr->encryption_algorithm_rtcp, ptr->integrity_algorithm_rtp, ptr->integrity_algorithm_rtcp);
if (ptr->info) gf_isom_box_dump(ptr->info, trace);
if (ptr->scheme_type) gf_isom_box_dump(ptr->scheme_type, trace);
gf_isom_box_dump_done("SRTPProcessBox", a, trace);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_HINTING
GF_Err fdpa_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_FDpacketBox *ptr = (GF_FDpacketBox *) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "FDpacketBox", trace);
fprintf(trace, "sender_current_time_present=\"%d\" expected_residual_time_present=\"%d\" session_close_bit=\"%d\" object_close_bit=\"%d\" transport_object_identifier=\"%d\">\n", ptr->info.sender_current_time_present, ptr->info.expected_residual_time_present, ptr->info.session_close_bit, ptr->info.object_close_bit, ptr->info.transport_object_identifier);
for (i=0; i<ptr->header_ext_count; i++) {
fprintf(trace, "<FDHeaderExt type=\"%d\"", ptr->headers[i].header_extension_type);
if (ptr->headers[i].header_extension_type > 127) {
dump_data_attribute(trace, "content", (char *) ptr->headers[i].content, 3);
} else if (ptr->headers[i].data_length) {
dump_data_attribute(trace, "data", ptr->headers[i].data, ptr->headers[i].data_length);
}
fprintf(trace, "/>\n");
}
if (!ptr->size) {
fprintf(trace, "<FDHeaderExt type=\"\" content=\"\" data=\"\"/>\n");
}
gf_isom_box_dump_done("FDpacketBox", a, trace);
return GF_OK;
}
GF_Err extr_dump(GF_Box *a, FILE * trace)
{
GF_ExtraDataBox *ptr = (GF_ExtraDataBox *) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "ExtraDataBox", trace);
dump_data_attribute(trace, "data", ptr->data, ptr->data_length);
fprintf(trace, ">\n");
if (ptr->feci) {
gf_isom_box_dump((GF_Box *)ptr->feci, trace);
}
gf_isom_box_dump_done("ExtraDataBox", a, trace);
return GF_OK;
}
GF_Err fdsa_dump(GF_Box *a, FILE * trace)
{
GF_Err e;
GF_HintSample *ptr = (GF_HintSample *) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "FDSampleBox", trace);
fprintf(trace, ">\n");
e = gf_isom_box_array_dump(ptr->packetTable, trace);
if (e) return e;
if (ptr->extra_data) {
e = gf_isom_box_dump((GF_Box *)ptr->extra_data, trace);
if (e) return e;
}
gf_isom_box_dump_done("FDSampleBox", a, trace);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_HINTING*/
GF_Err trik_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_TrickPlayBox *p = (GF_TrickPlayBox *) a;
gf_isom_box_dump_start(a, "TrickPlayBox", trace);
fprintf(trace, ">\n");
for (i=0; i<p->entry_count; i++) {
fprintf(trace, "<TrickPlayBoxEntry pic_type=\"%d\" dependency_level=\"%d\"/>\n", p->entries[i].pic_type, p->entries[i].dependency_level);
}
if (!p->size)
fprintf(trace, "<TrickPlayBoxEntry pic_type=\"\" dependency_level=\"\"/>\n");
gf_isom_box_dump_done("TrickPlayBox", a, trace);
return GF_OK;
}
GF_Err bloc_dump(GF_Box *a, FILE * trace)
{
GF_BaseLocationBox *p = (GF_BaseLocationBox *) a;
gf_isom_box_dump_start(a, "BaseLocationBox", trace);
fprintf(trace, "baseLocation=\"%s\" basePurlLocation=\"%s\">\n", p->baseLocation, p->basePurlLocation);
gf_isom_box_dump_done("BaseLocationBox", a, trace);
return GF_OK;
}
GF_Err ainf_dump(GF_Box *a, FILE * trace)
{
GF_AssetInformationBox *p = (GF_AssetInformationBox *) a;
gf_isom_box_dump_start(a, "AssetInformationBox", trace);
fprintf(trace, "profile_version=\"%d\" APID=\"%s\">\n", p->profile_version, p->APID);
gf_isom_box_dump_done("AssetInformationBox", a, trace);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_DUMP*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_210_2 |
crossvul-cpp_data_good_3190_1 | /*
etterfilter -- filter compiler for ettercap content filtering engine
Copyright (C) ALoR & NaGA
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 <ef.h>
#include <ef_functions.h>
#include <ec_libettercap.h>
#include <stdarg.h>
struct ec_globals *ec_gbls;
#define EF_GBL_FREE(x) do{ if (x != NULL) { free(x); x = NULL; } }while(0)
/* ef_globals */
extern FILE * yyin; /* from scanner */
extern int yyparse (void); /* from parser */
/* global options */
struct ef_globals *ef_gbls;
/*******************************************/
int main(int argc, char *argv[])
{
int ret_value = 0;
libettercap_init();
ef_globals_alloc();
select_text_interface();
libettercap_ui_init();
/* etterfilter copyright */
fprintf(stdout, "\n" EC_COLOR_BOLD "%s %s" EC_COLOR_END " copyright %s %s\n\n",
PROGRAM, EC_VERSION, EC_COPYRIGHT, EC_AUTHORS);
/* initialize the line number */
EF_GBL->lineno = 1;
/* getopt related parsing... */
parse_options(argc, argv);
/* set the input for source file */
if (EF_GBL_OPTIONS->source_file) {
yyin = fopen(EF_GBL_OPTIONS->source_file, "r");
if (yyin == NULL)
FATAL_ERROR("Input file not found !");
} else {
FATAL_ERROR("No source file.");
}
/* no buffering */
setbuf(yyin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
/* load the tables in etterfilter.tbl */
load_tables();
/* load the constants in etterfilter.cnt */
load_constants();
/* print the message */
fprintf(stdout, "\n Parsing source file \'%s\' ", EF_GBL_OPTIONS->source_file);
fflush(stdout);
ef_debug(1, "\n");
/* begin the parsing */
if (yyparse() == 0)
fprintf(stdout, " done.\n\n");
else
fprintf(stdout, "\n\nThe script contains errors...\n\n");
/* write to file */
ret_value = write_output();
if (ret_value == -E_NOTHANDLED)
FATAL_ERROR("Cannot write output file (%s): the filter is not correctly handled.", EF_GBL_OPTIONS->output_file);
else if (ret_value == -E_INVALID)
FATAL_ERROR("Cannot write output file (%s): the filter format is not correct. ", EF_GBL_OPTIONS->output_file);
ef_globals_free();
return 0;
}
/*
* print debug information
*/
void ef_debug(u_char level, const char *message, ...)
{
va_list ap;
/* if not in debug don't print anything */
if (EF_GBL_OPTIONS->debug < level)
return;
/* print the message */
va_start(ap, message);
vfprintf (stderr, message, ap);
fflush(stderr);
va_end(ap);
}
void ef_globals_alloc(void)
{
SAFE_CALLOC(ef_gbls, 1, sizeof(struct ef_globals));
return;
}
void ef_globals_free(void)
{
SAFE_FREE(ef_gbls->source_file);
SAFE_FREE(ef_gbls->output_file);
SAFE_FREE(ef_gbls);
return;
}
/* EOF */
// vim:ts=3:expandtab
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3190_1 |
crossvul-cpp_data_good_5007_1 | /* $Id: minissdpd.c,v 1.53 2016/03/01 18:06:46 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(l > (unsigned)(buf+n-p)) {
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(l > (unsigned)(buf+n-p)) {
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(l > (unsigned)(buf+n-p)) {
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(l > (unsigned)(buf+n-p)) {
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/good_5007_1 |
crossvul-cpp_data_bad_2588_5 | /*
* xmi.c -- Midi Wavetable Processing library
*
* Copyright (C) WildMIDI Developers 2001-2016
*
* This file is part of WildMIDI.
*
* WildMIDI is free software: you can redistribute and/or modify the player
* under the terms of the GNU General Public License and you can redistribute
* and/or modify the library under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of
* the licenses, or(at your option) any later version.
*
* WildMIDI is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License and
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License and the
* GNU Lesser General Public License along with WildMIDI. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "common.h"
#include "wm_error.h"
#include "wildmidi_lib.h"
#include "internal_midi.h"
#include "reverb.h"
#include "f_xmidi.h"
struct _mdi *_WM_ParseNewXmi(uint8_t *xmi_data, uint32_t xmi_size) {
struct _mdi *xmi_mdi = NULL;
uint32_t xmi_tmpdata = 0;
uint8_t xmi_formcnt = 0;
uint32_t xmi_catlen = 0;
uint32_t xmi_subformlen = 0;
uint32_t i = 0;
uint32_t j = 0;
uint32_t xmi_evntlen = 0;
uint32_t xmi_divisions = 60;
uint32_t xmi_tempo = 500000;
uint32_t xmi_sample_count = 0;
float xmi_sample_count_f = 0.0;
float xmi_sample_remainder = 0.0;
float xmi_samples_per_delta_f = 0.0;
uint8_t xmi_ch = 0;
uint8_t xmi_note = 0;
uint32_t *xmi_notelen = NULL;
uint32_t setup_ret = 0;
uint32_t xmi_delta = 0;
uint32_t xmi_lowestdelta = 0;
uint32_t xmi_evnt_cnt = 0;
if (memcmp(xmi_data,"FORM",4)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
return NULL;
}
xmi_data += 4;
xmi_size -= 4;
// bytes until next entry
xmi_tmpdata = *xmi_data++ << 24;
xmi_tmpdata |= *xmi_data++ << 16;
xmi_tmpdata |= *xmi_data++ << 8;
xmi_tmpdata |= *xmi_data++;
xmi_size -= 4;
if (memcmp(xmi_data,"XDIRINFO",8)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
return NULL;
}
xmi_data += 8;
xmi_size -= 8;
/*
0x00 0x00 0x00 0x02 at this point are unknown
so skip over them
*/
xmi_data += 4;
xmi_size -= 4;
// number of forms contained after this point
xmi_formcnt = *xmi_data++;
if (xmi_formcnt == 0) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
return NULL;
}
xmi_size--;
/*
at this stage unsure if remaining data in
this section means anything
*/
xmi_tmpdata -= 13;
xmi_data += xmi_tmpdata;
xmi_size -= xmi_tmpdata;
/* FIXME: Check: may not even need to process CAT information */
if (memcmp(xmi_data,"CAT ",4)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
return NULL;
}
xmi_data += 4;
xmi_size -= 4;
xmi_catlen = *xmi_data++ << 24;
xmi_catlen |= *xmi_data++ << 16;
xmi_catlen |= *xmi_data++ << 8;
xmi_catlen |= *xmi_data++;
xmi_size -= 4;
UNUSED(xmi_catlen);
if (memcmp(xmi_data,"XMID",4)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
return NULL;
}
xmi_data += 4;
xmi_size -= 4;
xmi_mdi = _WM_initMDI();
_WM_midi_setup_divisions(xmi_mdi, xmi_divisions);
_WM_midi_setup_tempo(xmi_mdi, xmi_tempo);
xmi_samples_per_delta_f = _WM_GetSamplesPerTick(xmi_divisions, xmi_tempo);
xmi_notelen = malloc(sizeof(uint32_t) * 16 * 128);
memset(xmi_notelen, 0, (sizeof(uint32_t) * 16 * 128));
for (i = 0; i < xmi_formcnt; i++) {
if (memcmp(xmi_data,"FORM",4)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
goto _xmi_end;
}
xmi_data += 4;
xmi_size -= 4;
xmi_subformlen = *xmi_data++ << 24;
xmi_subformlen |= *xmi_data++ << 16;
xmi_subformlen |= *xmi_data++ << 8;
xmi_subformlen |= *xmi_data++;
xmi_size -= 4;
if (memcmp(xmi_data,"XMID",4)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
goto _xmi_end;
}
xmi_data += 4;
xmi_size -= 4;
xmi_subformlen -= 4;
// Process Subform
do {
if (!memcmp(xmi_data,"TIMB",4)) {
// Holds patch information
// FIXME: May not be needed for playback as EVNT seems to
// hold patch events
xmi_data += 4;
xmi_tmpdata = *xmi_data++ << 24;
xmi_tmpdata |= *xmi_data++ << 16;
xmi_tmpdata |= *xmi_data++ << 8;
xmi_tmpdata |= *xmi_data++;
xmi_data += xmi_tmpdata;
xmi_size -= (8 + xmi_tmpdata);
xmi_subformlen -= (8 + xmi_tmpdata);
} else if (!memcmp(xmi_data,"RBRN",4)) {
// Unknown what this is
// FIXME: May not be needed for playback
xmi_data += 4;
xmi_tmpdata = *xmi_data++ << 24;
xmi_tmpdata |= *xmi_data++ << 16;
xmi_tmpdata |= *xmi_data++ << 8;
xmi_tmpdata |= *xmi_data++;
xmi_data += xmi_tmpdata;
xmi_size -= (8 + xmi_tmpdata);
xmi_subformlen -= (8 + xmi_tmpdata);
} else if (!memcmp(xmi_data,"EVNT",4)) {
// EVNT is where all the MIDI music information is stored
xmi_data += 4;
xmi_evnt_cnt++;
xmi_evntlen = *xmi_data++ << 24;
xmi_evntlen |= *xmi_data++ << 16;
xmi_evntlen |= *xmi_data++ << 8;
xmi_evntlen |= *xmi_data++;
xmi_size -= 8;
xmi_subformlen -= 8;
do {
if (*xmi_data < 0x80) {
xmi_delta = 0;
if (*xmi_data > 0x7f) {
while (*xmi_data > 0x7f) {
xmi_delta = (xmi_delta << 7) | (*xmi_data++ & 0x7f);
xmi_size--;
xmi_evntlen--;
xmi_subformlen--;
}
}
xmi_delta = (xmi_delta << 7) | (*xmi_data++ & 0x7f);
xmi_size--;
xmi_evntlen--;
xmi_subformlen--;
do {
// determine delta till next event
if ((xmi_lowestdelta != 0) && (xmi_lowestdelta <= xmi_delta)) {
xmi_tmpdata = xmi_lowestdelta;
} else {
xmi_tmpdata = xmi_delta;
}
xmi_sample_count_f= (((float) xmi_tmpdata * xmi_samples_per_delta_f) + xmi_sample_remainder);
xmi_sample_count = (uint32_t) xmi_sample_count_f;
xmi_sample_remainder = xmi_sample_count_f - (float) xmi_sample_count;
xmi_mdi->events[xmi_mdi->event_count - 1].samples_to_next += xmi_sample_count;
xmi_mdi->extra_info.approx_total_samples += xmi_sample_count;
xmi_lowestdelta = 0;
// scan through on notes
for (j = 0; j < (16*128); j++) {
// only want notes that are on
if (xmi_notelen[j] == 0) continue;
// remove delta to next event from on notes
xmi_notelen[j] -= xmi_tmpdata;
// Check if we need to turn note off
if (xmi_notelen[j] == 0) {
xmi_ch = j / 128;
xmi_note = j - (xmi_ch * 128);
_WM_midi_setup_noteoff(xmi_mdi, xmi_ch, xmi_note, 0);
} else {
// otherwise work out new lowest delta
if ((xmi_lowestdelta == 0) || (xmi_lowestdelta > xmi_notelen[j])) {
xmi_lowestdelta = xmi_notelen[j];
}
}
}
xmi_delta -= xmi_tmpdata;
} while (xmi_delta);
} else {
if ((xmi_data[0] == 0xff) && (xmi_data[1] == 0x51) && (xmi_data[2] == 0x03)) {
// Ignore tempo events
setup_ret = 6;
goto _XMI_Next_Event;
}
if ((setup_ret = _WM_SetupMidiEvent(xmi_mdi,xmi_data,0)) == 0) {
goto _xmi_end;
}
if ((*xmi_data & 0xf0) == 0x90) {
// Note on has extra data stating note length
xmi_ch = *xmi_data & 0x0f;
xmi_note = xmi_data[1];
xmi_data += setup_ret;
xmi_size -= setup_ret;
xmi_evntlen -= setup_ret;
xmi_subformlen -= setup_ret;
xmi_tmpdata = 0;
if (*xmi_data > 0x7f) {
while (*xmi_data > 0x7f) {
xmi_tmpdata = (xmi_tmpdata << 7) | (*xmi_data++ & 0x7f);
xmi_size--;
xmi_evntlen--;
xmi_subformlen--;
}
}
xmi_tmpdata = (xmi_tmpdata << 7) | (*xmi_data++ & 0x7f);
xmi_size--;
xmi_evntlen--;
xmi_subformlen--;
// store length
xmi_notelen[128 * xmi_ch + xmi_note] = xmi_tmpdata;
if ((xmi_tmpdata > 0) && ((xmi_lowestdelta == 0) || (xmi_tmpdata < xmi_lowestdelta))) {
xmi_lowestdelta = xmi_tmpdata;
}
} else {
_XMI_Next_Event:
xmi_data += setup_ret;
xmi_size -= setup_ret;
xmi_evntlen -= setup_ret;
xmi_subformlen -= setup_ret;
}
}
} while (xmi_evntlen);
} else {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
goto _xmi_end;
}
} while (xmi_subformlen);
}
// Finalise mdi structure
if ((xmi_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0);
goto _xmi_end;
}
xmi_mdi->extra_info.current_sample = 0;
xmi_mdi->current_event = &xmi_mdi->events[0];
xmi_mdi->samples_to_mix = 0;
xmi_mdi->note = NULL;
/* More than 1 event form in XMI means treat as type 2 */
if (xmi_evnt_cnt > 1) {
xmi_mdi->is_type2 = 1;
}
_WM_ResetToStart(xmi_mdi);
_xmi_end:
if (xmi_notelen != NULL) free(xmi_notelen);
if (xmi_mdi->reverb) return (xmi_mdi);
_WM_freeMDI(xmi_mdi);
return NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2588_5 |
crossvul-cpp_data_good_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 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;
/* We need the flags, at a minimum. */
if (opt_len < 4)
return 0;
if (flags & TH_SYN)
return 0;
if (mdss->flags & MP_DSS_F)
ND_PRINT((ndo, " fin"));
opt += 4;
opt_len -= 4;
if (mdss->flags & MP_DSS_A) {
/* Ack present */
ND_PRINT((ndo, " ack "));
/*
* If the a flag is set, we have an 8-byte ack; if it's
* clear, we have a 4-byte ack.
*/
if (mdss->flags & MP_DSS_a) {
if (opt_len < 8)
return 0;
ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt)));
opt += 8;
opt_len -= 8;
} else {
if (opt_len < 4)
return 0;
ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt)));
opt += 4;
opt_len -= 4;
}
}
if (mdss->flags & MP_DSS_M) {
/*
* Data Sequence Number (DSN), Subflow Sequence Number (SSN),
* Data-Level Length present, and Checksum possibly present.
*/
ND_PRINT((ndo, " seq "));
/*
* If the m flag is set, we have an 8-byte NDS; if it's clear,
* we have a 4-byte DSN.
*/
if (mdss->flags & MP_DSS_m) {
if (opt_len < 8)
return 0;
ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt)));
opt += 8;
opt_len -= 8;
} else {
if (opt_len < 4)
return 0;
ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt)));
opt += 4;
opt_len -= 4;
}
if (opt_len < 4)
return 0;
ND_PRINT((ndo, " subseq %u", EXTRACT_32BITS(opt)));
opt += 4;
opt_len -= 4;
if (opt_len < 2)
return 0;
ND_PRINT((ndo, " len %u", EXTRACT_16BITS(opt)));
opt += 2;
opt_len -= 2;
/*
* The Checksum is present only if negotiated.
* If there are at least 2 bytes left, process the next 2
* bytes as the Checksum.
*/
if (opt_len >= 2) {
ND_PRINT((ndo, " csum 0x%x", EXTRACT_16BITS(opt)));
opt_len -= 2;
}
}
if (opt_len != 0)
return 0;
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/good_2716_0 |
crossvul-cpp_data_good_2588_5 | /*
* xmi.c -- Midi Wavetable Processing library
*
* Copyright (C) WildMIDI Developers 2001-2016
*
* This file is part of WildMIDI.
*
* WildMIDI is free software: you can redistribute and/or modify the player
* under the terms of the GNU General Public License and you can redistribute
* and/or modify the library under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of
* the licenses, or(at your option) any later version.
*
* WildMIDI is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License and
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License and the
* GNU Lesser General Public License along with WildMIDI. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "common.h"
#include "wm_error.h"
#include "wildmidi_lib.h"
#include "internal_midi.h"
#include "reverb.h"
#include "f_xmidi.h"
struct _mdi *_WM_ParseNewXmi(uint8_t *xmi_data, uint32_t xmi_size) {
struct _mdi *xmi_mdi = NULL;
uint32_t xmi_tmpdata = 0;
uint8_t xmi_formcnt = 0;
uint32_t xmi_catlen = 0;
uint32_t xmi_subformlen = 0;
uint32_t i = 0;
uint32_t j = 0;
uint32_t xmi_evntlen = 0;
uint32_t xmi_divisions = 60;
uint32_t xmi_tempo = 500000;
uint32_t xmi_sample_count = 0;
float xmi_sample_count_f = 0.0;
float xmi_sample_remainder = 0.0;
float xmi_samples_per_delta_f = 0.0;
uint8_t xmi_ch = 0;
uint8_t xmi_note = 0;
uint32_t *xmi_notelen = NULL;
uint32_t setup_ret = 0;
uint32_t xmi_delta = 0;
uint32_t xmi_lowestdelta = 0;
uint32_t xmi_evnt_cnt = 0;
if (memcmp(xmi_data,"FORM",4)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
return NULL;
}
xmi_data += 4;
xmi_size -= 4;
// bytes until next entry
xmi_tmpdata = *xmi_data++ << 24;
xmi_tmpdata |= *xmi_data++ << 16;
xmi_tmpdata |= *xmi_data++ << 8;
xmi_tmpdata |= *xmi_data++;
xmi_size -= 4;
if (memcmp(xmi_data,"XDIRINFO",8)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
return NULL;
}
xmi_data += 8;
xmi_size -= 8;
/*
0x00 0x00 0x00 0x02 at this point are unknown
so skip over them
*/
xmi_data += 4;
xmi_size -= 4;
// number of forms contained after this point
xmi_formcnt = *xmi_data++;
if (xmi_formcnt == 0) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
return NULL;
}
xmi_size--;
/*
at this stage unsure if remaining data in
this section means anything
*/
xmi_tmpdata -= 13;
xmi_data += xmi_tmpdata;
xmi_size -= xmi_tmpdata;
/* FIXME: Check: may not even need to process CAT information */
if (memcmp(xmi_data,"CAT ",4)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
return NULL;
}
xmi_data += 4;
xmi_size -= 4;
xmi_catlen = *xmi_data++ << 24;
xmi_catlen |= *xmi_data++ << 16;
xmi_catlen |= *xmi_data++ << 8;
xmi_catlen |= *xmi_data++;
xmi_size -= 4;
UNUSED(xmi_catlen);
if (memcmp(xmi_data,"XMID",4)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
return NULL;
}
xmi_data += 4;
xmi_size -= 4;
xmi_mdi = _WM_initMDI();
_WM_midi_setup_divisions(xmi_mdi, xmi_divisions);
_WM_midi_setup_tempo(xmi_mdi, xmi_tempo);
xmi_samples_per_delta_f = _WM_GetSamplesPerTick(xmi_divisions, xmi_tempo);
xmi_notelen = malloc(sizeof(uint32_t) * 16 * 128);
memset(xmi_notelen, 0, (sizeof(uint32_t) * 16 * 128));
for (i = 0; i < xmi_formcnt; i++) {
if (memcmp(xmi_data,"FORM",4)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
goto _xmi_end;
}
xmi_data += 4;
xmi_size -= 4;
xmi_subformlen = *xmi_data++ << 24;
xmi_subformlen |= *xmi_data++ << 16;
xmi_subformlen |= *xmi_data++ << 8;
xmi_subformlen |= *xmi_data++;
xmi_size -= 4;
if (memcmp(xmi_data,"XMID",4)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
goto _xmi_end;
}
xmi_data += 4;
xmi_size -= 4;
xmi_subformlen -= 4;
// Process Subform
do {
if (!memcmp(xmi_data,"TIMB",4)) {
// Holds patch information
// FIXME: May not be needed for playback as EVNT seems to
// hold patch events
xmi_data += 4;
xmi_tmpdata = *xmi_data++ << 24;
xmi_tmpdata |= *xmi_data++ << 16;
xmi_tmpdata |= *xmi_data++ << 8;
xmi_tmpdata |= *xmi_data++;
xmi_data += xmi_tmpdata;
xmi_size -= (8 + xmi_tmpdata);
xmi_subformlen -= (8 + xmi_tmpdata);
} else if (!memcmp(xmi_data,"RBRN",4)) {
// Unknown what this is
// FIXME: May not be needed for playback
xmi_data += 4;
xmi_tmpdata = *xmi_data++ << 24;
xmi_tmpdata |= *xmi_data++ << 16;
xmi_tmpdata |= *xmi_data++ << 8;
xmi_tmpdata |= *xmi_data++;
xmi_data += xmi_tmpdata;
xmi_size -= (8 + xmi_tmpdata);
xmi_subformlen -= (8 + xmi_tmpdata);
} else if (!memcmp(xmi_data,"EVNT",4)) {
// EVNT is where all the MIDI music information is stored
xmi_data += 4;
xmi_evnt_cnt++;
xmi_evntlen = *xmi_data++ << 24;
xmi_evntlen |= *xmi_data++ << 16;
xmi_evntlen |= *xmi_data++ << 8;
xmi_evntlen |= *xmi_data++;
xmi_size -= 8;
xmi_subformlen -= 8;
do {
if (*xmi_data < 0x80) {
xmi_delta = 0;
if (*xmi_data > 0x7f) {
while (*xmi_data > 0x7f) {
xmi_delta = (xmi_delta << 7) | (*xmi_data++ & 0x7f);
xmi_size--;
xmi_evntlen--;
xmi_subformlen--;
}
}
xmi_delta = (xmi_delta << 7) | (*xmi_data++ & 0x7f);
xmi_size--;
xmi_evntlen--;
xmi_subformlen--;
do {
// determine delta till next event
if ((xmi_lowestdelta != 0) && (xmi_lowestdelta <= xmi_delta)) {
xmi_tmpdata = xmi_lowestdelta;
} else {
xmi_tmpdata = xmi_delta;
}
xmi_sample_count_f= (((float) xmi_tmpdata * xmi_samples_per_delta_f) + xmi_sample_remainder);
xmi_sample_count = (uint32_t) xmi_sample_count_f;
xmi_sample_remainder = xmi_sample_count_f - (float) xmi_sample_count;
xmi_mdi->events[xmi_mdi->event_count - 1].samples_to_next += xmi_sample_count;
xmi_mdi->extra_info.approx_total_samples += xmi_sample_count;
xmi_lowestdelta = 0;
// scan through on notes
for (j = 0; j < (16*128); j++) {
// only want notes that are on
if (xmi_notelen[j] == 0) continue;
// remove delta to next event from on notes
xmi_notelen[j] -= xmi_tmpdata;
// Check if we need to turn note off
if (xmi_notelen[j] == 0) {
xmi_ch = j / 128;
xmi_note = j - (xmi_ch * 128);
_WM_midi_setup_noteoff(xmi_mdi, xmi_ch, xmi_note, 0);
} else {
// otherwise work out new lowest delta
if ((xmi_lowestdelta == 0) || (xmi_lowestdelta > xmi_notelen[j])) {
xmi_lowestdelta = xmi_notelen[j];
}
}
}
xmi_delta -= xmi_tmpdata;
} while (xmi_delta);
} else {
if ((xmi_data[0] == 0xff) && (xmi_data[1] == 0x51) && (xmi_data[2] == 0x03)) {
// Ignore tempo events
setup_ret = 6;
goto _XMI_Next_Event;
}
if ((setup_ret = _WM_SetupMidiEvent(xmi_mdi,xmi_data, xmi_size, 0)) == 0) {
goto _xmi_end;
}
if ((*xmi_data & 0xf0) == 0x90) {
// Note on has extra data stating note length
xmi_ch = *xmi_data & 0x0f;
xmi_note = xmi_data[1];
xmi_data += setup_ret;
xmi_size -= setup_ret;
xmi_evntlen -= setup_ret;
xmi_subformlen -= setup_ret;
xmi_tmpdata = 0;
if (*xmi_data > 0x7f) {
while (*xmi_data > 0x7f) {
xmi_tmpdata = (xmi_tmpdata << 7) | (*xmi_data++ & 0x7f);
xmi_size--;
xmi_evntlen--;
xmi_subformlen--;
}
}
xmi_tmpdata = (xmi_tmpdata << 7) | (*xmi_data++ & 0x7f);
xmi_size--;
xmi_evntlen--;
xmi_subformlen--;
// store length
xmi_notelen[128 * xmi_ch + xmi_note] = xmi_tmpdata;
if ((xmi_tmpdata > 0) && ((xmi_lowestdelta == 0) || (xmi_tmpdata < xmi_lowestdelta))) {
xmi_lowestdelta = xmi_tmpdata;
}
} else {
_XMI_Next_Event:
xmi_data += setup_ret;
xmi_size -= setup_ret;
xmi_evntlen -= setup_ret;
xmi_subformlen -= setup_ret;
}
}
} while (xmi_evntlen);
} else {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
goto _xmi_end;
}
} while (xmi_subformlen);
}
// Finalise mdi structure
if ((xmi_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0);
goto _xmi_end;
}
xmi_mdi->extra_info.current_sample = 0;
xmi_mdi->current_event = &xmi_mdi->events[0];
xmi_mdi->samples_to_mix = 0;
xmi_mdi->note = NULL;
/* More than 1 event form in XMI means treat as type 2 */
if (xmi_evnt_cnt > 1) {
xmi_mdi->is_type2 = 1;
}
_WM_ResetToStart(xmi_mdi);
_xmi_end:
if (xmi_notelen != NULL) free(xmi_notelen);
if (xmi_mdi->reverb) return (xmi_mdi);
_WM_freeMDI(xmi_mdi);
return NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2588_5 |
crossvul-cpp_data_bad_2691_1 | /*
* 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 (netal == 0)
ND_PRINT((ndo, "\n\t %s", etheraddr_string(ndo, snpa)));
else
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, neta, netal)));
break;
}
case ESIS_PDU_ESH:
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_number = *pptr;
pptr++;
li--;
ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number));
while (source_address_number > 0) {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s",
source_address_length,
isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
source_address_number--;
}
break;
case ESIS_PDU_ISH: {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
break;
}
default:
if (ndo->ndo_vflag <= 1) {
if (pptr < ndo->ndo_snapend)
print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr);
}
return;
}
/* now walk the options */
while (li != 0) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return;
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return;
}
li -= opli;
tptr = pptr;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(esis_option_values,"Unknown",op),
op,
opli));
switch (op) {
case ESIS_OPTION_ES_CONF_TIME:
if (opli == 2) {
ND_TCHECK2(*pptr, 2);
ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr)));
} else
ND_PRINT((ndo, "(bad length)"));
break;
case ESIS_OPTION_PROTOCOLS:
while (opli>0) {
ND_TCHECK(*pptr);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (opli>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
opli--;
}
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
case ESIS_OPTION_QOS_MAINTENANCE:
case ESIS_OPTION_SECURITY:
case ESIS_OPTION_PRIORITY:
case ESIS_OPTION_ADDRESS_MASK:
case ESIS_OPTION_SNPA_MASK:
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
trunc:
return;
}
static void
isis_print_mcid(netdissect_options *ndo,
const struct isis_spb_mcid *mcid)
{
int i;
ND_TCHECK(*mcid);
ND_PRINT((ndo, "ID: %d, Name: ", mcid->format_id));
if (fn_printzp(ndo, mcid->name, 32, ndo->ndo_snapend))
goto trunc;
ND_PRINT((ndo, "\n\t Lvl: %d", EXTRACT_16BITS(mcid->revision_lvl)));
ND_PRINT((ndo, ", Digest: "));
for(i=0;i<16;i++)
ND_PRINT((ndo, "%.2x ", mcid->digest[i]));
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static int
isis_print_mt_port_cap_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len;
const struct isis_subtlv_spb_mcid *subtlv_spb_mcid;
int i;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
/*len -= TLV_TYPE_LEN_OFFSET;*/
len = len -2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_MCID:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN);
subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr;
ND_PRINT((ndo, "\n\t MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
ND_PRINT((ndo, "\n\t AUX-MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
tptr = tptr + sizeof(struct isis_subtlv_spb_mcid);
len = len - sizeof(struct isis_subtlv_spb_mcid);
break;
}
case ISIS_SUBTLV_SPB_DIGEST:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN);
ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d",
(*(tptr) >> 5), (((*tptr)>> 4) & 0x01),
((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03)));
tptr++;
ND_PRINT((ndo, "\n\t Digest: "));
for(i=1;i<=8; i++)
{
ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr)));
if (i%4 == 0 && i != 8)
ND_PRINT((ndo, "\n\t "));
tptr = tptr + 4;
}
len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_BVID:
{
ND_TCHECK2(*(tptr), stlv_len);
while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN)
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN);
ND_PRINT((ndo, "\n\t ECT: %08x",
EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ",
(EXTRACT_16BITS (tptr) >> 4) ,
(EXTRACT_16BITS (tptr) >> 3) & 0x01,
(EXTRACT_16BITS (tptr) >> 2) & 0x01));
tptr = tptr + 2;
len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
}
break;
}
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static int
isis_print_mt_capability_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len, tmp;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
len = len - 2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_INSTANCE:
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN);
ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr)));
tptr = tptr + 2;
ND_PRINT((ndo, "\n\t RES: %d",
EXTRACT_16BITS(tptr) >> 5));
ND_PRINT((ndo, ", V: %d",
(EXTRACT_16BITS(tptr) >> 4) & 0x0001));
ND_PRINT((ndo, ", SPSource-ID: %d",
(EXTRACT_32BITS(tptr) & 0x000fffff)));
tptr = tptr+4;
ND_PRINT((ndo, ", No of Trees: %x", *(tptr)));
tmp = *(tptr++);
len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
while (tmp)
{
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN);
ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d",
*(tptr) >> 7, (*(tptr) >> 6) & 0x01,
(*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f)));
tptr++;
ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr + 4;
ND_PRINT((ndo, ", BVID: %d, SPVID: %d",
(EXTRACT_24BITS(tptr) >> 12) & 0x000fff,
EXTRACT_24BITS(tptr) & 0x000fff));
tptr = tptr + 3;
len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
tmp--;
}
break;
case ISIS_SUBTLV_SPBM_SI:
ND_TCHECK2(*tptr, 8);
ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr)));
tptr = tptr+2;
ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12,
(EXTRACT_16BITS(tptr)) & 0x0fff));
tptr = tptr+2;
len = len - 8;
stlv_len = stlv_len - 8;
while (stlv_len >= 4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d",
(EXTRACT_32BITS(tptr) >> 31),
(EXTRACT_32BITS(tptr) >> 30) & 0x01,
(EXTRACT_32BITS(tptr) >> 24) & 0x03f,
(EXTRACT_32BITS(tptr)) & 0x0ffffff));
tptr = tptr + 4;
len = len - 4;
stlv_len = stlv_len - 4;
}
break;
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
/* shared routine for printing system, node and lsp-ids */
static char *
isis_print_id(const uint8_t *cp, int id_len)
{
int i;
static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")];
char *pos = id;
for (i = 1; i <= SYSTEM_ID_LEN; i++) {
snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++);
pos += strlen(pos);
if (i == 2 || i == 4)
*pos++ = '.';
}
if (id_len >= NODE_ID_LEN) {
snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++);
pos += strlen(pos);
}
if (id_len == LSP_ID_LEN)
snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp);
return (id);
}
/* print the 4-byte metric block which is common found in the old-style TLVs */
static int
isis_print_metric_block(netdissect_options *ndo,
const struct isis_metric_block *isis_metric_block)
{
ND_PRINT((ndo, ", Default Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_default),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_delay))
ND_PRINT((ndo, "\n\t\t Delay Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_delay),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_expense))
ND_PRINT((ndo, "\n\t\t Expense Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_expense),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_error))
ND_PRINT((ndo, "\n\t\t Error Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_error),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_error) ? "External" : "Internal"));
return(1); /* everything is ok */
}
static int
isis_print_tlv_ip_reach(netdissect_options *ndo,
const uint8_t *cp, const char *ident, int length)
{
int prefix_len;
const struct isis_tlv_ip_reach *tlv_ip_reach;
tlv_ip_reach = (const struct isis_tlv_ip_reach *)cp;
while (length > 0) {
if ((size_t)length < sizeof(*tlv_ip_reach)) {
ND_PRINT((ndo, "short IPv4 Reachability (%d vs %lu)",
length,
(unsigned long)sizeof(*tlv_ip_reach)));
return (0);
}
if (!ND_TTEST(*tlv_ip_reach))
return (0);
prefix_len = mask2plen(EXTRACT_32BITS(tlv_ip_reach->mask));
if (prefix_len == -1)
ND_PRINT((ndo, "%sIPv4 prefix: %s mask %s",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
ipaddr_string(ndo, (tlv_ip_reach->mask))));
else
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
prefix_len));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u, %s",
ISIS_LSP_TLV_METRIC_UPDOWN(tlv_ip_reach->isis_metric_block.metric_default) ? "down" : "up",
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_default),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_delay))
ND_PRINT((ndo, "%s Delay Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_delay),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_expense))
ND_PRINT((ndo, "%s Expense Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_expense),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_error))
ND_PRINT((ndo, "%s Error Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_error),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_error) ? "External" : "Internal"));
length -= sizeof(struct isis_tlv_ip_reach);
tlv_ip_reach++;
}
return (1);
}
/*
* this is the common IP-REACH subTLV decoder it is called
* from various EXTD-IP REACH TLVs (135,235,236,237)
*/
static int
isis_print_ip_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int subt, int subl,
const char *ident)
{
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_ip_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr,subl);
switch(subt) {
case ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR: /* fall through */
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32:
while (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x (=%u)",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr)));
tptr+=4;
subl-=4;
}
break;
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64:
while (subl >= 8) {
ND_PRINT((ndo, ", 0x%08x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr+4)));
tptr+=8;
subl-=8;
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
ND_PRINT((ndo, "%s", ident));
ND_PRINT((ndo, "%s", tstr));
return(0);
}
/*
* this is the common IS-REACH subTLV decoder it is called
* from isis_print_ext_is_reach()
*/
static int
isis_print_is_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, u_int subt, u_int subl,
const char *ident)
{
u_int te_class,priority_level,gmpls_switch_cap;
union { /* int to float conversion buffer for several subTLVs */
float f;
uint32_t i;
} bw;
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr, subl);
switch(subt) {
case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID:
if (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr)));
if (subl == 8) /* rfc4205 */
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR:
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR:
if (subl >= sizeof(struct in_addr))
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW :
case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW:
if (subl >= 4) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW :
if (subl >= 32) {
for (te_class = 0; te_class < 8; te_class++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD:
ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)",
ident,
tok2str(diffserv_te_bc_values, "unknown", *tptr),
*tptr));
tptr++;
/* decode BCs until the subTLV ends */
for (te_class = 0; te_class < (subl-1)/4; te_class++) {
ND_TCHECK2(*tptr, 4);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC:
if (subl >= 3)
ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE:
if (subl == 2) {
ND_PRINT((ndo, ", [ %s ] (0x%04x)",
bittok2str(isis_subtlv_link_attribute_values,
"Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE:
if (subl >= 2) {
ND_PRINT((ndo, ", %s, Priority %u",
bittok2str(gmpls_link_prot_values, "none", *tptr),
*(tptr+1)));
}
break;
case ISIS_SUBTLV_SPB_METRIC:
if (subl >= 6) {
ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr)));
tptr=tptr+3;
ND_PRINT((ndo, ", P: %u", *(tptr)));
tptr++;
ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR:
if (subl >= 36) {
gmpls_switch_cap = *tptr;
ND_PRINT((ndo, "%s Interface Switching Capability:%s",
ident,
tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap)));
ND_PRINT((ndo, ", LSP Encoding: %s",
tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1))));
tptr+=4;
ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident));
for (priority_level = 0; priority_level < 8; priority_level++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s priority level %d: %.3f Mbps",
ident,
priority_level,
bw.f * 8 / 1000000));
tptr+=4;
}
subl-=36;
switch (gmpls_switch_cap) {
case GMPLS_PSC1:
case GMPLS_PSC2:
case GMPLS_PSC3:
case GMPLS_PSC4:
ND_TCHECK2(*tptr, 6);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4)));
break;
case GMPLS_TSC:
ND_TCHECK2(*tptr, 8);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Indication %s", ident,
tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4))));
break;
default:
/* there is some optional stuff left to decode but this is as of yet
not specified so just lets hexdump what is left */
if(subl>0){
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
}
}
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
return(0);
}
/*
* this is the common IS-REACH decoder it is called
* from various EXTD-IS REACH style TLVs (22,24,222)
*/
static int
isis_print_ext_is_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, int tlv_type)
{
char ident_buffer[20];
int subtlv_type,subtlv_len,subtlv_sum_len;
int proc_bytes = 0; /* how many bytes did we process ? */
if (!ND_TTEST2(*tptr, NODE_ID_LEN))
return(0);
ND_PRINT((ndo, "%sIS Neighbor: %s", ident, isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
if (tlv_type != ISIS_TLV_IS_ALIAS_ID) { /* the Alias TLV Metric field is implicit 0 */
if (!ND_TTEST2(*tptr, 3)) /* and is therefore skipped */
return(0);
ND_PRINT((ndo, ", Metric: %d", EXTRACT_24BITS(tptr)));
tptr+=3;
}
if (!ND_TTEST2(*tptr, 1))
return(0);
subtlv_sum_len=*(tptr++); /* read out subTLV length */
proc_bytes=NODE_ID_LEN+3+1;
ND_PRINT((ndo, ", %ssub-TLVs present",subtlv_sum_len ? "" : "no "));
if (subtlv_sum_len) {
ND_PRINT((ndo, " (%u)", subtlv_sum_len));
while (subtlv_sum_len>0) {
if (!ND_TTEST2(*tptr,2))
return(0);
subtlv_type=*(tptr++);
subtlv_len=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_is_reach_subtlv(ndo, tptr, subtlv_type, subtlv_len, ident_buffer))
return(0);
tptr+=subtlv_len;
subtlv_sum_len-=(subtlv_len+2);
proc_bytes+=(subtlv_len+2);
}
}
return(proc_bytes);
}
/*
* this is the common Multi Topology ID decoder
* it is called from various MT-TLVs (222,229,235,237)
*/
static int
isis_print_mtid(netdissect_options *ndo,
const uint8_t *tptr, const char *ident)
{
if (!ND_TTEST2(*tptr, 2))
return(0);
ND_PRINT((ndo, "%s%s",
ident,
tok2str(isis_mt_values,
"Reserved for IETF Consensus",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)))));
ND_PRINT((ndo, " Topology (0x%03x), Flags: [%s]",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)),
bittok2str(isis_mt_flag_values, "none",ISIS_MASK_MTFLAGS(EXTRACT_16BITS(tptr)))));
return(2);
}
/*
* this is the common extended IP reach decoder
* it is called from TLVs (135,235,236,237)
* we process the TLV and optional subTLVs and return
* the amount of processed bytes
*/
static int
isis_print_extd_ip_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, uint16_t afi)
{
char ident_buffer[20];
uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */
u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen;
if (!ND_TTEST2(*tptr, 4))
return (0);
metric = EXTRACT_32BITS(tptr);
processed=4;
tptr+=4;
if (afi == AF_INET) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */
return (0);
status_byte=*(tptr++);
bit_length = status_byte&0x3f;
if (bit_length > 32) {
ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed++;
} else if (afi == AF_INET6) {
if (!ND_TTEST2(*tptr, 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_2691_1 |
crossvul-cpp_data_good_3255_1 | /*
* NET An implementation of the SOCKET network access protocol.
*
* Version: @(#)socket.c 1.1.93 18/02/95
*
* Authors: Orest Zborowski, <obz@Kodak.COM>
* Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
*
* Fixes:
* Anonymous : NOTSOCK/BADF cleanup. Error fix in
* shutdown()
* Alan Cox : verify_area() fixes
* Alan Cox : Removed DDI
* Jonathan Kamens : SOCK_DGRAM reconnect bug
* Alan Cox : Moved a load of checks to the very
* top level.
* Alan Cox : Move address structures to/from user
* mode above the protocol layers.
* Rob Janssen : Allow 0 length sends.
* Alan Cox : Asynchronous I/O support (cribbed from the
* tty drivers).
* Niibe Yutaka : Asynchronous I/O for writes (4.4BSD style)
* Jeff Uphoff : Made max number of sockets command-line
* configurable.
* Matti Aarnio : Made the number of sockets dynamic,
* to be allocated when needed, and mr.
* Uphoff's max is used as max to be
* allowed to allocate.
* Linus : Argh. removed all the socket allocation
* altogether: it's in the inode now.
* Alan Cox : Made sock_alloc()/sock_release() public
* for NetROM and future kernel nfsd type
* stuff.
* Alan Cox : sendmsg/recvmsg basics.
* Tom Dyas : Export net symbols.
* Marcin Dalecki : Fixed problems with CONFIG_NET="n".
* Alan Cox : Added thread locking to sys_* calls
* for sockets. May have errors at the
* moment.
* Kevin Buhr : Fixed the dumb errors in the above.
* Andi Kleen : Some small cleanups, optimizations,
* and fixed a copy_from_user() bug.
* Tigran Aivazian : sys_send(args) calls sys_sendto(args, NULL, 0)
* Tigran Aivazian : Made listen(2) backlog sanity checks
* protocol-independent
*
*
* 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 module is effectively the top level interface to the BSD socket
* paradigm.
*
* Based upon Swansea University Computer Society NET3.039
*/
#include <linux/mm.h>
#include <linux/socket.h>
#include <linux/file.h>
#include <linux/net.h>
#include <linux/interrupt.h>
#include <linux/thread_info.h>
#include <linux/rcupdate.h>
#include <linux/netdevice.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/mutex.h>
#include <linux/if_bridge.h>
#include <linux/if_frad.h>
#include <linux/if_vlan.h>
#include <linux/ptp_classify.h>
#include <linux/init.h>
#include <linux/poll.h>
#include <linux/cache.h>
#include <linux/module.h>
#include <linux/highmem.h>
#include <linux/mount.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/compat.h>
#include <linux/kmod.h>
#include <linux/audit.h>
#include <linux/wireless.h>
#include <linux/nsproxy.h>
#include <linux/magic.h>
#include <linux/slab.h>
#include <linux/xattr.h>
#include <linux/uaccess.h>
#include <asm/unistd.h>
#include <net/compat.h>
#include <net/wext.h>
#include <net/cls_cgroup.h>
#include <net/sock.h>
#include <linux/netfilter.h>
#include <linux/if_tun.h>
#include <linux/ipv6_route.h>
#include <linux/route.h>
#include <linux/sockios.h>
#include <linux/atalk.h>
#include <net/busy_poll.h>
#include <linux/errqueue.h>
#ifdef CONFIG_NET_RX_BUSY_POLL
unsigned int sysctl_net_busy_read __read_mostly;
unsigned int sysctl_net_busy_poll __read_mostly;
#endif
static ssize_t sock_read_iter(struct kiocb *iocb, struct iov_iter *to);
static ssize_t sock_write_iter(struct kiocb *iocb, struct iov_iter *from);
static int sock_mmap(struct file *file, struct vm_area_struct *vma);
static int sock_close(struct inode *inode, struct file *file);
static unsigned int sock_poll(struct file *file,
struct poll_table_struct *wait);
static long sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
#ifdef CONFIG_COMPAT
static long compat_sock_ioctl(struct file *file,
unsigned int cmd, unsigned long arg);
#endif
static int sock_fasync(int fd, struct file *filp, int on);
static ssize_t sock_sendpage(struct file *file, struct page *page,
int offset, size_t size, loff_t *ppos, int more);
static ssize_t sock_splice_read(struct file *file, loff_t *ppos,
struct pipe_inode_info *pipe, size_t len,
unsigned int flags);
/*
* Socket files have a set of 'special' operations as well as the generic file ones. These don't appear
* in the operation structures but are done directly via the socketcall() multiplexor.
*/
static const struct file_operations socket_file_ops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read_iter = sock_read_iter,
.write_iter = sock_write_iter,
.poll = sock_poll,
.unlocked_ioctl = sock_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = compat_sock_ioctl,
#endif
.mmap = sock_mmap,
.release = sock_close,
.fasync = sock_fasync,
.sendpage = sock_sendpage,
.splice_write = generic_splice_sendpage,
.splice_read = sock_splice_read,
};
/*
* The protocol list. Each protocol is registered in here.
*/
static DEFINE_SPINLOCK(net_family_lock);
static const struct net_proto_family __rcu *net_families[NPROTO] __read_mostly;
/*
* Statistics counters of the socket lists
*/
static DEFINE_PER_CPU(int, sockets_in_use);
/*
* Support routines.
* Move socket addresses back and forth across the kernel/user
* divide and look after the messy bits.
*/
/**
* move_addr_to_kernel - copy a socket address into kernel space
* @uaddr: Address in user space
* @kaddr: Address in kernel space
* @ulen: Length in user space
*
* The address is copied into kernel space. If the provided address is
* too long an error code of -EINVAL is returned. If the copy gives
* invalid addresses -EFAULT is returned. On a success 0 is returned.
*/
int move_addr_to_kernel(void __user *uaddr, int ulen, struct sockaddr_storage *kaddr)
{
if (ulen < 0 || ulen > sizeof(struct sockaddr_storage))
return -EINVAL;
if (ulen == 0)
return 0;
if (copy_from_user(kaddr, uaddr, ulen))
return -EFAULT;
return audit_sockaddr(ulen, kaddr);
}
/**
* move_addr_to_user - copy an address to user space
* @kaddr: kernel space address
* @klen: length of address in kernel
* @uaddr: user space address
* @ulen: pointer to user length field
*
* The value pointed to by ulen on entry is the buffer length available.
* This is overwritten with the buffer space used. -EINVAL is returned
* if an overlong buffer is specified or a negative buffer size. -EFAULT
* is returned if either the buffer or the length field are not
* accessible.
* After copying the data up to the limit the user specifies, the true
* length of the data is written over the length limit the user
* specified. Zero is returned for a success.
*/
static int move_addr_to_user(struct sockaddr_storage *kaddr, int klen,
void __user *uaddr, int __user *ulen)
{
int err;
int len;
BUG_ON(klen > sizeof(struct sockaddr_storage));
err = get_user(len, ulen);
if (err)
return err;
if (len > klen)
len = klen;
if (len < 0)
return -EINVAL;
if (len) {
if (audit_sockaddr(klen, kaddr))
return -ENOMEM;
if (copy_to_user(uaddr, kaddr, len))
return -EFAULT;
}
/*
* "fromlen shall refer to the value before truncation.."
* 1003.1g
*/
return __put_user(klen, ulen);
}
static struct kmem_cache *sock_inode_cachep __read_mostly;
static struct inode *sock_alloc_inode(struct super_block *sb)
{
struct socket_alloc *ei;
struct socket_wq *wq;
ei = kmem_cache_alloc(sock_inode_cachep, GFP_KERNEL);
if (!ei)
return NULL;
wq = kmalloc(sizeof(*wq), GFP_KERNEL);
if (!wq) {
kmem_cache_free(sock_inode_cachep, ei);
return NULL;
}
init_waitqueue_head(&wq->wait);
wq->fasync_list = NULL;
wq->flags = 0;
RCU_INIT_POINTER(ei->socket.wq, wq);
ei->socket.state = SS_UNCONNECTED;
ei->socket.flags = 0;
ei->socket.ops = NULL;
ei->socket.sk = NULL;
ei->socket.file = NULL;
return &ei->vfs_inode;
}
static void sock_destroy_inode(struct inode *inode)
{
struct socket_alloc *ei;
struct socket_wq *wq;
ei = container_of(inode, struct socket_alloc, vfs_inode);
wq = rcu_dereference_protected(ei->socket.wq, 1);
kfree_rcu(wq, rcu);
kmem_cache_free(sock_inode_cachep, ei);
}
static void init_once(void *foo)
{
struct socket_alloc *ei = (struct socket_alloc *)foo;
inode_init_once(&ei->vfs_inode);
}
static void init_inodecache(void)
{
sock_inode_cachep = kmem_cache_create("sock_inode_cache",
sizeof(struct socket_alloc),
0,
(SLAB_HWCACHE_ALIGN |
SLAB_RECLAIM_ACCOUNT |
SLAB_MEM_SPREAD | SLAB_ACCOUNT),
init_once);
BUG_ON(sock_inode_cachep == NULL);
}
static const struct super_operations sockfs_ops = {
.alloc_inode = sock_alloc_inode,
.destroy_inode = sock_destroy_inode,
.statfs = simple_statfs,
};
/*
* sockfs_dname() is called from d_path().
*/
static char *sockfs_dname(struct dentry *dentry, char *buffer, int buflen)
{
return dynamic_dname(dentry, buffer, buflen, "socket:[%lu]",
d_inode(dentry)->i_ino);
}
static const struct dentry_operations sockfs_dentry_operations = {
.d_dname = sockfs_dname,
};
static int sockfs_xattr_get(const struct xattr_handler *handler,
struct dentry *dentry, struct inode *inode,
const char *suffix, void *value, size_t size)
{
if (value) {
if (dentry->d_name.len + 1 > size)
return -ERANGE;
memcpy(value, dentry->d_name.name, dentry->d_name.len + 1);
}
return dentry->d_name.len + 1;
}
#define XATTR_SOCKPROTONAME_SUFFIX "sockprotoname"
#define XATTR_NAME_SOCKPROTONAME (XATTR_SYSTEM_PREFIX XATTR_SOCKPROTONAME_SUFFIX)
#define XATTR_NAME_SOCKPROTONAME_LEN (sizeof(XATTR_NAME_SOCKPROTONAME)-1)
static const struct xattr_handler sockfs_xattr_handler = {
.name = XATTR_NAME_SOCKPROTONAME,
.get = sockfs_xattr_get,
};
static int sockfs_security_xattr_set(const struct xattr_handler *handler,
struct dentry *dentry, struct inode *inode,
const char *suffix, const void *value,
size_t size, int flags)
{
/* Handled by LSM. */
return -EAGAIN;
}
static const struct xattr_handler sockfs_security_xattr_handler = {
.prefix = XATTR_SECURITY_PREFIX,
.set = sockfs_security_xattr_set,
};
static const struct xattr_handler *sockfs_xattr_handlers[] = {
&sockfs_xattr_handler,
&sockfs_security_xattr_handler,
NULL
};
static struct dentry *sockfs_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
return mount_pseudo_xattr(fs_type, "socket:", &sockfs_ops,
sockfs_xattr_handlers,
&sockfs_dentry_operations, SOCKFS_MAGIC);
}
static struct vfsmount *sock_mnt __read_mostly;
static struct file_system_type sock_fs_type = {
.name = "sockfs",
.mount = sockfs_mount,
.kill_sb = kill_anon_super,
};
/*
* Obtains the first available file descriptor and sets it up for use.
*
* These functions create file structures and maps them to fd space
* of the current process. On success it returns file descriptor
* and file struct implicitly stored in sock->file.
* Note that another thread may close file descriptor before we return
* from this function. We use the fact that now we do not refer
* to socket after mapping. If one day we will need it, this
* function will increment ref. count on file by 1.
*
* In any case returned fd MAY BE not valid!
* This race condition is unavoidable
* with shared fd spaces, we cannot solve it inside kernel,
* but we take care of internal coherence yet.
*/
struct file *sock_alloc_file(struct socket *sock, int flags, const char *dname)
{
struct qstr name = { .name = "" };
struct path path;
struct file *file;
if (dname) {
name.name = dname;
name.len = strlen(name.name);
} else if (sock->sk) {
name.name = sock->sk->sk_prot_creator->name;
name.len = strlen(name.name);
}
path.dentry = d_alloc_pseudo(sock_mnt->mnt_sb, &name);
if (unlikely(!path.dentry))
return ERR_PTR(-ENOMEM);
path.mnt = mntget(sock_mnt);
d_instantiate(path.dentry, SOCK_INODE(sock));
file = alloc_file(&path, FMODE_READ | FMODE_WRITE,
&socket_file_ops);
if (IS_ERR(file)) {
/* drop dentry, keep inode */
ihold(d_inode(path.dentry));
path_put(&path);
return file;
}
sock->file = file;
file->f_flags = O_RDWR | (flags & O_NONBLOCK);
file->private_data = sock;
return file;
}
EXPORT_SYMBOL(sock_alloc_file);
static int sock_map_fd(struct socket *sock, int flags)
{
struct file *newfile;
int fd = get_unused_fd_flags(flags);
if (unlikely(fd < 0))
return fd;
newfile = sock_alloc_file(sock, flags, NULL);
if (likely(!IS_ERR(newfile))) {
fd_install(fd, newfile);
return fd;
}
put_unused_fd(fd);
return PTR_ERR(newfile);
}
struct socket *sock_from_file(struct file *file, int *err)
{
if (file->f_op == &socket_file_ops)
return file->private_data; /* set in sock_map_fd */
*err = -ENOTSOCK;
return NULL;
}
EXPORT_SYMBOL(sock_from_file);
/**
* sockfd_lookup - Go from a file number to its socket slot
* @fd: file handle
* @err: pointer to an error code return
*
* The file handle passed in is locked and the socket it is bound
* too is returned. If an error occurs the err pointer is overwritten
* with a negative errno code and NULL is returned. The function checks
* for both invalid handles and passing a handle which is not a socket.
*
* On a success the socket object pointer is returned.
*/
struct socket *sockfd_lookup(int fd, int *err)
{
struct file *file;
struct socket *sock;
file = fget(fd);
if (!file) {
*err = -EBADF;
return NULL;
}
sock = sock_from_file(file, err);
if (!sock)
fput(file);
return sock;
}
EXPORT_SYMBOL(sockfd_lookup);
static struct socket *sockfd_lookup_light(int fd, int *err, int *fput_needed)
{
struct fd f = fdget(fd);
struct socket *sock;
*err = -EBADF;
if (f.file) {
sock = sock_from_file(f.file, err);
if (likely(sock)) {
*fput_needed = f.flags;
return sock;
}
fdput(f);
}
return NULL;
}
static ssize_t sockfs_listxattr(struct dentry *dentry, char *buffer,
size_t size)
{
ssize_t len;
ssize_t used = 0;
len = security_inode_listsecurity(d_inode(dentry), buffer, size);
if (len < 0)
return len;
used += len;
if (buffer) {
if (size < used)
return -ERANGE;
buffer += len;
}
len = (XATTR_NAME_SOCKPROTONAME_LEN + 1);
used += len;
if (buffer) {
if (size < used)
return -ERANGE;
memcpy(buffer, XATTR_NAME_SOCKPROTONAME, len);
buffer += len;
}
return used;
}
static int sockfs_setattr(struct dentry *dentry, struct iattr *iattr)
{
int err = simple_setattr(dentry, iattr);
if (!err && (iattr->ia_valid & ATTR_UID)) {
struct socket *sock = SOCKET_I(d_inode(dentry));
sock->sk->sk_uid = iattr->ia_uid;
}
return err;
}
static const struct inode_operations sockfs_inode_ops = {
.listxattr = sockfs_listxattr,
.setattr = sockfs_setattr,
};
/**
* sock_alloc - allocate a socket
*
* Allocate a new inode and socket object. The two are bound together
* and initialised. The socket is then returned. If we are out of inodes
* NULL is returned.
*/
struct socket *sock_alloc(void)
{
struct inode *inode;
struct socket *sock;
inode = new_inode_pseudo(sock_mnt->mnt_sb);
if (!inode)
return NULL;
sock = SOCKET_I(inode);
kmemcheck_annotate_bitfield(sock, type);
inode->i_ino = get_next_ino();
inode->i_mode = S_IFSOCK | S_IRWXUGO;
inode->i_uid = current_fsuid();
inode->i_gid = current_fsgid();
inode->i_op = &sockfs_inode_ops;
this_cpu_add(sockets_in_use, 1);
return sock;
}
EXPORT_SYMBOL(sock_alloc);
/**
* sock_release - close a socket
* @sock: socket to close
*
* The socket is released from the protocol stack if it has a release
* callback, and the inode is then released if the socket is bound to
* an inode not a file.
*/
void sock_release(struct socket *sock)
{
if (sock->ops) {
struct module *owner = sock->ops->owner;
sock->ops->release(sock);
sock->ops = NULL;
module_put(owner);
}
if (rcu_dereference_protected(sock->wq, 1)->fasync_list)
pr_err("%s: fasync list not empty!\n", __func__);
this_cpu_sub(sockets_in_use, 1);
if (!sock->file) {
iput(SOCK_INODE(sock));
return;
}
sock->file = NULL;
}
EXPORT_SYMBOL(sock_release);
void __sock_tx_timestamp(__u16 tsflags, __u8 *tx_flags)
{
u8 flags = *tx_flags;
if (tsflags & SOF_TIMESTAMPING_TX_HARDWARE)
flags |= SKBTX_HW_TSTAMP;
if (tsflags & SOF_TIMESTAMPING_TX_SOFTWARE)
flags |= SKBTX_SW_TSTAMP;
if (tsflags & SOF_TIMESTAMPING_TX_SCHED)
flags |= SKBTX_SCHED_TSTAMP;
*tx_flags = flags;
}
EXPORT_SYMBOL(__sock_tx_timestamp);
static inline int sock_sendmsg_nosec(struct socket *sock, struct msghdr *msg)
{
int ret = sock->ops->sendmsg(sock, msg, msg_data_left(msg));
BUG_ON(ret == -EIOCBQUEUED);
return ret;
}
int sock_sendmsg(struct socket *sock, struct msghdr *msg)
{
int err = security_socket_sendmsg(sock, msg,
msg_data_left(msg));
return err ?: sock_sendmsg_nosec(sock, msg);
}
EXPORT_SYMBOL(sock_sendmsg);
int kernel_sendmsg(struct socket *sock, struct msghdr *msg,
struct kvec *vec, size_t num, size_t size)
{
iov_iter_kvec(&msg->msg_iter, WRITE | ITER_KVEC, vec, num, size);
return sock_sendmsg(sock, msg);
}
EXPORT_SYMBOL(kernel_sendmsg);
static bool skb_is_err_queue(const struct sk_buff *skb)
{
/* pkt_type of skbs enqueued on the error queue are set to
* PACKET_OUTGOING in skb_set_err_queue(). This is only safe to do
* in recvmsg, since skbs received on a local socket will never
* have a pkt_type of PACKET_OUTGOING.
*/
return skb->pkt_type == PACKET_OUTGOING;
}
/*
* called from sock_recv_timestamp() if sock_flag(sk, SOCK_RCVTSTAMP)
*/
void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk,
struct sk_buff *skb)
{
int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP);
struct scm_timestamping tss;
int empty = 1;
struct skb_shared_hwtstamps *shhwtstamps =
skb_hwtstamps(skb);
/* Race occurred between timestamp enabling and packet
receiving. Fill in the current time for now. */
if (need_software_tstamp && skb->tstamp == 0)
__net_timestamp(skb);
if (need_software_tstamp) {
if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) {
struct timeval tv;
skb_get_timestamp(skb, &tv);
put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP,
sizeof(tv), &tv);
} else {
struct timespec ts;
skb_get_timestampns(skb, &ts);
put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS,
sizeof(ts), &ts);
}
}
memset(&tss, 0, sizeof(tss));
if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) &&
ktime_to_timespec_cond(skb->tstamp, tss.ts + 0))
empty = 0;
if (shhwtstamps &&
(sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2))
empty = 0;
if (!empty) {
put_cmsg(msg, SOL_SOCKET,
SCM_TIMESTAMPING, sizeof(tss), &tss);
if (skb_is_err_queue(skb) && skb->len &&
(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS))
put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS,
skb->len, skb->data);
}
}
EXPORT_SYMBOL_GPL(__sock_recv_timestamp);
void __sock_recv_wifi_status(struct msghdr *msg, struct sock *sk,
struct sk_buff *skb)
{
int ack;
if (!sock_flag(sk, SOCK_WIFI_STATUS))
return;
if (!skb->wifi_acked_valid)
return;
ack = skb->wifi_acked;
put_cmsg(msg, SOL_SOCKET, SCM_WIFI_STATUS, sizeof(ack), &ack);
}
EXPORT_SYMBOL_GPL(__sock_recv_wifi_status);
static inline void sock_recv_drops(struct msghdr *msg, struct sock *sk,
struct sk_buff *skb)
{
if (sock_flag(sk, SOCK_RXQ_OVFL) && skb && SOCK_SKB_CB(skb)->dropcount)
put_cmsg(msg, SOL_SOCKET, SO_RXQ_OVFL,
sizeof(__u32), &SOCK_SKB_CB(skb)->dropcount);
}
void __sock_recv_ts_and_drops(struct msghdr *msg, struct sock *sk,
struct sk_buff *skb)
{
sock_recv_timestamp(msg, sk, skb);
sock_recv_drops(msg, sk, skb);
}
EXPORT_SYMBOL_GPL(__sock_recv_ts_and_drops);
static inline int sock_recvmsg_nosec(struct socket *sock, struct msghdr *msg,
int flags)
{
return sock->ops->recvmsg(sock, msg, msg_data_left(msg), flags);
}
int sock_recvmsg(struct socket *sock, struct msghdr *msg, int flags)
{
int err = security_socket_recvmsg(sock, msg, msg_data_left(msg), flags);
return err ?: sock_recvmsg_nosec(sock, msg, flags);
}
EXPORT_SYMBOL(sock_recvmsg);
/**
* kernel_recvmsg - Receive a message from a socket (kernel space)
* @sock: The socket to receive the message from
* @msg: Received message
* @vec: Input s/g array for message data
* @num: Size of input s/g array
* @size: Number of bytes to read
* @flags: Message flags (MSG_DONTWAIT, etc...)
*
* On return the msg structure contains the scatter/gather array passed in the
* vec argument. The array is modified so that it consists of the unfilled
* portion of the original array.
*
* The returned value is the total number of bytes received, or an error.
*/
int kernel_recvmsg(struct socket *sock, struct msghdr *msg,
struct kvec *vec, size_t num, size_t size, int flags)
{
mm_segment_t oldfs = get_fs();
int result;
iov_iter_kvec(&msg->msg_iter, READ | ITER_KVEC, vec, num, size);
set_fs(KERNEL_DS);
result = sock_recvmsg(sock, msg, flags);
set_fs(oldfs);
return result;
}
EXPORT_SYMBOL(kernel_recvmsg);
static ssize_t sock_sendpage(struct file *file, struct page *page,
int offset, size_t size, loff_t *ppos, int more)
{
struct socket *sock;
int flags;
sock = file->private_data;
flags = (file->f_flags & O_NONBLOCK) ? MSG_DONTWAIT : 0;
/* more is a combination of MSG_MORE and MSG_SENDPAGE_NOTLAST */
flags |= more;
return kernel_sendpage(sock, page, offset, size, flags);
}
static ssize_t sock_splice_read(struct file *file, loff_t *ppos,
struct pipe_inode_info *pipe, size_t len,
unsigned int flags)
{
struct socket *sock = file->private_data;
if (unlikely(!sock->ops->splice_read))
return -EINVAL;
return sock->ops->splice_read(sock, ppos, pipe, len, flags);
}
static ssize_t sock_read_iter(struct kiocb *iocb, struct iov_iter *to)
{
struct file *file = iocb->ki_filp;
struct socket *sock = file->private_data;
struct msghdr msg = {.msg_iter = *to,
.msg_iocb = iocb};
ssize_t res;
if (file->f_flags & O_NONBLOCK)
msg.msg_flags = MSG_DONTWAIT;
if (iocb->ki_pos != 0)
return -ESPIPE;
if (!iov_iter_count(to)) /* Match SYS5 behaviour */
return 0;
res = sock_recvmsg(sock, &msg, msg.msg_flags);
*to = msg.msg_iter;
return res;
}
static ssize_t sock_write_iter(struct kiocb *iocb, struct iov_iter *from)
{
struct file *file = iocb->ki_filp;
struct socket *sock = file->private_data;
struct msghdr msg = {.msg_iter = *from,
.msg_iocb = iocb};
ssize_t res;
if (iocb->ki_pos != 0)
return -ESPIPE;
if (file->f_flags & O_NONBLOCK)
msg.msg_flags = MSG_DONTWAIT;
if (sock->type == SOCK_SEQPACKET)
msg.msg_flags |= MSG_EOR;
res = sock_sendmsg(sock, &msg);
*from = msg.msg_iter;
return res;
}
/*
* Atomic setting of ioctl hooks to avoid race
* with module unload.
*/
static DEFINE_MUTEX(br_ioctl_mutex);
static int (*br_ioctl_hook) (struct net *, unsigned int cmd, void __user *arg);
void brioctl_set(int (*hook) (struct net *, unsigned int, void __user *))
{
mutex_lock(&br_ioctl_mutex);
br_ioctl_hook = hook;
mutex_unlock(&br_ioctl_mutex);
}
EXPORT_SYMBOL(brioctl_set);
static DEFINE_MUTEX(vlan_ioctl_mutex);
static int (*vlan_ioctl_hook) (struct net *, void __user *arg);
void vlan_ioctl_set(int (*hook) (struct net *, void __user *))
{
mutex_lock(&vlan_ioctl_mutex);
vlan_ioctl_hook = hook;
mutex_unlock(&vlan_ioctl_mutex);
}
EXPORT_SYMBOL(vlan_ioctl_set);
static DEFINE_MUTEX(dlci_ioctl_mutex);
static int (*dlci_ioctl_hook) (unsigned int, void __user *);
void dlci_ioctl_set(int (*hook) (unsigned int, void __user *))
{
mutex_lock(&dlci_ioctl_mutex);
dlci_ioctl_hook = hook;
mutex_unlock(&dlci_ioctl_mutex);
}
EXPORT_SYMBOL(dlci_ioctl_set);
static long sock_do_ioctl(struct net *net, struct socket *sock,
unsigned int cmd, unsigned long arg)
{
int err;
void __user *argp = (void __user *)arg;
err = sock->ops->ioctl(sock, cmd, arg);
/*
* If this ioctl is unknown try to hand it down
* to the NIC driver.
*/
if (err == -ENOIOCTLCMD)
err = dev_ioctl(net, cmd, argp);
return err;
}
/*
* With an ioctl, arg may well be a user mode pointer, but we don't know
* what to do with it - that's up to the protocol still.
*/
static struct ns_common *get_net_ns(struct ns_common *ns)
{
return &get_net(container_of(ns, struct net, ns))->ns;
}
static long sock_ioctl(struct file *file, unsigned cmd, unsigned long arg)
{
struct socket *sock;
struct sock *sk;
void __user *argp = (void __user *)arg;
int pid, err;
struct net *net;
sock = file->private_data;
sk = sock->sk;
net = sock_net(sk);
if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15)) {
err = dev_ioctl(net, cmd, argp);
} else
#ifdef CONFIG_WEXT_CORE
if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST) {
err = dev_ioctl(net, cmd, argp);
} else
#endif
switch (cmd) {
case FIOSETOWN:
case SIOCSPGRP:
err = -EFAULT;
if (get_user(pid, (int __user *)argp))
break;
f_setown(sock->file, pid, 1);
err = 0;
break;
case FIOGETOWN:
case SIOCGPGRP:
err = put_user(f_getown(sock->file),
(int __user *)argp);
break;
case SIOCGIFBR:
case SIOCSIFBR:
case SIOCBRADDBR:
case SIOCBRDELBR:
err = -ENOPKG;
if (!br_ioctl_hook)
request_module("bridge");
mutex_lock(&br_ioctl_mutex);
if (br_ioctl_hook)
err = br_ioctl_hook(net, cmd, argp);
mutex_unlock(&br_ioctl_mutex);
break;
case SIOCGIFVLAN:
case SIOCSIFVLAN:
err = -ENOPKG;
if (!vlan_ioctl_hook)
request_module("8021q");
mutex_lock(&vlan_ioctl_mutex);
if (vlan_ioctl_hook)
err = vlan_ioctl_hook(net, argp);
mutex_unlock(&vlan_ioctl_mutex);
break;
case SIOCADDDLCI:
case SIOCDELDLCI:
err = -ENOPKG;
if (!dlci_ioctl_hook)
request_module("dlci");
mutex_lock(&dlci_ioctl_mutex);
if (dlci_ioctl_hook)
err = dlci_ioctl_hook(cmd, argp);
mutex_unlock(&dlci_ioctl_mutex);
break;
case SIOCGSKNS:
err = -EPERM;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
break;
err = open_related_ns(&net->ns, get_net_ns);
break;
default:
err = sock_do_ioctl(net, sock, cmd, arg);
break;
}
return err;
}
int sock_create_lite(int family, int type, int protocol, struct socket **res)
{
int err;
struct socket *sock = NULL;
err = security_socket_create(family, type, protocol, 1);
if (err)
goto out;
sock = sock_alloc();
if (!sock) {
err = -ENOMEM;
goto out;
}
sock->type = type;
err = security_socket_post_create(sock, family, type, protocol, 1);
if (err)
goto out_release;
out:
*res = sock;
return err;
out_release:
sock_release(sock);
sock = NULL;
goto out;
}
EXPORT_SYMBOL(sock_create_lite);
/* No kernel lock held - perfect */
static unsigned int sock_poll(struct file *file, poll_table *wait)
{
unsigned int busy_flag = 0;
struct socket *sock;
/*
* We can't return errors to poll, so it's either yes or no.
*/
sock = file->private_data;
if (sk_can_busy_loop(sock->sk)) {
/* this socket can poll_ll so tell the system call */
busy_flag = POLL_BUSY_LOOP;
/* once, only if requested by syscall */
if (wait && (wait->_key & POLL_BUSY_LOOP))
sk_busy_loop(sock->sk, 1);
}
return busy_flag | sock->ops->poll(file, sock, wait);
}
static int sock_mmap(struct file *file, struct vm_area_struct *vma)
{
struct socket *sock = file->private_data;
return sock->ops->mmap(file, sock, vma);
}
static int sock_close(struct inode *inode, struct file *filp)
{
sock_release(SOCKET_I(inode));
return 0;
}
/*
* Update the socket async list
*
* Fasync_list locking strategy.
*
* 1. fasync_list is modified only under process context socket lock
* i.e. under semaphore.
* 2. fasync_list is used under read_lock(&sk->sk_callback_lock)
* or under socket lock
*/
static int sock_fasync(int fd, struct file *filp, int on)
{
struct socket *sock = filp->private_data;
struct sock *sk = sock->sk;
struct socket_wq *wq;
if (sk == NULL)
return -EINVAL;
lock_sock(sk);
wq = rcu_dereference_protected(sock->wq, lockdep_sock_is_held(sk));
fasync_helper(fd, filp, on, &wq->fasync_list);
if (!wq->fasync_list)
sock_reset_flag(sk, SOCK_FASYNC);
else
sock_set_flag(sk, SOCK_FASYNC);
release_sock(sk);
return 0;
}
/* This function may be called only under rcu_lock */
int sock_wake_async(struct socket_wq *wq, int how, int band)
{
if (!wq || !wq->fasync_list)
return -1;
switch (how) {
case SOCK_WAKE_WAITD:
if (test_bit(SOCKWQ_ASYNC_WAITDATA, &wq->flags))
break;
goto call_kill;
case SOCK_WAKE_SPACE:
if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &wq->flags))
break;
/* fall through */
case SOCK_WAKE_IO:
call_kill:
kill_fasync(&wq->fasync_list, SIGIO, band);
break;
case SOCK_WAKE_URG:
kill_fasync(&wq->fasync_list, SIGURG, band);
}
return 0;
}
EXPORT_SYMBOL(sock_wake_async);
int __sock_create(struct net *net, int family, int type, int protocol,
struct socket **res, int kern)
{
int err;
struct socket *sock;
const struct net_proto_family *pf;
/*
* Check protocol is in range
*/
if (family < 0 || family >= NPROTO)
return -EAFNOSUPPORT;
if (type < 0 || type >= SOCK_MAX)
return -EINVAL;
/* Compatibility.
This uglymoron is moved from INET layer to here to avoid
deadlock in module load.
*/
if (family == PF_INET && type == SOCK_PACKET) {
pr_info_once("%s uses obsolete (PF_INET,SOCK_PACKET)\n",
current->comm);
family = PF_PACKET;
}
err = security_socket_create(family, type, protocol, kern);
if (err)
return err;
/*
* Allocate the socket and allow the family to set things up. if
* the protocol is 0, the family is instructed to select an appropriate
* default.
*/
sock = sock_alloc();
if (!sock) {
net_warn_ratelimited("socket: no more sockets\n");
return -ENFILE; /* Not exactly a match, but its the
closest posix thing */
}
sock->type = type;
#ifdef CONFIG_MODULES
/* Attempt to load a protocol module if the find failed.
*
* 12/09/1996 Marcin: But! this makes REALLY only sense, if the user
* requested real, full-featured networking support upon configuration.
* Otherwise module support will break!
*/
if (rcu_access_pointer(net_families[family]) == NULL)
request_module("net-pf-%d", family);
#endif
rcu_read_lock();
pf = rcu_dereference(net_families[family]);
err = -EAFNOSUPPORT;
if (!pf)
goto out_release;
/*
* We will call the ->create function, that possibly is in a loadable
* module, so we have to bump that loadable module refcnt first.
*/
if (!try_module_get(pf->owner))
goto out_release;
/* Now protected by module ref count */
rcu_read_unlock();
err = pf->create(net, sock, protocol, kern);
if (err < 0)
goto out_module_put;
/*
* Now to bump the refcnt of the [loadable] module that owns this
* socket at sock_release time we decrement its refcnt.
*/
if (!try_module_get(sock->ops->owner))
goto out_module_busy;
/*
* Now that we're done with the ->create function, the [loadable]
* module can have its refcnt decremented
*/
module_put(pf->owner);
err = security_socket_post_create(sock, family, type, protocol, kern);
if (err)
goto out_sock_release;
*res = sock;
return 0;
out_module_busy:
err = -EAFNOSUPPORT;
out_module_put:
sock->ops = NULL;
module_put(pf->owner);
out_sock_release:
sock_release(sock);
return err;
out_release:
rcu_read_unlock();
goto out_sock_release;
}
EXPORT_SYMBOL(__sock_create);
int sock_create(int family, int type, int protocol, struct socket **res)
{
return __sock_create(current->nsproxy->net_ns, family, type, protocol, res, 0);
}
EXPORT_SYMBOL(sock_create);
int sock_create_kern(struct net *net, int family, int type, int protocol, struct socket **res)
{
return __sock_create(net, family, type, protocol, res, 1);
}
EXPORT_SYMBOL(sock_create_kern);
SYSCALL_DEFINE3(socket, int, family, int, type, int, protocol)
{
int retval;
struct socket *sock;
int flags;
/* Check the SOCK_* constants for consistency. */
BUILD_BUG_ON(SOCK_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON((SOCK_MAX | SOCK_TYPE_MASK) != SOCK_TYPE_MASK);
BUILD_BUG_ON(SOCK_CLOEXEC & SOCK_TYPE_MASK);
BUILD_BUG_ON(SOCK_NONBLOCK & SOCK_TYPE_MASK);
flags = type & ~SOCK_TYPE_MASK;
if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
return -EINVAL;
type &= SOCK_TYPE_MASK;
if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK))
flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
retval = sock_create(family, type, protocol, &sock);
if (retval < 0)
goto out;
retval = sock_map_fd(sock, flags & (O_CLOEXEC | O_NONBLOCK));
if (retval < 0)
goto out_release;
out:
/* It may be already another descriptor 8) Not kernel problem. */
return retval;
out_release:
sock_release(sock);
return retval;
}
/*
* Create a pair of connected sockets.
*/
SYSCALL_DEFINE4(socketpair, int, family, int, type, int, protocol,
int __user *, usockvec)
{
struct socket *sock1, *sock2;
int fd1, fd2, err;
struct file *newfile1, *newfile2;
int flags;
flags = type & ~SOCK_TYPE_MASK;
if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
return -EINVAL;
type &= SOCK_TYPE_MASK;
if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK))
flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
/*
* Obtain the first socket and check if the underlying protocol
* supports the socketpair call.
*/
err = sock_create(family, type, protocol, &sock1);
if (err < 0)
goto out;
err = sock_create(family, type, protocol, &sock2);
if (err < 0)
goto out_release_1;
err = sock1->ops->socketpair(sock1, sock2);
if (err < 0)
goto out_release_both;
fd1 = get_unused_fd_flags(flags);
if (unlikely(fd1 < 0)) {
err = fd1;
goto out_release_both;
}
fd2 = get_unused_fd_flags(flags);
if (unlikely(fd2 < 0)) {
err = fd2;
goto out_put_unused_1;
}
newfile1 = sock_alloc_file(sock1, flags, NULL);
if (IS_ERR(newfile1)) {
err = PTR_ERR(newfile1);
goto out_put_unused_both;
}
newfile2 = sock_alloc_file(sock2, flags, NULL);
if (IS_ERR(newfile2)) {
err = PTR_ERR(newfile2);
goto out_fput_1;
}
err = put_user(fd1, &usockvec[0]);
if (err)
goto out_fput_both;
err = put_user(fd2, &usockvec[1]);
if (err)
goto out_fput_both;
audit_fd_pair(fd1, fd2);
fd_install(fd1, newfile1);
fd_install(fd2, newfile2);
/* fd1 and fd2 may be already another descriptors.
* Not kernel problem.
*/
return 0;
out_fput_both:
fput(newfile2);
fput(newfile1);
put_unused_fd(fd2);
put_unused_fd(fd1);
goto out;
out_fput_1:
fput(newfile1);
put_unused_fd(fd2);
put_unused_fd(fd1);
sock_release(sock2);
goto out;
out_put_unused_both:
put_unused_fd(fd2);
out_put_unused_1:
put_unused_fd(fd1);
out_release_both:
sock_release(sock2);
out_release_1:
sock_release(sock1);
out:
return err;
}
/*
* Bind a name to a socket. Nothing much to do here since it's
* the protocol's responsibility to handle the local address.
*
* We move the socket address to kernel space before we call
* the protocol layer (having also checked the address is ok).
*/
SYSCALL_DEFINE3(bind, int, fd, struct sockaddr __user *, umyaddr, int, addrlen)
{
struct socket *sock;
struct sockaddr_storage address;
int err, fput_needed;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (sock) {
err = move_addr_to_kernel(umyaddr, addrlen, &address);
if (err >= 0) {
err = security_socket_bind(sock,
(struct sockaddr *)&address,
addrlen);
if (!err)
err = sock->ops->bind(sock,
(struct sockaddr *)
&address, addrlen);
}
fput_light(sock->file, fput_needed);
}
return err;
}
/*
* Perform a listen. Basically, we allow the protocol to do anything
* necessary for a listen, and if that works, we mark the socket as
* ready for listening.
*/
SYSCALL_DEFINE2(listen, int, fd, int, backlog)
{
struct socket *sock;
int err, fput_needed;
int somaxconn;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (sock) {
somaxconn = sock_net(sock->sk)->core.sysctl_somaxconn;
if ((unsigned int)backlog > somaxconn)
backlog = somaxconn;
err = security_socket_listen(sock, backlog);
if (!err)
err = sock->ops->listen(sock, backlog);
fput_light(sock->file, fput_needed);
}
return err;
}
/*
* For accept, we attempt to create a new socket, set up the link
* with the client, wake up the client, then return the new
* connected fd. We collect the address of the connector in kernel
* space and move it to user at the very end. This is unclean because
* we open the socket then return an error.
*
* 1003.1g adds the ability to recvmsg() to query connection pending
* status to recvmsg. We need to add that support in a way thats
* clean when we restucture accept also.
*/
SYSCALL_DEFINE4(accept4, int, fd, struct sockaddr __user *, upeer_sockaddr,
int __user *, upeer_addrlen, int, flags)
{
struct socket *sock, *newsock;
struct file *newfile;
int err, len, newfd, fput_needed;
struct sockaddr_storage address;
if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
return -EINVAL;
if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK))
flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
err = -ENFILE;
newsock = sock_alloc();
if (!newsock)
goto out_put;
newsock->type = sock->type;
newsock->ops = sock->ops;
/*
* We don't need try_module_get here, as the listening socket (sock)
* has the protocol module (sock->ops->owner) held.
*/
__module_get(newsock->ops->owner);
newfd = get_unused_fd_flags(flags);
if (unlikely(newfd < 0)) {
err = newfd;
sock_release(newsock);
goto out_put;
}
newfile = sock_alloc_file(newsock, flags, sock->sk->sk_prot_creator->name);
if (IS_ERR(newfile)) {
err = PTR_ERR(newfile);
put_unused_fd(newfd);
sock_release(newsock);
goto out_put;
}
err = security_socket_accept(sock, newsock);
if (err)
goto out_fd;
err = sock->ops->accept(sock, newsock, sock->file->f_flags, false);
if (err < 0)
goto out_fd;
if (upeer_sockaddr) {
if (newsock->ops->getname(newsock, (struct sockaddr *)&address,
&len, 2) < 0) {
err = -ECONNABORTED;
goto out_fd;
}
err = move_addr_to_user(&address,
len, upeer_sockaddr, upeer_addrlen);
if (err < 0)
goto out_fd;
}
/* File flags are not inherited via accept() unlike another OSes. */
fd_install(newfd, newfile);
err = newfd;
out_put:
fput_light(sock->file, fput_needed);
out:
return err;
out_fd:
fput(newfile);
put_unused_fd(newfd);
goto out_put;
}
SYSCALL_DEFINE3(accept, int, fd, struct sockaddr __user *, upeer_sockaddr,
int __user *, upeer_addrlen)
{
return sys_accept4(fd, upeer_sockaddr, upeer_addrlen, 0);
}
/*
* Attempt to connect to a socket with the server address. The address
* is in user space so we verify it is OK and move it to kernel space.
*
* For 1003.1g we need to add clean support for a bind to AF_UNSPEC to
* break bindings
*
* NOTE: 1003.1g draft 6.3 is broken with respect to AX.25/NetROM and
* other SEQPACKET protocols that take time to connect() as it doesn't
* include the -EINPROGRESS status for such sockets.
*/
SYSCALL_DEFINE3(connect, int, fd, struct sockaddr __user *, uservaddr,
int, addrlen)
{
struct socket *sock;
struct sockaddr_storage address;
int err, fput_needed;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
err = move_addr_to_kernel(uservaddr, addrlen, &address);
if (err < 0)
goto out_put;
err =
security_socket_connect(sock, (struct sockaddr *)&address, addrlen);
if (err)
goto out_put;
err = sock->ops->connect(sock, (struct sockaddr *)&address, addrlen,
sock->file->f_flags);
out_put:
fput_light(sock->file, fput_needed);
out:
return err;
}
/*
* Get the local address ('name') of a socket object. Move the obtained
* name to user space.
*/
SYSCALL_DEFINE3(getsockname, int, fd, struct sockaddr __user *, usockaddr,
int __user *, usockaddr_len)
{
struct socket *sock;
struct sockaddr_storage address;
int len, err, fput_needed;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
err = security_socket_getsockname(sock);
if (err)
goto out_put;
err = sock->ops->getname(sock, (struct sockaddr *)&address, &len, 0);
if (err)
goto out_put;
err = move_addr_to_user(&address, len, usockaddr, usockaddr_len);
out_put:
fput_light(sock->file, fput_needed);
out:
return err;
}
/*
* Get the remote address ('name') of a socket object. Move the obtained
* name to user space.
*/
SYSCALL_DEFINE3(getpeername, int, fd, struct sockaddr __user *, usockaddr,
int __user *, usockaddr_len)
{
struct socket *sock;
struct sockaddr_storage address;
int len, err, fput_needed;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (sock != NULL) {
err = security_socket_getpeername(sock);
if (err) {
fput_light(sock->file, fput_needed);
return err;
}
err =
sock->ops->getname(sock, (struct sockaddr *)&address, &len,
1);
if (!err)
err = move_addr_to_user(&address, len, usockaddr,
usockaddr_len);
fput_light(sock->file, fput_needed);
}
return err;
}
/*
* Send a datagram to a given address. We move the address into kernel
* space and check the user space data area is readable before invoking
* the protocol.
*/
SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len,
unsigned int, flags, struct sockaddr __user *, addr,
int, addr_len)
{
struct socket *sock;
struct sockaddr_storage address;
int err;
struct msghdr msg;
struct iovec iov;
int fput_needed;
err = import_single_range(WRITE, buff, len, &iov, &msg.msg_iter);
if (unlikely(err))
return err;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
msg.msg_name = NULL;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_namelen = 0;
if (addr) {
err = move_addr_to_kernel(addr, addr_len, &address);
if (err < 0)
goto out_put;
msg.msg_name = (struct sockaddr *)&address;
msg.msg_namelen = addr_len;
}
if (sock->file->f_flags & O_NONBLOCK)
flags |= MSG_DONTWAIT;
msg.msg_flags = flags;
err = sock_sendmsg(sock, &msg);
out_put:
fput_light(sock->file, fput_needed);
out:
return err;
}
/*
* Send a datagram down a socket.
*/
SYSCALL_DEFINE4(send, int, fd, void __user *, buff, size_t, len,
unsigned int, flags)
{
return sys_sendto(fd, buff, len, flags, NULL, 0);
}
/*
* Receive a frame from the socket and optionally record the address of the
* sender. We verify the buffers are writable and if needed move the
* sender address from kernel to user space.
*/
SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size,
unsigned int, flags, struct sockaddr __user *, addr,
int __user *, addr_len)
{
struct socket *sock;
struct iovec iov;
struct msghdr msg;
struct sockaddr_storage address;
int err, err2;
int fput_needed;
err = import_single_range(READ, ubuf, size, &iov, &msg.msg_iter);
if (unlikely(err))
return err;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
msg.msg_control = NULL;
msg.msg_controllen = 0;
/* Save some cycles and don't copy the address if not needed */
msg.msg_name = addr ? (struct sockaddr *)&address : NULL;
/* We assume all kernel code knows the size of sockaddr_storage */
msg.msg_namelen = 0;
msg.msg_iocb = NULL;
msg.msg_flags = 0;
if (sock->file->f_flags & O_NONBLOCK)
flags |= MSG_DONTWAIT;
err = sock_recvmsg(sock, &msg, flags);
if (err >= 0 && addr != NULL) {
err2 = move_addr_to_user(&address,
msg.msg_namelen, addr, addr_len);
if (err2 < 0)
err = err2;
}
fput_light(sock->file, fput_needed);
out:
return err;
}
/*
* Receive a datagram from a socket.
*/
SYSCALL_DEFINE4(recv, int, fd, void __user *, ubuf, size_t, size,
unsigned int, flags)
{
return sys_recvfrom(fd, ubuf, size, flags, NULL, NULL);
}
/*
* Set a socket option. Because we don't know the option lengths we have
* to pass the user mode parameter for the protocols to sort out.
*/
SYSCALL_DEFINE5(setsockopt, int, fd, int, level, int, optname,
char __user *, optval, int, optlen)
{
int err, fput_needed;
struct socket *sock;
if (optlen < 0)
return -EINVAL;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (sock != NULL) {
err = security_socket_setsockopt(sock, level, optname);
if (err)
goto out_put;
if (level == SOL_SOCKET)
err =
sock_setsockopt(sock, level, optname, optval,
optlen);
else
err =
sock->ops->setsockopt(sock, level, optname, optval,
optlen);
out_put:
fput_light(sock->file, fput_needed);
}
return err;
}
/*
* Get a socket option. Because we don't know the option lengths we have
* to pass a user mode parameter for the protocols to sort out.
*/
SYSCALL_DEFINE5(getsockopt, int, fd, int, level, int, optname,
char __user *, optval, int __user *, optlen)
{
int err, fput_needed;
struct socket *sock;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (sock != NULL) {
err = security_socket_getsockopt(sock, level, optname);
if (err)
goto out_put;
if (level == SOL_SOCKET)
err =
sock_getsockopt(sock, level, optname, optval,
optlen);
else
err =
sock->ops->getsockopt(sock, level, optname, optval,
optlen);
out_put:
fput_light(sock->file, fput_needed);
}
return err;
}
/*
* Shutdown a socket.
*/
SYSCALL_DEFINE2(shutdown, int, fd, int, how)
{
int err, fput_needed;
struct socket *sock;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (sock != NULL) {
err = security_socket_shutdown(sock, how);
if (!err)
err = sock->ops->shutdown(sock, how);
fput_light(sock->file, fput_needed);
}
return err;
}
/* A couple of helpful macros for getting the address of the 32/64 bit
* fields which are the same type (int / unsigned) on our platforms.
*/
#define COMPAT_MSG(msg, member) ((MSG_CMSG_COMPAT & flags) ? &msg##_compat->member : &msg->member)
#define COMPAT_NAMELEN(msg) COMPAT_MSG(msg, msg_namelen)
#define COMPAT_FLAGS(msg) COMPAT_MSG(msg, msg_flags)
struct used_address {
struct sockaddr_storage name;
unsigned int name_len;
};
static int copy_msghdr_from_user(struct msghdr *kmsg,
struct user_msghdr __user *umsg,
struct sockaddr __user **save_addr,
struct iovec **iov)
{
struct sockaddr __user *uaddr;
struct iovec __user *uiov;
size_t nr_segs;
ssize_t err;
if (!access_ok(VERIFY_READ, umsg, sizeof(*umsg)) ||
__get_user(uaddr, &umsg->msg_name) ||
__get_user(kmsg->msg_namelen, &umsg->msg_namelen) ||
__get_user(uiov, &umsg->msg_iov) ||
__get_user(nr_segs, &umsg->msg_iovlen) ||
__get_user(kmsg->msg_control, &umsg->msg_control) ||
__get_user(kmsg->msg_controllen, &umsg->msg_controllen) ||
__get_user(kmsg->msg_flags, &umsg->msg_flags))
return -EFAULT;
if (!uaddr)
kmsg->msg_namelen = 0;
if (kmsg->msg_namelen < 0)
return -EINVAL;
if (kmsg->msg_namelen > sizeof(struct sockaddr_storage))
kmsg->msg_namelen = sizeof(struct sockaddr_storage);
if (save_addr)
*save_addr = uaddr;
if (uaddr && kmsg->msg_namelen) {
if (!save_addr) {
err = move_addr_to_kernel(uaddr, kmsg->msg_namelen,
kmsg->msg_name);
if (err < 0)
return err;
}
} else {
kmsg->msg_name = NULL;
kmsg->msg_namelen = 0;
}
if (nr_segs > UIO_MAXIOV)
return -EMSGSIZE;
kmsg->msg_iocb = NULL;
return import_iovec(save_addr ? READ : WRITE, uiov, nr_segs,
UIO_FASTIOV, iov, &kmsg->msg_iter);
}
static int ___sys_sendmsg(struct socket *sock, struct user_msghdr __user *msg,
struct msghdr *msg_sys, unsigned int flags,
struct used_address *used_address,
unsigned int allowed_msghdr_flags)
{
struct compat_msghdr __user *msg_compat =
(struct compat_msghdr __user *)msg;
struct sockaddr_storage address;
struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
unsigned char ctl[sizeof(struct cmsghdr) + 20]
__aligned(sizeof(__kernel_size_t));
/* 20 is size of ipv6_pktinfo */
unsigned char *ctl_buf = ctl;
int ctl_len;
ssize_t err;
msg_sys->msg_name = &address;
if (MSG_CMSG_COMPAT & flags)
err = get_compat_msghdr(msg_sys, msg_compat, NULL, &iov);
else
err = copy_msghdr_from_user(msg_sys, msg, NULL, &iov);
if (err < 0)
return err;
err = -ENOBUFS;
if (msg_sys->msg_controllen > INT_MAX)
goto out_freeiov;
flags |= (msg_sys->msg_flags & allowed_msghdr_flags);
ctl_len = msg_sys->msg_controllen;
if ((MSG_CMSG_COMPAT & flags) && ctl_len) {
err =
cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl,
sizeof(ctl));
if (err)
goto out_freeiov;
ctl_buf = msg_sys->msg_control;
ctl_len = msg_sys->msg_controllen;
} else if (ctl_len) {
BUILD_BUG_ON(sizeof(struct cmsghdr) !=
CMSG_ALIGN(sizeof(struct cmsghdr)));
if (ctl_len > sizeof(ctl)) {
ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL);
if (ctl_buf == NULL)
goto out_freeiov;
}
err = -EFAULT;
/*
* Careful! Before this, msg_sys->msg_control contains a user pointer.
* Afterwards, it will be a kernel pointer. Thus the compiler-assisted
* checking falls down on this.
*/
if (copy_from_user(ctl_buf,
(void __user __force *)msg_sys->msg_control,
ctl_len))
goto out_freectl;
msg_sys->msg_control = ctl_buf;
}
msg_sys->msg_flags = flags;
if (sock->file->f_flags & O_NONBLOCK)
msg_sys->msg_flags |= MSG_DONTWAIT;
/*
* If this is sendmmsg() and current destination address is same as
* previously succeeded address, omit asking LSM's decision.
* used_address->name_len is initialized to UINT_MAX so that the first
* destination address never matches.
*/
if (used_address && msg_sys->msg_name &&
used_address->name_len == msg_sys->msg_namelen &&
!memcmp(&used_address->name, msg_sys->msg_name,
used_address->name_len)) {
err = sock_sendmsg_nosec(sock, msg_sys);
goto out_freectl;
}
err = sock_sendmsg(sock, msg_sys);
/*
* If this is sendmmsg() and sending to current destination address was
* successful, remember it.
*/
if (used_address && err >= 0) {
used_address->name_len = msg_sys->msg_namelen;
if (msg_sys->msg_name)
memcpy(&used_address->name, msg_sys->msg_name,
used_address->name_len);
}
out_freectl:
if (ctl_buf != ctl)
sock_kfree_s(sock->sk, ctl_buf, ctl_len);
out_freeiov:
kfree(iov);
return err;
}
/*
* BSD sendmsg interface
*/
long __sys_sendmsg(int fd, struct user_msghdr __user *msg, unsigned flags)
{
int fput_needed, err;
struct msghdr msg_sys;
struct socket *sock;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
err = ___sys_sendmsg(sock, msg, &msg_sys, flags, NULL, 0);
fput_light(sock->file, fput_needed);
out:
return err;
}
SYSCALL_DEFINE3(sendmsg, int, fd, struct user_msghdr __user *, msg, unsigned int, flags)
{
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
return __sys_sendmsg(fd, msg, flags);
}
/*
* Linux sendmmsg interface
*/
int __sys_sendmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen,
unsigned int flags)
{
int fput_needed, err, datagrams;
struct socket *sock;
struct mmsghdr __user *entry;
struct compat_mmsghdr __user *compat_entry;
struct msghdr msg_sys;
struct used_address used_address;
unsigned int oflags = flags;
if (vlen > UIO_MAXIOV)
vlen = UIO_MAXIOV;
datagrams = 0;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
return err;
used_address.name_len = UINT_MAX;
entry = mmsg;
compat_entry = (struct compat_mmsghdr __user *)mmsg;
err = 0;
flags |= MSG_BATCH;
while (datagrams < vlen) {
if (datagrams == vlen - 1)
flags = oflags;
if (MSG_CMSG_COMPAT & flags) {
err = ___sys_sendmsg(sock, (struct user_msghdr __user *)compat_entry,
&msg_sys, flags, &used_address, MSG_EOR);
if (err < 0)
break;
err = __put_user(err, &compat_entry->msg_len);
++compat_entry;
} else {
err = ___sys_sendmsg(sock,
(struct user_msghdr __user *)entry,
&msg_sys, flags, &used_address, MSG_EOR);
if (err < 0)
break;
err = put_user(err, &entry->msg_len);
++entry;
}
if (err)
break;
++datagrams;
if (msg_data_left(&msg_sys))
break;
cond_resched();
}
fput_light(sock->file, fput_needed);
/* We only return an error if no datagrams were able to be sent */
if (datagrams != 0)
return datagrams;
return err;
}
SYSCALL_DEFINE4(sendmmsg, int, fd, struct mmsghdr __user *, mmsg,
unsigned int, vlen, unsigned int, flags)
{
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
return __sys_sendmmsg(fd, mmsg, vlen, flags);
}
static int ___sys_recvmsg(struct socket *sock, struct user_msghdr __user *msg,
struct msghdr *msg_sys, unsigned int flags, int nosec)
{
struct compat_msghdr __user *msg_compat =
(struct compat_msghdr __user *)msg;
struct iovec iovstack[UIO_FASTIOV];
struct iovec *iov = iovstack;
unsigned long cmsg_ptr;
int len;
ssize_t err;
/* kernel mode address */
struct sockaddr_storage addr;
/* user mode address pointers */
struct sockaddr __user *uaddr;
int __user *uaddr_len = COMPAT_NAMELEN(msg);
msg_sys->msg_name = &addr;
if (MSG_CMSG_COMPAT & flags)
err = get_compat_msghdr(msg_sys, msg_compat, &uaddr, &iov);
else
err = copy_msghdr_from_user(msg_sys, msg, &uaddr, &iov);
if (err < 0)
return err;
cmsg_ptr = (unsigned long)msg_sys->msg_control;
msg_sys->msg_flags = flags & (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT);
/* We assume all kernel code knows the size of sockaddr_storage */
msg_sys->msg_namelen = 0;
if (sock->file->f_flags & O_NONBLOCK)
flags |= MSG_DONTWAIT;
err = (nosec ? sock_recvmsg_nosec : sock_recvmsg)(sock, msg_sys, flags);
if (err < 0)
goto out_freeiov;
len = err;
if (uaddr != NULL) {
err = move_addr_to_user(&addr,
msg_sys->msg_namelen, uaddr,
uaddr_len);
if (err < 0)
goto out_freeiov;
}
err = __put_user((msg_sys->msg_flags & ~MSG_CMSG_COMPAT),
COMPAT_FLAGS(msg));
if (err)
goto out_freeiov;
if (MSG_CMSG_COMPAT & flags)
err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr,
&msg_compat->msg_controllen);
else
err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr,
&msg->msg_controllen);
if (err)
goto out_freeiov;
err = len;
out_freeiov:
kfree(iov);
return err;
}
/*
* BSD recvmsg interface
*/
long __sys_recvmsg(int fd, struct user_msghdr __user *msg, unsigned flags)
{
int fput_needed, err;
struct msghdr msg_sys;
struct socket *sock;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
err = ___sys_recvmsg(sock, msg, &msg_sys, flags, 0);
fput_light(sock->file, fput_needed);
out:
return err;
}
SYSCALL_DEFINE3(recvmsg, int, fd, struct user_msghdr __user *, msg,
unsigned int, flags)
{
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
return __sys_recvmsg(fd, msg, flags);
}
/*
* Linux recvmmsg interface
*/
int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen,
unsigned int flags, struct timespec *timeout)
{
int fput_needed, err, datagrams;
struct socket *sock;
struct mmsghdr __user *entry;
struct compat_mmsghdr __user *compat_entry;
struct msghdr msg_sys;
struct timespec64 end_time;
struct timespec64 timeout64;
if (timeout &&
poll_select_set_timeout(&end_time, timeout->tv_sec,
timeout->tv_nsec))
return -EINVAL;
datagrams = 0;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
return err;
err = sock_error(sock->sk);
if (err) {
datagrams = err;
goto out_put;
}
entry = mmsg;
compat_entry = (struct compat_mmsghdr __user *)mmsg;
while (datagrams < vlen) {
/*
* No need to ask LSM for more than the first datagram.
*/
if (MSG_CMSG_COMPAT & flags) {
err = ___sys_recvmsg(sock, (struct user_msghdr __user *)compat_entry,
&msg_sys, flags & ~MSG_WAITFORONE,
datagrams);
if (err < 0)
break;
err = __put_user(err, &compat_entry->msg_len);
++compat_entry;
} else {
err = ___sys_recvmsg(sock,
(struct user_msghdr __user *)entry,
&msg_sys, flags & ~MSG_WAITFORONE,
datagrams);
if (err < 0)
break;
err = put_user(err, &entry->msg_len);
++entry;
}
if (err)
break;
++datagrams;
/* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */
if (flags & MSG_WAITFORONE)
flags |= MSG_DONTWAIT;
if (timeout) {
ktime_get_ts64(&timeout64);
*timeout = timespec64_to_timespec(
timespec64_sub(end_time, timeout64));
if (timeout->tv_sec < 0) {
timeout->tv_sec = timeout->tv_nsec = 0;
break;
}
/* Timeout, return less than vlen datagrams */
if (timeout->tv_nsec == 0 && timeout->tv_sec == 0)
break;
}
/* Out of band data, return right away */
if (msg_sys.msg_flags & MSG_OOB)
break;
cond_resched();
}
if (err == 0)
goto out_put;
if (datagrams == 0) {
datagrams = err;
goto out_put;
}
/*
* We may return less entries than requested (vlen) if the
* sock is non block and there aren't enough datagrams...
*/
if (err != -EAGAIN) {
/*
* ... or if recvmsg returns an error after we
* received some datagrams, where we record the
* error to return on the next call or if the
* app asks about it using getsockopt(SO_ERROR).
*/
sock->sk->sk_err = -err;
}
out_put:
fput_light(sock->file, fput_needed);
return datagrams;
}
SYSCALL_DEFINE5(recvmmsg, int, fd, struct mmsghdr __user *, mmsg,
unsigned int, vlen, unsigned int, flags,
struct timespec __user *, timeout)
{
int datagrams;
struct timespec timeout_sys;
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
if (!timeout)
return __sys_recvmmsg(fd, mmsg, vlen, flags, NULL);
if (copy_from_user(&timeout_sys, timeout, sizeof(timeout_sys)))
return -EFAULT;
datagrams = __sys_recvmmsg(fd, mmsg, vlen, flags, &timeout_sys);
if (datagrams > 0 &&
copy_to_user(timeout, &timeout_sys, sizeof(timeout_sys)))
datagrams = -EFAULT;
return datagrams;
}
#ifdef __ARCH_WANT_SYS_SOCKETCALL
/* Argument list sizes for sys_socketcall */
#define AL(x) ((x) * sizeof(unsigned long))
static const unsigned char nargs[21] = {
AL(0), AL(3), AL(3), AL(3), AL(2), AL(3),
AL(3), AL(3), AL(4), AL(4), AL(4), AL(6),
AL(6), AL(2), AL(5), AL(5), AL(3), AL(3),
AL(4), AL(5), AL(4)
};
#undef AL
/*
* System call vectors.
*
* Argument checking cleaned up. Saved 20% in size.
* This function doesn't need to set the kernel lock because
* it is set by the callees.
*/
SYSCALL_DEFINE2(socketcall, int, call, unsigned long __user *, args)
{
unsigned long a[AUDITSC_ARGS];
unsigned long a0, a1;
int err;
unsigned int len;
if (call < 1 || call > SYS_SENDMMSG)
return -EINVAL;
len = nargs[call];
if (len > sizeof(a))
return -EINVAL;
/* copy_from_user should be SMP safe. */
if (copy_from_user(a, args, len))
return -EFAULT;
err = audit_socketcall(nargs[call] / sizeof(unsigned long), a);
if (err)
return err;
a0 = a[0];
a1 = a[1];
switch (call) {
case SYS_SOCKET:
err = sys_socket(a0, a1, a[2]);
break;
case SYS_BIND:
err = sys_bind(a0, (struct sockaddr __user *)a1, a[2]);
break;
case SYS_CONNECT:
err = sys_connect(a0, (struct sockaddr __user *)a1, a[2]);
break;
case SYS_LISTEN:
err = sys_listen(a0, a1);
break;
case SYS_ACCEPT:
err = sys_accept4(a0, (struct sockaddr __user *)a1,
(int __user *)a[2], 0);
break;
case SYS_GETSOCKNAME:
err =
sys_getsockname(a0, (struct sockaddr __user *)a1,
(int __user *)a[2]);
break;
case SYS_GETPEERNAME:
err =
sys_getpeername(a0, (struct sockaddr __user *)a1,
(int __user *)a[2]);
break;
case SYS_SOCKETPAIR:
err = sys_socketpair(a0, a1, a[2], (int __user *)a[3]);
break;
case SYS_SEND:
err = sys_send(a0, (void __user *)a1, a[2], a[3]);
break;
case SYS_SENDTO:
err = sys_sendto(a0, (void __user *)a1, a[2], a[3],
(struct sockaddr __user *)a[4], a[5]);
break;
case SYS_RECV:
err = sys_recv(a0, (void __user *)a1, a[2], a[3]);
break;
case SYS_RECVFROM:
err = sys_recvfrom(a0, (void __user *)a1, a[2], a[3],
(struct sockaddr __user *)a[4],
(int __user *)a[5]);
break;
case SYS_SHUTDOWN:
err = sys_shutdown(a0, a1);
break;
case SYS_SETSOCKOPT:
err = sys_setsockopt(a0, a1, a[2], (char __user *)a[3], a[4]);
break;
case SYS_GETSOCKOPT:
err =
sys_getsockopt(a0, a1, a[2], (char __user *)a[3],
(int __user *)a[4]);
break;
case SYS_SENDMSG:
err = sys_sendmsg(a0, (struct user_msghdr __user *)a1, a[2]);
break;
case SYS_SENDMMSG:
err = sys_sendmmsg(a0, (struct mmsghdr __user *)a1, a[2], a[3]);
break;
case SYS_RECVMSG:
err = sys_recvmsg(a0, (struct user_msghdr __user *)a1, a[2]);
break;
case SYS_RECVMMSG:
err = sys_recvmmsg(a0, (struct mmsghdr __user *)a1, a[2], a[3],
(struct timespec __user *)a[4]);
break;
case SYS_ACCEPT4:
err = sys_accept4(a0, (struct sockaddr __user *)a1,
(int __user *)a[2], a[3]);
break;
default:
err = -EINVAL;
break;
}
return err;
}
#endif /* __ARCH_WANT_SYS_SOCKETCALL */
/**
* sock_register - add a socket protocol handler
* @ops: description of protocol
*
* This function is called by a protocol handler that wants to
* advertise its address family, and have it linked into the
* socket interface. The value ops->family corresponds to the
* socket system call protocol family.
*/
int sock_register(const struct net_proto_family *ops)
{
int err;
if (ops->family >= NPROTO) {
pr_crit("protocol %d >= NPROTO(%d)\n", ops->family, NPROTO);
return -ENOBUFS;
}
spin_lock(&net_family_lock);
if (rcu_dereference_protected(net_families[ops->family],
lockdep_is_held(&net_family_lock)))
err = -EEXIST;
else {
rcu_assign_pointer(net_families[ops->family], ops);
err = 0;
}
spin_unlock(&net_family_lock);
pr_info("NET: Registered protocol family %d\n", ops->family);
return err;
}
EXPORT_SYMBOL(sock_register);
/**
* sock_unregister - remove a protocol handler
* @family: protocol family to remove
*
* This function is called by a protocol handler that wants to
* remove its address family, and have it unlinked from the
* new socket creation.
*
* If protocol handler is a module, then it can use module reference
* counts to protect against new references. If protocol handler is not
* a module then it needs to provide its own protection in
* the ops->create routine.
*/
void sock_unregister(int family)
{
BUG_ON(family < 0 || family >= NPROTO);
spin_lock(&net_family_lock);
RCU_INIT_POINTER(net_families[family], NULL);
spin_unlock(&net_family_lock);
synchronize_rcu();
pr_info("NET: Unregistered protocol family %d\n", family);
}
EXPORT_SYMBOL(sock_unregister);
static int __init sock_init(void)
{
int err;
/*
* Initialize the network sysctl infrastructure.
*/
err = net_sysctl_init();
if (err)
goto out;
/*
* Initialize skbuff SLAB cache
*/
skb_init();
/*
* Initialize the protocols module.
*/
init_inodecache();
err = register_filesystem(&sock_fs_type);
if (err)
goto out_fs;
sock_mnt = kern_mount(&sock_fs_type);
if (IS_ERR(sock_mnt)) {
err = PTR_ERR(sock_mnt);
goto out_mount;
}
/* The real protocol initialization is performed in later initcalls.
*/
#ifdef CONFIG_NETFILTER
err = netfilter_init();
if (err)
goto out;
#endif
ptp_classifier_init();
out:
return err;
out_mount:
unregister_filesystem(&sock_fs_type);
out_fs:
goto out;
}
core_initcall(sock_init); /* early initcall */
#ifdef CONFIG_PROC_FS
void socket_seq_show(struct seq_file *seq)
{
int cpu;
int counter = 0;
for_each_possible_cpu(cpu)
counter += per_cpu(sockets_in_use, cpu);
/* It can be negative, by the way. 8) */
if (counter < 0)
counter = 0;
seq_printf(seq, "sockets: used %d\n", counter);
}
#endif /* CONFIG_PROC_FS */
#ifdef CONFIG_COMPAT
static int do_siocgstamp(struct net *net, struct socket *sock,
unsigned int cmd, void __user *up)
{
mm_segment_t old_fs = get_fs();
struct timeval ktv;
int err;
set_fs(KERNEL_DS);
err = sock_do_ioctl(net, sock, cmd, (unsigned long)&ktv);
set_fs(old_fs);
if (!err)
err = compat_put_timeval(&ktv, up);
return err;
}
static int do_siocgstampns(struct net *net, struct socket *sock,
unsigned int cmd, void __user *up)
{
mm_segment_t old_fs = get_fs();
struct timespec kts;
int err;
set_fs(KERNEL_DS);
err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts);
set_fs(old_fs);
if (!err)
err = compat_put_timespec(&kts, up);
return err;
}
static int dev_ifname32(struct net *net, struct compat_ifreq __user *uifr32)
{
struct ifreq __user *uifr;
int err;
uifr = compat_alloc_user_space(sizeof(struct ifreq));
if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq)))
return -EFAULT;
err = dev_ioctl(net, SIOCGIFNAME, uifr);
if (err)
return err;
if (copy_in_user(uifr32, uifr, sizeof(struct compat_ifreq)))
return -EFAULT;
return 0;
}
static int dev_ifconf(struct net *net, struct compat_ifconf __user *uifc32)
{
struct compat_ifconf ifc32;
struct ifconf ifc;
struct ifconf __user *uifc;
struct compat_ifreq __user *ifr32;
struct ifreq __user *ifr;
unsigned int i, j;
int err;
if (copy_from_user(&ifc32, uifc32, sizeof(struct compat_ifconf)))
return -EFAULT;
memset(&ifc, 0, sizeof(ifc));
if (ifc32.ifcbuf == 0) {
ifc32.ifc_len = 0;
ifc.ifc_len = 0;
ifc.ifc_req = NULL;
uifc = compat_alloc_user_space(sizeof(struct ifconf));
} else {
size_t len = ((ifc32.ifc_len / sizeof(struct compat_ifreq)) + 1) *
sizeof(struct ifreq);
uifc = compat_alloc_user_space(sizeof(struct ifconf) + len);
ifc.ifc_len = len;
ifr = ifc.ifc_req = (void __user *)(uifc + 1);
ifr32 = compat_ptr(ifc32.ifcbuf);
for (i = 0; i < ifc32.ifc_len; i += sizeof(struct compat_ifreq)) {
if (copy_in_user(ifr, ifr32, sizeof(struct compat_ifreq)))
return -EFAULT;
ifr++;
ifr32++;
}
}
if (copy_to_user(uifc, &ifc, sizeof(struct ifconf)))
return -EFAULT;
err = dev_ioctl(net, SIOCGIFCONF, uifc);
if (err)
return err;
if (copy_from_user(&ifc, uifc, sizeof(struct ifconf)))
return -EFAULT;
ifr = ifc.ifc_req;
ifr32 = compat_ptr(ifc32.ifcbuf);
for (i = 0, j = 0;
i + sizeof(struct compat_ifreq) <= ifc32.ifc_len && j < ifc.ifc_len;
i += sizeof(struct compat_ifreq), j += sizeof(struct ifreq)) {
if (copy_in_user(ifr32, ifr, sizeof(struct compat_ifreq)))
return -EFAULT;
ifr32++;
ifr++;
}
if (ifc32.ifcbuf == 0) {
/* Translate from 64-bit structure multiple to
* a 32-bit one.
*/
i = ifc.ifc_len;
i = ((i / sizeof(struct ifreq)) * sizeof(struct compat_ifreq));
ifc32.ifc_len = i;
} else {
ifc32.ifc_len = i;
}
if (copy_to_user(uifc32, &ifc32, sizeof(struct compat_ifconf)))
return -EFAULT;
return 0;
}
static int ethtool_ioctl(struct net *net, struct compat_ifreq __user *ifr32)
{
struct compat_ethtool_rxnfc __user *compat_rxnfc;
bool convert_in = false, convert_out = false;
size_t buf_size = ALIGN(sizeof(struct ifreq), 8);
struct ethtool_rxnfc __user *rxnfc;
struct ifreq __user *ifr;
u32 rule_cnt = 0, actual_rule_cnt;
u32 ethcmd;
u32 data;
int ret;
if (get_user(data, &ifr32->ifr_ifru.ifru_data))
return -EFAULT;
compat_rxnfc = compat_ptr(data);
if (get_user(ethcmd, &compat_rxnfc->cmd))
return -EFAULT;
/* Most ethtool structures are defined without padding.
* Unfortunately struct ethtool_rxnfc is an exception.
*/
switch (ethcmd) {
default:
break;
case ETHTOOL_GRXCLSRLALL:
/* Buffer size is variable */
if (get_user(rule_cnt, &compat_rxnfc->rule_cnt))
return -EFAULT;
if (rule_cnt > KMALLOC_MAX_SIZE / sizeof(u32))
return -ENOMEM;
buf_size += rule_cnt * sizeof(u32);
/* fall through */
case ETHTOOL_GRXRINGS:
case ETHTOOL_GRXCLSRLCNT:
case ETHTOOL_GRXCLSRULE:
case ETHTOOL_SRXCLSRLINS:
convert_out = true;
/* fall through */
case ETHTOOL_SRXCLSRLDEL:
buf_size += sizeof(struct ethtool_rxnfc);
convert_in = true;
break;
}
ifr = compat_alloc_user_space(buf_size);
rxnfc = (void __user *)ifr + ALIGN(sizeof(struct ifreq), 8);
if (copy_in_user(&ifr->ifr_name, &ifr32->ifr_name, IFNAMSIZ))
return -EFAULT;
if (put_user(convert_in ? rxnfc : compat_ptr(data),
&ifr->ifr_ifru.ifru_data))
return -EFAULT;
if (convert_in) {
/* We expect there to be holes between fs.m_ext and
* fs.ring_cookie and at the end of fs, but nowhere else.
*/
BUILD_BUG_ON(offsetof(struct compat_ethtool_rxnfc, fs.m_ext) +
sizeof(compat_rxnfc->fs.m_ext) !=
offsetof(struct ethtool_rxnfc, fs.m_ext) +
sizeof(rxnfc->fs.m_ext));
BUILD_BUG_ON(
offsetof(struct compat_ethtool_rxnfc, fs.location) -
offsetof(struct compat_ethtool_rxnfc, fs.ring_cookie) !=
offsetof(struct ethtool_rxnfc, fs.location) -
offsetof(struct ethtool_rxnfc, fs.ring_cookie));
if (copy_in_user(rxnfc, compat_rxnfc,
(void __user *)(&rxnfc->fs.m_ext + 1) -
(void __user *)rxnfc) ||
copy_in_user(&rxnfc->fs.ring_cookie,
&compat_rxnfc->fs.ring_cookie,
(void __user *)(&rxnfc->fs.location + 1) -
(void __user *)&rxnfc->fs.ring_cookie) ||
copy_in_user(&rxnfc->rule_cnt, &compat_rxnfc->rule_cnt,
sizeof(rxnfc->rule_cnt)))
return -EFAULT;
}
ret = dev_ioctl(net, SIOCETHTOOL, ifr);
if (ret)
return ret;
if (convert_out) {
if (copy_in_user(compat_rxnfc, rxnfc,
(const void __user *)(&rxnfc->fs.m_ext + 1) -
(const void __user *)rxnfc) ||
copy_in_user(&compat_rxnfc->fs.ring_cookie,
&rxnfc->fs.ring_cookie,
(const void __user *)(&rxnfc->fs.location + 1) -
(const void __user *)&rxnfc->fs.ring_cookie) ||
copy_in_user(&compat_rxnfc->rule_cnt, &rxnfc->rule_cnt,
sizeof(rxnfc->rule_cnt)))
return -EFAULT;
if (ethcmd == ETHTOOL_GRXCLSRLALL) {
/* As an optimisation, we only copy the actual
* number of rules that the underlying
* function returned. Since Mallory might
* change the rule count in user memory, we
* check that it is less than the rule count
* originally given (as the user buffer size),
* which has been range-checked.
*/
if (get_user(actual_rule_cnt, &rxnfc->rule_cnt))
return -EFAULT;
if (actual_rule_cnt < rule_cnt)
rule_cnt = actual_rule_cnt;
if (copy_in_user(&compat_rxnfc->rule_locs[0],
&rxnfc->rule_locs[0],
rule_cnt * sizeof(u32)))
return -EFAULT;
}
}
return 0;
}
static int compat_siocwandev(struct net *net, struct compat_ifreq __user *uifr32)
{
void __user *uptr;
compat_uptr_t uptr32;
struct ifreq __user *uifr;
uifr = compat_alloc_user_space(sizeof(*uifr));
if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq)))
return -EFAULT;
if (get_user(uptr32, &uifr32->ifr_settings.ifs_ifsu))
return -EFAULT;
uptr = compat_ptr(uptr32);
if (put_user(uptr, &uifr->ifr_settings.ifs_ifsu.raw_hdlc))
return -EFAULT;
return dev_ioctl(net, SIOCWANDEV, uifr);
}
static int bond_ioctl(struct net *net, unsigned int cmd,
struct compat_ifreq __user *ifr32)
{
struct ifreq kifr;
mm_segment_t old_fs;
int err;
switch (cmd) {
case SIOCBONDENSLAVE:
case SIOCBONDRELEASE:
case SIOCBONDSETHWADDR:
case SIOCBONDCHANGEACTIVE:
if (copy_from_user(&kifr, ifr32, sizeof(struct compat_ifreq)))
return -EFAULT;
old_fs = get_fs();
set_fs(KERNEL_DS);
err = dev_ioctl(net, cmd,
(struct ifreq __user __force *) &kifr);
set_fs(old_fs);
return err;
default:
return -ENOIOCTLCMD;
}
}
/* Handle ioctls that use ifreq::ifr_data and just need struct ifreq converted */
static int compat_ifr_data_ioctl(struct net *net, unsigned int cmd,
struct compat_ifreq __user *u_ifreq32)
{
struct ifreq __user *u_ifreq64;
char tmp_buf[IFNAMSIZ];
void __user *data64;
u32 data32;
if (copy_from_user(&tmp_buf[0], &(u_ifreq32->ifr_ifrn.ifrn_name[0]),
IFNAMSIZ))
return -EFAULT;
if (get_user(data32, &u_ifreq32->ifr_ifru.ifru_data))
return -EFAULT;
data64 = compat_ptr(data32);
u_ifreq64 = compat_alloc_user_space(sizeof(*u_ifreq64));
if (copy_to_user(&u_ifreq64->ifr_ifrn.ifrn_name[0], &tmp_buf[0],
IFNAMSIZ))
return -EFAULT;
if (put_user(data64, &u_ifreq64->ifr_ifru.ifru_data))
return -EFAULT;
return dev_ioctl(net, cmd, u_ifreq64);
}
static int dev_ifsioc(struct net *net, struct socket *sock,
unsigned int cmd, struct compat_ifreq __user *uifr32)
{
struct ifreq __user *uifr;
int err;
uifr = compat_alloc_user_space(sizeof(*uifr));
if (copy_in_user(uifr, uifr32, sizeof(*uifr32)))
return -EFAULT;
err = sock_do_ioctl(net, sock, cmd, (unsigned long)uifr);
if (!err) {
switch (cmd) {
case SIOCGIFFLAGS:
case SIOCGIFMETRIC:
case SIOCGIFMTU:
case SIOCGIFMEM:
case SIOCGIFHWADDR:
case SIOCGIFINDEX:
case SIOCGIFADDR:
case SIOCGIFBRDADDR:
case SIOCGIFDSTADDR:
case SIOCGIFNETMASK:
case SIOCGIFPFLAGS:
case SIOCGIFTXQLEN:
case SIOCGMIIPHY:
case SIOCGMIIREG:
if (copy_in_user(uifr32, uifr, sizeof(*uifr32)))
err = -EFAULT;
break;
}
}
return err;
}
static int compat_sioc_ifmap(struct net *net, unsigned int cmd,
struct compat_ifreq __user *uifr32)
{
struct ifreq ifr;
struct compat_ifmap __user *uifmap32;
mm_segment_t old_fs;
int err;
uifmap32 = &uifr32->ifr_ifru.ifru_map;
err = copy_from_user(&ifr, uifr32, sizeof(ifr.ifr_name));
err |= get_user(ifr.ifr_map.mem_start, &uifmap32->mem_start);
err |= get_user(ifr.ifr_map.mem_end, &uifmap32->mem_end);
err |= get_user(ifr.ifr_map.base_addr, &uifmap32->base_addr);
err |= get_user(ifr.ifr_map.irq, &uifmap32->irq);
err |= get_user(ifr.ifr_map.dma, &uifmap32->dma);
err |= get_user(ifr.ifr_map.port, &uifmap32->port);
if (err)
return -EFAULT;
old_fs = get_fs();
set_fs(KERNEL_DS);
err = dev_ioctl(net, cmd, (void __user __force *)&ifr);
set_fs(old_fs);
if (cmd == SIOCGIFMAP && !err) {
err = copy_to_user(uifr32, &ifr, sizeof(ifr.ifr_name));
err |= put_user(ifr.ifr_map.mem_start, &uifmap32->mem_start);
err |= put_user(ifr.ifr_map.mem_end, &uifmap32->mem_end);
err |= put_user(ifr.ifr_map.base_addr, &uifmap32->base_addr);
err |= put_user(ifr.ifr_map.irq, &uifmap32->irq);
err |= put_user(ifr.ifr_map.dma, &uifmap32->dma);
err |= put_user(ifr.ifr_map.port, &uifmap32->port);
if (err)
err = -EFAULT;
}
return err;
}
struct rtentry32 {
u32 rt_pad1;
struct sockaddr rt_dst; /* target address */
struct sockaddr rt_gateway; /* gateway addr (RTF_GATEWAY) */
struct sockaddr rt_genmask; /* target network mask (IP) */
unsigned short rt_flags;
short rt_pad2;
u32 rt_pad3;
unsigned char rt_tos;
unsigned char rt_class;
short rt_pad4;
short rt_metric; /* +1 for binary compatibility! */
/* char * */ u32 rt_dev; /* forcing the device at add */
u32 rt_mtu; /* per route MTU/Window */
u32 rt_window; /* Window clamping */
unsigned short rt_irtt; /* Initial RTT */
};
struct in6_rtmsg32 {
struct in6_addr rtmsg_dst;
struct in6_addr rtmsg_src;
struct in6_addr rtmsg_gateway;
u32 rtmsg_type;
u16 rtmsg_dst_len;
u16 rtmsg_src_len;
u32 rtmsg_metric;
u32 rtmsg_info;
u32 rtmsg_flags;
s32 rtmsg_ifindex;
};
static int routing_ioctl(struct net *net, struct socket *sock,
unsigned int cmd, void __user *argp)
{
int ret;
void *r = NULL;
struct in6_rtmsg r6;
struct rtentry r4;
char devname[16];
u32 rtdev;
mm_segment_t old_fs = get_fs();
if (sock && sock->sk && sock->sk->sk_family == AF_INET6) { /* ipv6 */
struct in6_rtmsg32 __user *ur6 = argp;
ret = copy_from_user(&r6.rtmsg_dst, &(ur6->rtmsg_dst),
3 * sizeof(struct in6_addr));
ret |= get_user(r6.rtmsg_type, &(ur6->rtmsg_type));
ret |= get_user(r6.rtmsg_dst_len, &(ur6->rtmsg_dst_len));
ret |= get_user(r6.rtmsg_src_len, &(ur6->rtmsg_src_len));
ret |= get_user(r6.rtmsg_metric, &(ur6->rtmsg_metric));
ret |= get_user(r6.rtmsg_info, &(ur6->rtmsg_info));
ret |= get_user(r6.rtmsg_flags, &(ur6->rtmsg_flags));
ret |= get_user(r6.rtmsg_ifindex, &(ur6->rtmsg_ifindex));
r = (void *) &r6;
} else { /* ipv4 */
struct rtentry32 __user *ur4 = argp;
ret = copy_from_user(&r4.rt_dst, &(ur4->rt_dst),
3 * sizeof(struct sockaddr));
ret |= get_user(r4.rt_flags, &(ur4->rt_flags));
ret |= get_user(r4.rt_metric, &(ur4->rt_metric));
ret |= get_user(r4.rt_mtu, &(ur4->rt_mtu));
ret |= get_user(r4.rt_window, &(ur4->rt_window));
ret |= get_user(r4.rt_irtt, &(ur4->rt_irtt));
ret |= get_user(rtdev, &(ur4->rt_dev));
if (rtdev) {
ret |= copy_from_user(devname, compat_ptr(rtdev), 15);
r4.rt_dev = (char __user __force *)devname;
devname[15] = 0;
} else
r4.rt_dev = NULL;
r = (void *) &r4;
}
if (ret) {
ret = -EFAULT;
goto out;
}
set_fs(KERNEL_DS);
ret = sock_do_ioctl(net, sock, cmd, (unsigned long) r);
set_fs(old_fs);
out:
return ret;
}
/* Since old style bridge ioctl's endup using SIOCDEVPRIVATE
* for some operations; this forces use of the newer bridge-utils that
* use compatible ioctls
*/
static int old_bridge_ioctl(compat_ulong_t __user *argp)
{
compat_ulong_t tmp;
if (get_user(tmp, argp))
return -EFAULT;
if (tmp == BRCTL_GET_VERSION)
return BRCTL_VERSION + 1;
return -EINVAL;
}
static int compat_sock_ioctl_trans(struct file *file, struct socket *sock,
unsigned int cmd, unsigned long arg)
{
void __user *argp = compat_ptr(arg);
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15))
return compat_ifr_data_ioctl(net, cmd, argp);
switch (cmd) {
case SIOCSIFBR:
case SIOCGIFBR:
return old_bridge_ioctl(argp);
case SIOCGIFNAME:
return dev_ifname32(net, argp);
case SIOCGIFCONF:
return dev_ifconf(net, argp);
case SIOCETHTOOL:
return ethtool_ioctl(net, argp);
case SIOCWANDEV:
return compat_siocwandev(net, argp);
case SIOCGIFMAP:
case SIOCSIFMAP:
return compat_sioc_ifmap(net, cmd, argp);
case SIOCBONDENSLAVE:
case SIOCBONDRELEASE:
case SIOCBONDSETHWADDR:
case SIOCBONDCHANGEACTIVE:
return bond_ioctl(net, cmd, argp);
case SIOCADDRT:
case SIOCDELRT:
return routing_ioctl(net, sock, cmd, argp);
case SIOCGSTAMP:
return do_siocgstamp(net, sock, cmd, argp);
case SIOCGSTAMPNS:
return do_siocgstampns(net, sock, cmd, argp);
case SIOCBONDSLAVEINFOQUERY:
case SIOCBONDINFOQUERY:
case SIOCSHWTSTAMP:
case SIOCGHWTSTAMP:
return compat_ifr_data_ioctl(net, cmd, argp);
case FIOSETOWN:
case SIOCSPGRP:
case FIOGETOWN:
case SIOCGPGRP:
case SIOCBRADDBR:
case SIOCBRDELBR:
case SIOCGIFVLAN:
case SIOCSIFVLAN:
case SIOCADDDLCI:
case SIOCDELDLCI:
case SIOCGSKNS:
return sock_ioctl(file, cmd, arg);
case SIOCGIFFLAGS:
case SIOCSIFFLAGS:
case SIOCGIFMETRIC:
case SIOCSIFMETRIC:
case SIOCGIFMTU:
case SIOCSIFMTU:
case SIOCGIFMEM:
case SIOCSIFMEM:
case SIOCGIFHWADDR:
case SIOCSIFHWADDR:
case SIOCADDMULTI:
case SIOCDELMULTI:
case SIOCGIFINDEX:
case SIOCGIFADDR:
case SIOCSIFADDR:
case SIOCSIFHWBROADCAST:
case SIOCDIFADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
case SIOCSIFPFLAGS:
case SIOCGIFPFLAGS:
case SIOCGIFTXQLEN:
case SIOCSIFTXQLEN:
case SIOCBRADDIF:
case SIOCBRDELIF:
case SIOCSIFNAME:
case SIOCGMIIPHY:
case SIOCGMIIREG:
case SIOCSMIIREG:
return dev_ifsioc(net, sock, cmd, argp);
case SIOCSARP:
case SIOCGARP:
case SIOCDARP:
case SIOCATMARK:
return sock_do_ioctl(net, sock, cmd, arg);
}
return -ENOIOCTLCMD;
}
static long compat_sock_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct socket *sock = file->private_data;
int ret = -ENOIOCTLCMD;
struct sock *sk;
struct net *net;
sk = sock->sk;
net = sock_net(sk);
if (sock->ops->compat_ioctl)
ret = sock->ops->compat_ioctl(sock, cmd, arg);
if (ret == -ENOIOCTLCMD &&
(cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST))
ret = compat_wext_handle_ioctl(net, cmd, arg);
if (ret == -ENOIOCTLCMD)
ret = compat_sock_ioctl_trans(file, sock, cmd, arg);
return ret;
}
#endif
int kernel_bind(struct socket *sock, struct sockaddr *addr, int addrlen)
{
return sock->ops->bind(sock, addr, addrlen);
}
EXPORT_SYMBOL(kernel_bind);
int kernel_listen(struct socket *sock, int backlog)
{
return sock->ops->listen(sock, backlog);
}
EXPORT_SYMBOL(kernel_listen);
int kernel_accept(struct socket *sock, struct socket **newsock, int flags)
{
struct sock *sk = sock->sk;
int err;
err = sock_create_lite(sk->sk_family, sk->sk_type, sk->sk_protocol,
newsock);
if (err < 0)
goto done;
err = sock->ops->accept(sock, *newsock, flags, true);
if (err < 0) {
sock_release(*newsock);
*newsock = NULL;
goto done;
}
(*newsock)->ops = sock->ops;
__module_get((*newsock)->ops->owner);
done:
return err;
}
EXPORT_SYMBOL(kernel_accept);
int kernel_connect(struct socket *sock, struct sockaddr *addr, int addrlen,
int flags)
{
return sock->ops->connect(sock, addr, addrlen, flags);
}
EXPORT_SYMBOL(kernel_connect);
int kernel_getsockname(struct socket *sock, struct sockaddr *addr,
int *addrlen)
{
return sock->ops->getname(sock, addr, addrlen, 0);
}
EXPORT_SYMBOL(kernel_getsockname);
int kernel_getpeername(struct socket *sock, struct sockaddr *addr,
int *addrlen)
{
return sock->ops->getname(sock, addr, addrlen, 1);
}
EXPORT_SYMBOL(kernel_getpeername);
int kernel_getsockopt(struct socket *sock, int level, int optname,
char *optval, int *optlen)
{
mm_segment_t oldfs = get_fs();
char __user *uoptval;
int __user *uoptlen;
int err;
uoptval = (char __user __force *) optval;
uoptlen = (int __user __force *) optlen;
set_fs(KERNEL_DS);
if (level == SOL_SOCKET)
err = sock_getsockopt(sock, level, optname, uoptval, uoptlen);
else
err = sock->ops->getsockopt(sock, level, optname, uoptval,
uoptlen);
set_fs(oldfs);
return err;
}
EXPORT_SYMBOL(kernel_getsockopt);
int kernel_setsockopt(struct socket *sock, int level, int optname,
char *optval, unsigned int optlen)
{
mm_segment_t oldfs = get_fs();
char __user *uoptval;
int err;
uoptval = (char __user __force *) optval;
set_fs(KERNEL_DS);
if (level == SOL_SOCKET)
err = sock_setsockopt(sock, level, optname, uoptval, optlen);
else
err = sock->ops->setsockopt(sock, level, optname, uoptval,
optlen);
set_fs(oldfs);
return err;
}
EXPORT_SYMBOL(kernel_setsockopt);
int kernel_sendpage(struct socket *sock, struct page *page, int offset,
size_t size, int flags)
{
if (sock->ops->sendpage)
return sock->ops->sendpage(sock, page, offset, size, flags);
return sock_no_sendpage(sock, page, offset, size, flags);
}
EXPORT_SYMBOL(kernel_sendpage);
int kernel_sock_ioctl(struct socket *sock, int cmd, unsigned long arg)
{
mm_segment_t oldfs = get_fs();
int err;
set_fs(KERNEL_DS);
err = sock->ops->ioctl(sock, cmd, arg);
set_fs(oldfs);
return err;
}
EXPORT_SYMBOL(kernel_sock_ioctl);
int kernel_sock_shutdown(struct socket *sock, enum sock_shutdown_cmd how)
{
return sock->ops->shutdown(sock, how);
}
EXPORT_SYMBOL(kernel_sock_shutdown);
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3255_1 |
crossvul-cpp_data_bad_543_0 | // SPDX-License-Identifier: (GPL-2.0 OR MIT)
/*
* SerDes PHY driver for Microsemi Ocelot
*
* Copyright (c) 2018 Microsemi
*
*/
#include <linux/err.h>
#include <linux/mfd/syscon.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_platform.h>
#include <linux/phy/phy.h>
#include <linux/platform_device.h>
#include <linux/regmap.h>
#include <soc/mscc/ocelot_hsio.h>
#include <dt-bindings/phy/phy-ocelot-serdes.h>
struct serdes_ctrl {
struct regmap *regs;
struct device *dev;
struct phy *phys[SERDES_MAX];
};
struct serdes_macro {
u8 idx;
/* Not used when in QSGMII or PCIe mode */
int port;
struct serdes_ctrl *ctrl;
};
#define MCB_S1G_CFG_TIMEOUT 50
static int __serdes_write_mcb_s1g(struct regmap *regmap, u8 macro, u32 op)
{
unsigned int regval;
regmap_write(regmap, HSIO_MCB_S1G_ADDR_CFG, op |
HSIO_MCB_S1G_ADDR_CFG_SERDES1G_ADDR(BIT(macro)));
return regmap_read_poll_timeout(regmap, HSIO_MCB_S1G_ADDR_CFG, regval,
(regval & op) != op, 100,
MCB_S1G_CFG_TIMEOUT * 1000);
}
static int serdes_commit_mcb_s1g(struct regmap *regmap, u8 macro)
{
return __serdes_write_mcb_s1g(regmap, macro,
HSIO_MCB_S1G_ADDR_CFG_SERDES1G_WR_ONE_SHOT);
}
static int serdes_update_mcb_s1g(struct regmap *regmap, u8 macro)
{
return __serdes_write_mcb_s1g(regmap, macro,
HSIO_MCB_S1G_ADDR_CFG_SERDES1G_RD_ONE_SHOT);
}
static int serdes_init_s1g(struct regmap *regmap, u8 serdes)
{
int ret;
ret = serdes_update_mcb_s1g(regmap, serdes);
if (ret)
return ret;
regmap_update_bits(regmap, HSIO_S1G_COMMON_CFG,
HSIO_S1G_COMMON_CFG_SYS_RST |
HSIO_S1G_COMMON_CFG_ENA_LANE |
HSIO_S1G_COMMON_CFG_ENA_ELOOP |
HSIO_S1G_COMMON_CFG_ENA_FLOOP,
HSIO_S1G_COMMON_CFG_ENA_LANE);
regmap_update_bits(regmap, HSIO_S1G_PLL_CFG,
HSIO_S1G_PLL_CFG_PLL_FSM_ENA |
HSIO_S1G_PLL_CFG_PLL_FSM_CTRL_DATA_M,
HSIO_S1G_PLL_CFG_PLL_FSM_CTRL_DATA(200) |
HSIO_S1G_PLL_CFG_PLL_FSM_ENA);
regmap_update_bits(regmap, HSIO_S1G_MISC_CFG,
HSIO_S1G_MISC_CFG_DES_100FX_CPMD_ENA |
HSIO_S1G_MISC_CFG_LANE_RST,
HSIO_S1G_MISC_CFG_LANE_RST);
ret = serdes_commit_mcb_s1g(regmap, serdes);
if (ret)
return ret;
regmap_update_bits(regmap, HSIO_S1G_COMMON_CFG,
HSIO_S1G_COMMON_CFG_SYS_RST,
HSIO_S1G_COMMON_CFG_SYS_RST);
regmap_update_bits(regmap, HSIO_S1G_MISC_CFG,
HSIO_S1G_MISC_CFG_LANE_RST, 0);
ret = serdes_commit_mcb_s1g(regmap, serdes);
if (ret)
return ret;
return 0;
}
struct serdes_mux {
u8 idx;
u8 port;
enum phy_mode mode;
u32 mask;
u32 mux;
};
#define SERDES_MUX(_idx, _port, _mode, _mask, _mux) { \
.idx = _idx, \
.port = _port, \
.mode = _mode, \
.mask = _mask, \
.mux = _mux, \
}
#define SERDES_MUX_SGMII(i, p, m, c) SERDES_MUX(i, p, PHY_MODE_SGMII, m, c)
#define SERDES_MUX_QSGMII(i, p, m, c) SERDES_MUX(i, p, PHY_MODE_QSGMII, m, c)
static const struct serdes_mux ocelot_serdes_muxes[] = {
SERDES_MUX_SGMII(SERDES1G(0), 0, 0, 0),
SERDES_MUX_SGMII(SERDES1G(1), 1, HSIO_HW_CFG_DEV1G_5_MODE, 0),
SERDES_MUX_SGMII(SERDES1G(1), 5, HSIO_HW_CFG_QSGMII_ENA |
HSIO_HW_CFG_DEV1G_5_MODE, HSIO_HW_CFG_DEV1G_5_MODE),
SERDES_MUX_SGMII(SERDES1G(2), 2, HSIO_HW_CFG_DEV1G_4_MODE, 0),
SERDES_MUX_SGMII(SERDES1G(2), 4, HSIO_HW_CFG_QSGMII_ENA |
HSIO_HW_CFG_DEV1G_4_MODE, HSIO_HW_CFG_DEV1G_4_MODE),
SERDES_MUX_SGMII(SERDES1G(3), 3, HSIO_HW_CFG_DEV1G_6_MODE, 0),
SERDES_MUX_SGMII(SERDES1G(3), 6, HSIO_HW_CFG_QSGMII_ENA |
HSIO_HW_CFG_DEV1G_6_MODE, HSIO_HW_CFG_DEV1G_6_MODE),
SERDES_MUX_SGMII(SERDES1G(4), 4, HSIO_HW_CFG_QSGMII_ENA |
HSIO_HW_CFG_DEV1G_4_MODE | HSIO_HW_CFG_DEV1G_9_MODE,
0),
SERDES_MUX_SGMII(SERDES1G(4), 9, HSIO_HW_CFG_DEV1G_4_MODE |
HSIO_HW_CFG_DEV1G_9_MODE, HSIO_HW_CFG_DEV1G_4_MODE |
HSIO_HW_CFG_DEV1G_9_MODE),
SERDES_MUX_SGMII(SERDES1G(5), 5, HSIO_HW_CFG_QSGMII_ENA |
HSIO_HW_CFG_DEV1G_5_MODE | HSIO_HW_CFG_DEV2G5_10_MODE,
0),
SERDES_MUX_SGMII(SERDES1G(5), 10, HSIO_HW_CFG_PCIE_ENA |
HSIO_HW_CFG_DEV1G_5_MODE | HSIO_HW_CFG_DEV2G5_10_MODE,
HSIO_HW_CFG_DEV1G_5_MODE | HSIO_HW_CFG_DEV2G5_10_MODE),
SERDES_MUX_QSGMII(SERDES6G(0), 4, HSIO_HW_CFG_QSGMII_ENA,
HSIO_HW_CFG_QSGMII_ENA),
SERDES_MUX_QSGMII(SERDES6G(0), 5, HSIO_HW_CFG_QSGMII_ENA,
HSIO_HW_CFG_QSGMII_ENA),
SERDES_MUX_QSGMII(SERDES6G(0), 6, HSIO_HW_CFG_QSGMII_ENA,
HSIO_HW_CFG_QSGMII_ENA),
SERDES_MUX_SGMII(SERDES6G(0), 7, HSIO_HW_CFG_QSGMII_ENA, 0),
SERDES_MUX_QSGMII(SERDES6G(0), 7, HSIO_HW_CFG_QSGMII_ENA,
HSIO_HW_CFG_QSGMII_ENA),
SERDES_MUX_SGMII(SERDES6G(1), 8, 0, 0),
SERDES_MUX_SGMII(SERDES6G(2), 10, HSIO_HW_CFG_PCIE_ENA |
HSIO_HW_CFG_DEV2G5_10_MODE, 0),
SERDES_MUX(SERDES6G(2), 10, PHY_MODE_PCIE, HSIO_HW_CFG_PCIE_ENA,
HSIO_HW_CFG_PCIE_ENA),
};
static int serdes_set_mode(struct phy *phy, enum phy_mode mode)
{
struct serdes_macro *macro = phy_get_drvdata(phy);
unsigned int i;
int ret;
for (i = 0; i < ARRAY_SIZE(ocelot_serdes_muxes); i++) {
if (macro->idx != ocelot_serdes_muxes[i].idx ||
mode != ocelot_serdes_muxes[i].mode)
continue;
if (mode != PHY_MODE_QSGMII &&
macro->port != ocelot_serdes_muxes[i].port)
continue;
ret = regmap_update_bits(macro->ctrl->regs, HSIO_HW_CFG,
ocelot_serdes_muxes[i].mask,
ocelot_serdes_muxes[i].mux);
if (ret)
return ret;
if (macro->idx <= SERDES1G_MAX)
return serdes_init_s1g(macro->ctrl->regs, macro->idx);
/* SERDES6G and PCIe not supported yet */
return -EOPNOTSUPP;
}
return -EINVAL;
}
static const struct phy_ops serdes_ops = {
.set_mode = serdes_set_mode,
.owner = THIS_MODULE,
};
static struct phy *serdes_simple_xlate(struct device *dev,
struct of_phandle_args *args)
{
struct serdes_ctrl *ctrl = dev_get_drvdata(dev);
unsigned int port, idx, i;
if (args->args_count != 2)
return ERR_PTR(-EINVAL);
port = args->args[0];
idx = args->args[1];
for (i = 0; i <= SERDES_MAX; i++) {
struct serdes_macro *macro = phy_get_drvdata(ctrl->phys[i]);
if (idx != macro->idx)
continue;
/* SERDES6G(0) is the only SerDes capable of QSGMII */
if (idx != SERDES6G(0) && macro->port >= 0)
return ERR_PTR(-EBUSY);
macro->port = port;
return ctrl->phys[i];
}
return ERR_PTR(-ENODEV);
}
static int serdes_phy_create(struct serdes_ctrl *ctrl, u8 idx, struct phy **phy)
{
struct serdes_macro *macro;
*phy = devm_phy_create(ctrl->dev, NULL, &serdes_ops);
if (IS_ERR(*phy))
return PTR_ERR(*phy);
macro = devm_kzalloc(ctrl->dev, sizeof(*macro), GFP_KERNEL);
if (!macro)
return -ENOMEM;
macro->idx = idx;
macro->ctrl = ctrl;
macro->port = -1;
phy_set_drvdata(*phy, macro);
return 0;
}
static int serdes_probe(struct platform_device *pdev)
{
struct phy_provider *provider;
struct serdes_ctrl *ctrl;
unsigned int i;
int ret;
ctrl = devm_kzalloc(&pdev->dev, sizeof(*ctrl), GFP_KERNEL);
if (!ctrl)
return -ENOMEM;
ctrl->dev = &pdev->dev;
ctrl->regs = syscon_node_to_regmap(pdev->dev.parent->of_node);
if (IS_ERR(ctrl->regs))
return PTR_ERR(ctrl->regs);
for (i = 0; i <= SERDES_MAX; i++) {
ret = serdes_phy_create(ctrl, i, &ctrl->phys[i]);
if (ret)
return ret;
}
dev_set_drvdata(&pdev->dev, ctrl);
provider = devm_of_phy_provider_register(ctrl->dev,
serdes_simple_xlate);
return PTR_ERR_OR_ZERO(provider);
}
static const struct of_device_id serdes_ids[] = {
{ .compatible = "mscc,vsc7514-serdes", },
{},
};
MODULE_DEVICE_TABLE(of, serdes_ids);
static struct platform_driver mscc_ocelot_serdes = {
.probe = serdes_probe,
.driver = {
.name = "mscc,ocelot-serdes",
.of_match_table = of_match_ptr(serdes_ids),
},
};
module_platform_driver(mscc_ocelot_serdes);
MODULE_AUTHOR("Quentin Schulz <quentin.schulz@bootlin.com>");
MODULE_DESCRIPTION("SerDes driver for Microsemi Ocelot");
MODULE_LICENSE("Dual MIT/GPL");
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_543_0 |
crossvul-cpp_data_bad_5361_1 | /*-
* Copyright (c) 2003-2007 Tim Kientzle
* Copyright (c) 2008 Joerg Sonnenberger
* Copyright (c) 2011-2012 Michihiro NAKAJIMA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "archive_platform.h"
__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_mtree.c 201165 2009-12-29 05:52:13Z kientzle $");
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include <stddef.h>
/* #include <stdint.h> */ /* See archive_platform.h */
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#include "archive.h"
#include "archive_entry.h"
#include "archive_private.h"
#include "archive_read_private.h"
#include "archive_string.h"
#include "archive_pack_dev.h"
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_CLOEXEC
#define O_CLOEXEC 0
#endif
#define MTREE_HAS_DEVICE 0x0001
#define MTREE_HAS_FFLAGS 0x0002
#define MTREE_HAS_GID 0x0004
#define MTREE_HAS_GNAME 0x0008
#define MTREE_HAS_MTIME 0x0010
#define MTREE_HAS_NLINK 0x0020
#define MTREE_HAS_PERM 0x0040
#define MTREE_HAS_SIZE 0x0080
#define MTREE_HAS_TYPE 0x0100
#define MTREE_HAS_UID 0x0200
#define MTREE_HAS_UNAME 0x0400
#define MTREE_HAS_OPTIONAL 0x0800
#define MTREE_HAS_NOCHANGE 0x1000 /* FreeBSD specific */
struct mtree_option {
struct mtree_option *next;
char *value;
};
struct mtree_entry {
struct mtree_entry *next;
struct mtree_option *options;
char *name;
char full;
char used;
};
struct mtree {
struct archive_string line;
size_t buffsize;
char *buff;
int64_t offset;
int fd;
int archive_format;
const char *archive_format_name;
struct mtree_entry *entries;
struct mtree_entry *this_entry;
struct archive_string current_dir;
struct archive_string contents_name;
struct archive_entry_linkresolver *resolver;
int64_t cur_size;
char checkfs;
};
static int bid_keycmp(const char *, const char *, ssize_t);
static int cleanup(struct archive_read *);
static int detect_form(struct archive_read *, int *);
static int mtree_bid(struct archive_read *, int);
static int parse_file(struct archive_read *, struct archive_entry *,
struct mtree *, struct mtree_entry *, int *);
static void parse_escapes(char *, struct mtree_entry *);
static int parse_line(struct archive_read *, struct archive_entry *,
struct mtree *, struct mtree_entry *, int *);
static int parse_keyword(struct archive_read *, struct mtree *,
struct archive_entry *, struct mtree_option *, int *);
static int read_data(struct archive_read *a,
const void **buff, size_t *size, int64_t *offset);
static ssize_t readline(struct archive_read *, struct mtree *, char **, ssize_t);
static int skip(struct archive_read *a);
static int read_header(struct archive_read *,
struct archive_entry *);
static int64_t mtree_atol10(char **);
static int64_t mtree_atol8(char **);
static int64_t mtree_atol(char **);
/*
* There's no standard for TIME_T_MAX/TIME_T_MIN. So we compute them
* here. TODO: Move this to configure time, but be careful
* about cross-compile environments.
*/
static int64_t
get_time_t_max(void)
{
#if defined(TIME_T_MAX)
return TIME_T_MAX;
#else
/* ISO C allows time_t to be a floating-point type,
but POSIX requires an integer type. The following
should work on any system that follows the POSIX
conventions. */
if (((time_t)0) < ((time_t)-1)) {
/* Time_t is unsigned */
return (~(time_t)0);
} else {
/* Time_t is signed. */
/* Assume it's the same as int64_t or int32_t */
if (sizeof(time_t) == sizeof(int64_t)) {
return (time_t)INT64_MAX;
} else {
return (time_t)INT32_MAX;
}
}
#endif
}
static int64_t
get_time_t_min(void)
{
#if defined(TIME_T_MIN)
return TIME_T_MIN;
#else
if (((time_t)0) < ((time_t)-1)) {
/* Time_t is unsigned */
return (time_t)0;
} else {
/* Time_t is signed. */
if (sizeof(time_t) == sizeof(int64_t)) {
return (time_t)INT64_MIN;
} else {
return (time_t)INT32_MIN;
}
}
#endif
}
static int
archive_read_format_mtree_options(struct archive_read *a,
const char *key, const char *val)
{
struct mtree *mtree;
mtree = (struct mtree *)(a->format->data);
if (strcmp(key, "checkfs") == 0) {
/* Allows to read information missing from the mtree from the file system */
if (val == NULL || val[0] == 0) {
mtree->checkfs = 0;
} else {
mtree->checkfs = 1;
}
return (ARCHIVE_OK);
}
/* Note: The "warn" return is just to inform the options
* supervisor that we didn't handle it. It will generate
* a suitable error if no one used this option. */
return (ARCHIVE_WARN);
}
static void
free_options(struct mtree_option *head)
{
struct mtree_option *next;
for (; head != NULL; head = next) {
next = head->next;
free(head->value);
free(head);
}
}
int
archive_read_support_format_mtree(struct archive *_a)
{
struct archive_read *a = (struct archive_read *)_a;
struct mtree *mtree;
int r;
archive_check_magic(_a, ARCHIVE_READ_MAGIC,
ARCHIVE_STATE_NEW, "archive_read_support_format_mtree");
mtree = (struct mtree *)malloc(sizeof(*mtree));
if (mtree == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate mtree data");
return (ARCHIVE_FATAL);
}
memset(mtree, 0, sizeof(*mtree));
mtree->fd = -1;
r = __archive_read_register_format(a, mtree, "mtree",
mtree_bid, archive_read_format_mtree_options, read_header, read_data, skip, NULL, cleanup, NULL, NULL);
if (r != ARCHIVE_OK)
free(mtree);
return (ARCHIVE_OK);
}
static int
cleanup(struct archive_read *a)
{
struct mtree *mtree;
struct mtree_entry *p, *q;
mtree = (struct mtree *)(a->format->data);
p = mtree->entries;
while (p != NULL) {
q = p->next;
free(p->name);
free_options(p->options);
free(p);
p = q;
}
archive_string_free(&mtree->line);
archive_string_free(&mtree->current_dir);
archive_string_free(&mtree->contents_name);
archive_entry_linkresolver_free(mtree->resolver);
free(mtree->buff);
free(mtree);
(a->format->data) = NULL;
return (ARCHIVE_OK);
}
static ssize_t
get_line_size(const char *b, ssize_t avail, ssize_t *nlsize)
{
ssize_t len;
len = 0;
while (len < avail) {
switch (*b) {
case '\0':/* Non-ascii character or control character. */
if (nlsize != NULL)
*nlsize = 0;
return (-1);
case '\r':
if (avail-len > 1 && b[1] == '\n') {
if (nlsize != NULL)
*nlsize = 2;
return (len+2);
}
/* FALL THROUGH */
case '\n':
if (nlsize != NULL)
*nlsize = 1;
return (len+1);
default:
b++;
len++;
break;
}
}
if (nlsize != NULL)
*nlsize = 0;
return (avail);
}
static ssize_t
next_line(struct archive_read *a,
const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)
{
ssize_t len;
int quit;
quit = 0;
if (*avail == 0) {
*nl = 0;
len = 0;
} else
len = get_line_size(*b, *avail, nl);
/*
* Read bytes more while it does not reach the end of line.
*/
while (*nl == 0 && len == *avail && !quit) {
ssize_t diff = *ravail - *avail;
size_t nbytes_req = (*ravail+1023) & ~1023U;
ssize_t tested;
/* Increase reading bytes if it is not enough to at least
* new two lines. */
if (nbytes_req < (size_t)*ravail + 160)
nbytes_req <<= 1;
*b = __archive_read_ahead(a, nbytes_req, avail);
if (*b == NULL) {
if (*ravail >= *avail)
return (0);
/* Reading bytes reaches the end of file. */
*b = __archive_read_ahead(a, *avail, avail);
quit = 1;
}
*ravail = *avail;
*b += diff;
*avail -= diff;
tested = len;/* Skip some bytes we already determinated. */
len = get_line_size(*b, *avail, nl);
if (len >= 0)
len += tested;
}
return (len);
}
/*
* Compare characters with a mtree keyword.
* Returns the length of a mtree keyword if matched.
* Returns 0 if not matched.
*/
static int
bid_keycmp(const char *p, const char *key, ssize_t len)
{
int match_len = 0;
while (len > 0 && *p && *key) {
if (*p == *key) {
--len;
++p;
++key;
++match_len;
continue;
}
return (0);/* Not match */
}
if (*key != '\0')
return (0);/* Not match */
/* A following character should be specified characters */
if (p[0] == '=' || p[0] == ' ' || p[0] == '\t' ||
p[0] == '\n' || p[0] == '\r' ||
(p[0] == '\\' && (p[1] == '\n' || p[1] == '\r')))
return (match_len);
return (0);/* Not match */
}
/*
* Test whether the characters 'p' has is mtree keyword.
* Returns the length of a detected keyword.
* Returns 0 if any keywords were not found.
*/
static int
bid_keyword(const char *p, ssize_t len)
{
static const char *keys_c[] = {
"content", "contents", "cksum", NULL
};
static const char *keys_df[] = {
"device", "flags", NULL
};
static const char *keys_g[] = {
"gid", "gname", NULL
};
static const char *keys_il[] = {
"ignore", "inode", "link", NULL
};
static const char *keys_m[] = {
"md5", "md5digest", "mode", NULL
};
static const char *keys_no[] = {
"nlink", "nochange", "optional", NULL
};
static const char *keys_r[] = {
"resdevice", "rmd160", "rmd160digest", NULL
};
static const char *keys_s[] = {
"sha1", "sha1digest",
"sha256", "sha256digest",
"sha384", "sha384digest",
"sha512", "sha512digest",
"size", NULL
};
static const char *keys_t[] = {
"tags", "time", "type", NULL
};
static const char *keys_u[] = {
"uid", "uname", NULL
};
const char **keys;
int i;
switch (*p) {
case 'c': keys = keys_c; break;
case 'd': case 'f': keys = keys_df; break;
case 'g': keys = keys_g; break;
case 'i': case 'l': keys = keys_il; break;
case 'm': keys = keys_m; break;
case 'n': case 'o': keys = keys_no; break;
case 'r': keys = keys_r; break;
case 's': keys = keys_s; break;
case 't': keys = keys_t; break;
case 'u': keys = keys_u; break;
default: return (0);/* Unknown key */
}
for (i = 0; keys[i] != NULL; i++) {
int l = bid_keycmp(p, keys[i], len);
if (l > 0)
return (l);
}
return (0);/* Unknown key */
}
/*
* Test whether there is a set of mtree keywords.
* Returns the number of keyword.
* Returns -1 if we got incorrect sequence.
* This function expects a set of "<space characters>keyword=value".
* When "unset" is specified, expects a set of "<space characters>keyword".
*/
static int
bid_keyword_list(const char *p, ssize_t len, int unset, int last_is_path)
{
int l;
int keycnt = 0;
while (len > 0 && *p) {
int blank = 0;
/* Test whether there are blank characters in the line. */
while (len >0 && (*p == ' ' || *p == '\t')) {
++p;
--len;
blank = 1;
}
if (*p == '\n' || *p == '\r')
break;
if (p[0] == '\\' && (p[1] == '\n' || p[1] == '\r'))
break;
if (!blank && !last_is_path) /* No blank character. */
return (-1);
if (last_is_path && len == 0)
return (keycnt);
if (unset) {
l = bid_keycmp(p, "all", len);
if (l > 0)
return (1);
}
/* Test whether there is a correct key in the line. */
l = bid_keyword(p, len);
if (l == 0)
return (-1);/* Unknown keyword was found. */
p += l;
len -= l;
keycnt++;
/* Skip value */
if (*p == '=') {
int value = 0;
++p;
--len;
while (len > 0 && *p != ' ' && *p != '\t') {
++p;
--len;
value = 1;
}
/* A keyword should have a its value unless
* "/unset" operation. */
if (!unset && value == 0)
return (-1);
}
}
return (keycnt);
}
static int
bid_entry(const char *p, ssize_t len, ssize_t nl, int *last_is_path)
{
int f = 0;
static const unsigned char safe_char[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 00 - 0F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 1F */
/* !"$%&'()*+,-./ EXCLUSION:( )(#) */
0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 20 - 2F */
/* 0123456789:;<>? EXCLUSION:(=) */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, /* 30 - 3F */
/* @ABCDEFGHIJKLMNO */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 40 - 4F */
/* PQRSTUVWXYZ[\]^_ */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 50 - 5F */
/* `abcdefghijklmno */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 60 - 6F */
/* pqrstuvwxyz{|}~ */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, /* 70 - 7F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F0 - FF */
};
ssize_t ll;
const char *pp = p;
const char * const pp_end = pp + len;
*last_is_path = 0;
/*
* Skip the path-name which is quoted.
*/
for (;pp < pp_end; ++pp) {
if (!safe_char[*(const unsigned char *)pp]) {
if (*pp != ' ' && *pp != '\t' && *pp != '\r'
&& *pp != '\n')
f = 0;
break;
}
f = 1;
}
ll = pp_end - pp;
/* If a path-name was not found at the first, try to check
* a mtree format(a.k.a form D) ``NetBSD's mtree -D'' creates,
* which places the path-name at the last. */
if (f == 0) {
const char *pb = p + len - nl;
int name_len = 0;
int slash;
/* The form D accepts only a single line for an entry. */
if (pb-2 >= p &&
pb[-1] == '\\' && (pb[-2] == ' ' || pb[-2] == '\t'))
return (-1);
if (pb-1 >= p && pb[-1] == '\\')
return (-1);
slash = 0;
while (p <= --pb && *pb != ' ' && *pb != '\t') {
if (!safe_char[*(const unsigned char *)pb])
return (-1);
name_len++;
/* The pathname should have a slash in this
* format. */
if (*pb == '/')
slash = 1;
}
if (name_len == 0 || slash == 0)
return (-1);
/* If '/' is placed at the first in this field, this is not
* a valid filename. */
if (pb[1] == '/')
return (-1);
ll = len - nl - name_len;
pp = p;
*last_is_path = 1;
}
return (bid_keyword_list(pp, ll, 0, *last_is_path));
}
#define MAX_BID_ENTRY 3
static int
mtree_bid(struct archive_read *a, int best_bid)
{
const char *signature = "#mtree";
const char *p;
(void)best_bid; /* UNUSED */
/* Now let's look at the actual header and see if it matches. */
p = __archive_read_ahead(a, strlen(signature), NULL);
if (p == NULL)
return (-1);
if (memcmp(p, signature, strlen(signature)) == 0)
return (8 * (int)strlen(signature));
/*
* There is not a mtree signature. Let's try to detect mtree format.
*/
return (detect_form(a, NULL));
}
static int
detect_form(struct archive_read *a, int *is_form_d)
{
const char *p;
ssize_t avail, ravail;
ssize_t detected_bytes = 0, len, nl;
int entry_cnt = 0, multiline = 0;
int form_D = 0;/* The archive is generated by `NetBSD mtree -D'
* (In this source we call it `form D') . */
if (is_form_d != NULL)
*is_form_d = 0;
p = __archive_read_ahead(a, 1, &avail);
if (p == NULL)
return (-1);
ravail = avail;
for (;;) {
len = next_line(a, &p, &avail, &ravail, &nl);
/* The terminal character of the line should be
* a new line character, '\r\n' or '\n'. */
if (len <= 0 || nl == 0)
break;
if (!multiline) {
/* Leading whitespace is never significant,
* ignore it. */
while (len > 0 && (*p == ' ' || *p == '\t')) {
++p;
--avail;
--len;
}
/* Skip comment or empty line. */
if (p[0] == '#' || p[0] == '\n' || p[0] == '\r') {
p += len;
avail -= len;
continue;
}
} else {
/* A continuance line; the terminal
* character of previous line was '\' character. */
if (bid_keyword_list(p, len, 0, 0) <= 0)
break;
if (multiline == 1)
detected_bytes += len;
if (p[len-nl-1] != '\\') {
if (multiline == 1 &&
++entry_cnt >= MAX_BID_ENTRY)
break;
multiline = 0;
}
p += len;
avail -= len;
continue;
}
if (p[0] != '/') {
int last_is_path, keywords;
keywords = bid_entry(p, len, nl, &last_is_path);
if (keywords >= 0) {
detected_bytes += len;
if (form_D == 0) {
if (last_is_path)
form_D = 1;
else if (keywords > 0)
/* This line is not `form D'. */
form_D = -1;
} else if (form_D == 1) {
if (!last_is_path && keywords > 0)
/* This this is not `form D'
* and We cannot accept mixed
* format. */
break;
}
if (!last_is_path && p[len-nl-1] == '\\')
/* This line continues. */
multiline = 1;
else {
/* We've got plenty of correct lines
* to assume that this file is a mtree
* format. */
if (++entry_cnt >= MAX_BID_ENTRY)
break;
}
} else
break;
} else if (strncmp(p, "/set", 4) == 0) {
if (bid_keyword_list(p+4, len-4, 0, 0) <= 0)
break;
/* This line continues. */
if (p[len-nl-1] == '\\')
multiline = 2;
} else if (strncmp(p, "/unset", 6) == 0) {
if (bid_keyword_list(p+6, len-6, 1, 0) <= 0)
break;
/* This line continues. */
if (p[len-nl-1] == '\\')
multiline = 2;
} else
break;
/* Test next line. */
p += len;
avail -= len;
}
if (entry_cnt >= MAX_BID_ENTRY || (entry_cnt > 0 && len == 0)) {
if (is_form_d != NULL) {
if (form_D == 1)
*is_form_d = 1;
}
return (32);
}
return (0);
}
/*
* The extended mtree format permits multiple lines specifying
* attributes for each file. For those entries, only the last line
* is actually used. Practically speaking, that means we have
* to read the entire mtree file into memory up front.
*
* The parsing is done in two steps. First, it is decided if a line
* changes the global defaults and if it is, processed accordingly.
* Otherwise, the options of the line are merged with the current
* global options.
*/
static int
add_option(struct archive_read *a, struct mtree_option **global,
const char *value, size_t len)
{
struct mtree_option *opt;
if ((opt = malloc(sizeof(*opt))) == NULL) {
archive_set_error(&a->archive, errno, "Can't allocate memory");
return (ARCHIVE_FATAL);
}
if ((opt->value = malloc(len + 1)) == NULL) {
free(opt);
archive_set_error(&a->archive, errno, "Can't allocate memory");
return (ARCHIVE_FATAL);
}
memcpy(opt->value, value, len);
opt->value[len] = '\0';
opt->next = *global;
*global = opt;
return (ARCHIVE_OK);
}
static void
remove_option(struct mtree_option **global, const char *value, size_t len)
{
struct mtree_option *iter, *last;
last = NULL;
for (iter = *global; iter != NULL; last = iter, iter = iter->next) {
if (strncmp(iter->value, value, len) == 0 &&
(iter->value[len] == '\0' ||
iter->value[len] == '='))
break;
}
if (iter == NULL)
return;
if (last == NULL)
*global = iter->next;
else
last->next = iter->next;
free(iter->value);
free(iter);
}
static int
process_global_set(struct archive_read *a,
struct mtree_option **global, const char *line)
{
const char *next, *eq;
size_t len;
int r;
line += 4;
for (;;) {
next = line + strspn(line, " \t\r\n");
if (*next == '\0')
return (ARCHIVE_OK);
line = next;
next = line + strcspn(line, " \t\r\n");
eq = strchr(line, '=');
if (eq > next)
len = next - line;
else
len = eq - line;
remove_option(global, line, len);
r = add_option(a, global, line, next - line);
if (r != ARCHIVE_OK)
return (r);
line = next;
}
}
static int
process_global_unset(struct archive_read *a,
struct mtree_option **global, const char *line)
{
const char *next;
size_t len;
line += 6;
if (strchr(line, '=') != NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"/unset shall not contain `='");
return ARCHIVE_FATAL;
}
for (;;) {
next = line + strspn(line, " \t\r\n");
if (*next == '\0')
return (ARCHIVE_OK);
line = next;
len = strcspn(line, " \t\r\n");
if (len == 3 && strncmp(line, "all", 3) == 0) {
free_options(*global);
*global = NULL;
} else {
remove_option(global, line, len);
}
line += len;
}
}
static int
process_add_entry(struct archive_read *a, struct mtree *mtree,
struct mtree_option **global, const char *line, ssize_t line_len,
struct mtree_entry **last_entry, int is_form_d)
{
struct mtree_entry *entry;
struct mtree_option *iter;
const char *next, *eq, *name, *end;
size_t name_len, len;
int r, i;
if ((entry = malloc(sizeof(*entry))) == NULL) {
archive_set_error(&a->archive, errno, "Can't allocate memory");
return (ARCHIVE_FATAL);
}
entry->next = NULL;
entry->options = NULL;
entry->name = NULL;
entry->used = 0;
entry->full = 0;
/* Add this entry to list. */
if (*last_entry == NULL)
mtree->entries = entry;
else
(*last_entry)->next = entry;
*last_entry = entry;
if (is_form_d) {
/* Filename is last item on line. */
/* Adjust line_len to trim trailing whitespace */
while (line_len > 0) {
char last_character = line[line_len - 1];
if (last_character == '\r'
|| last_character == '\n'
|| last_character == '\t'
|| last_character == ' ') {
line_len--;
} else {
break;
}
}
/* Name starts after the last whitespace separator */
name = line;
for (i = 0; i < line_len; i++) {
if (line[i] == '\r'
|| line[i] == '\n'
|| line[i] == '\t'
|| line[i] == ' ') {
name = line + i + 1;
}
}
name_len = line + line_len - name;
end = name;
} else {
/* Filename is first item on line */
name_len = strcspn(line, " \t\r\n");
name = line;
line += name_len;
end = line + line_len;
}
/* name/name_len is the name within the line. */
/* line..end brackets the entire line except the name */
if ((entry->name = malloc(name_len + 1)) == NULL) {
archive_set_error(&a->archive, errno, "Can't allocate memory");
return (ARCHIVE_FATAL);
}
memcpy(entry->name, name, name_len);
entry->name[name_len] = '\0';
parse_escapes(entry->name, entry);
for (iter = *global; iter != NULL; iter = iter->next) {
r = add_option(a, &entry->options, iter->value,
strlen(iter->value));
if (r != ARCHIVE_OK)
return (r);
}
for (;;) {
next = line + strspn(line, " \t\r\n");
if (*next == '\0')
return (ARCHIVE_OK);
if (next >= end)
return (ARCHIVE_OK);
line = next;
next = line + strcspn(line, " \t\r\n");
eq = strchr(line, '=');
if (eq == NULL || eq > next)
len = next - line;
else
len = eq - line;
remove_option(&entry->options, line, len);
r = add_option(a, &entry->options, line, next - line);
if (r != ARCHIVE_OK)
return (r);
line = next;
}
}
static int
read_mtree(struct archive_read *a, struct mtree *mtree)
{
ssize_t len;
uintmax_t counter;
char *p;
struct mtree_option *global;
struct mtree_entry *last_entry;
int r, is_form_d;
mtree->archive_format = ARCHIVE_FORMAT_MTREE;
mtree->archive_format_name = "mtree";
global = NULL;
last_entry = NULL;
(void)detect_form(a, &is_form_d);
for (counter = 1; ; ++counter) {
len = readline(a, mtree, &p, 65536);
if (len == 0) {
mtree->this_entry = mtree->entries;
free_options(global);
return (ARCHIVE_OK);
}
if (len < 0) {
free_options(global);
return ((int)len);
}
/* Leading whitespace is never significant, ignore it. */
while (*p == ' ' || *p == '\t') {
++p;
--len;
}
/* Skip content lines and blank lines. */
if (*p == '#')
continue;
if (*p == '\r' || *p == '\n' || *p == '\0')
continue;
if (*p != '/') {
r = process_add_entry(a, mtree, &global, p, len,
&last_entry, is_form_d);
} else if (strncmp(p, "/set", 4) == 0) {
if (p[4] != ' ' && p[4] != '\t')
break;
r = process_global_set(a, &global, p);
} else if (strncmp(p, "/unset", 6) == 0) {
if (p[6] != ' ' && p[6] != '\t')
break;
r = process_global_unset(a, &global, p);
} else
break;
if (r != ARCHIVE_OK) {
free_options(global);
return r;
}
}
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Can't parse line %ju", counter);
free_options(global);
return (ARCHIVE_FATAL);
}
/*
* Read in the entire mtree file into memory on the first request.
* Then use the next unused file to satisfy each header request.
*/
static int
read_header(struct archive_read *a, struct archive_entry *entry)
{
struct mtree *mtree;
char *p;
int r, use_next;
mtree = (struct mtree *)(a->format->data);
if (mtree->fd >= 0) {
close(mtree->fd);
mtree->fd = -1;
}
if (mtree->entries == NULL) {
mtree->resolver = archive_entry_linkresolver_new();
if (mtree->resolver == NULL)
return ARCHIVE_FATAL;
archive_entry_linkresolver_set_strategy(mtree->resolver,
ARCHIVE_FORMAT_MTREE);
r = read_mtree(a, mtree);
if (r != ARCHIVE_OK)
return (r);
}
a->archive.archive_format = mtree->archive_format;
a->archive.archive_format_name = mtree->archive_format_name;
for (;;) {
if (mtree->this_entry == NULL)
return (ARCHIVE_EOF);
if (strcmp(mtree->this_entry->name, "..") == 0) {
mtree->this_entry->used = 1;
if (archive_strlen(&mtree->current_dir) > 0) {
/* Roll back current path. */
p = mtree->current_dir.s
+ mtree->current_dir.length - 1;
while (p >= mtree->current_dir.s && *p != '/')
--p;
if (p >= mtree->current_dir.s)
--p;
mtree->current_dir.length
= p - mtree->current_dir.s + 1;
}
}
if (!mtree->this_entry->used) {
use_next = 0;
r = parse_file(a, entry, mtree, mtree->this_entry,
&use_next);
if (use_next == 0)
return (r);
}
mtree->this_entry = mtree->this_entry->next;
}
}
/*
* A single file can have multiple lines contribute specifications.
* Parse as many lines as necessary, then pull additional information
* from a backing file on disk as necessary.
*/
static int
parse_file(struct archive_read *a, struct archive_entry *entry,
struct mtree *mtree, struct mtree_entry *mentry, int *use_next)
{
const char *path;
struct stat st_storage, *st;
struct mtree_entry *mp;
struct archive_entry *sparse_entry;
int r = ARCHIVE_OK, r1, parsed_kws;
mentry->used = 1;
/* Initialize reasonable defaults. */
archive_entry_set_filetype(entry, AE_IFREG);
archive_entry_set_size(entry, 0);
archive_string_empty(&mtree->contents_name);
/* Parse options from this line. */
parsed_kws = 0;
r = parse_line(a, entry, mtree, mentry, &parsed_kws);
if (mentry->full) {
archive_entry_copy_pathname(entry, mentry->name);
/*
* "Full" entries are allowed to have multiple lines
* and those lines aren't required to be adjacent. We
* don't support multiple lines for "relative" entries
* nor do we make any attempt to merge data from
* separate "relative" and "full" entries. (Merging
* "relative" and "full" entries would require dealing
* with pathname canonicalization, which is a very
* tricky subject.)
*/
for (mp = mentry->next; mp != NULL; mp = mp->next) {
if (mp->full && !mp->used
&& strcmp(mentry->name, mp->name) == 0) {
/* Later lines override earlier ones. */
mp->used = 1;
r1 = parse_line(a, entry, mtree, mp,
&parsed_kws);
if (r1 < r)
r = r1;
}
}
} else {
/*
* Relative entries require us to construct
* the full path and possibly update the
* current directory.
*/
size_t n = archive_strlen(&mtree->current_dir);
if (n > 0)
archive_strcat(&mtree->current_dir, "/");
archive_strcat(&mtree->current_dir, mentry->name);
archive_entry_copy_pathname(entry, mtree->current_dir.s);
if (archive_entry_filetype(entry) != AE_IFDIR)
mtree->current_dir.length = n;
}
if (mtree->checkfs) {
/*
* Try to open and stat the file to get the real size
* and other file info. It would be nice to avoid
* this here so that getting a listing of an mtree
* wouldn't require opening every referenced contents
* file. But then we wouldn't know the actual
* contents size, so I don't see a really viable way
* around this. (Also, we may want to someday pull
* other unspecified info from the contents file on
* disk.)
*/
mtree->fd = -1;
if (archive_strlen(&mtree->contents_name) > 0)
path = mtree->contents_name.s;
else
path = archive_entry_pathname(entry);
if (archive_entry_filetype(entry) == AE_IFREG ||
archive_entry_filetype(entry) == AE_IFDIR) {
mtree->fd = open(path, O_RDONLY | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(mtree->fd);
if (mtree->fd == -1 &&
(errno != ENOENT ||
archive_strlen(&mtree->contents_name) > 0)) {
archive_set_error(&a->archive, errno,
"Can't open %s", path);
r = ARCHIVE_WARN;
}
}
st = &st_storage;
if (mtree->fd >= 0) {
if (fstat(mtree->fd, st) == -1) {
archive_set_error(&a->archive, errno,
"Could not fstat %s", path);
r = ARCHIVE_WARN;
/* If we can't stat it, don't keep it open. */
close(mtree->fd);
mtree->fd = -1;
st = NULL;
}
} else if (lstat(path, st) == -1) {
st = NULL;
}
/*
* Check for a mismatch between the type in the specification
* and the type of the contents object on disk.
*/
if (st != NULL) {
if (((st->st_mode & S_IFMT) == S_IFREG &&
archive_entry_filetype(entry) == AE_IFREG)
#ifdef S_IFLNK
||((st->st_mode & S_IFMT) == S_IFLNK &&
archive_entry_filetype(entry) == AE_IFLNK)
#endif
#ifdef S_IFSOCK
||((st->st_mode & S_IFSOCK) == S_IFSOCK &&
archive_entry_filetype(entry) == AE_IFSOCK)
#endif
#ifdef S_IFCHR
||((st->st_mode & S_IFMT) == S_IFCHR &&
archive_entry_filetype(entry) == AE_IFCHR)
#endif
#ifdef S_IFBLK
||((st->st_mode & S_IFMT) == S_IFBLK &&
archive_entry_filetype(entry) == AE_IFBLK)
#endif
||((st->st_mode & S_IFMT) == S_IFDIR &&
archive_entry_filetype(entry) == AE_IFDIR)
#ifdef S_IFIFO
||((st->st_mode & S_IFMT) == S_IFIFO &&
archive_entry_filetype(entry) == AE_IFIFO)
#endif
) {
/* Types match. */
} else {
/* Types don't match; bail out gracefully. */
if (mtree->fd >= 0)
close(mtree->fd);
mtree->fd = -1;
if (parsed_kws & MTREE_HAS_OPTIONAL) {
/* It's not an error for an optional
* entry to not match disk. */
*use_next = 1;
} else if (r == ARCHIVE_OK) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"mtree specification has different"
" type for %s",
archive_entry_pathname(entry));
r = ARCHIVE_WARN;
}
return (r);
}
}
/*
* If there is a contents file on disk, pick some of the
* metadata from that file. For most of these, we only
* set it from the contents if it wasn't already parsed
* from the specification.
*/
if (st != NULL) {
if (((parsed_kws & MTREE_HAS_DEVICE) == 0 ||
(parsed_kws & MTREE_HAS_NOCHANGE) != 0) &&
(archive_entry_filetype(entry) == AE_IFCHR ||
archive_entry_filetype(entry) == AE_IFBLK))
archive_entry_set_rdev(entry, st->st_rdev);
if ((parsed_kws & (MTREE_HAS_GID | MTREE_HAS_GNAME))
== 0 ||
(parsed_kws & MTREE_HAS_NOCHANGE) != 0)
archive_entry_set_gid(entry, st->st_gid);
if ((parsed_kws & (MTREE_HAS_UID | MTREE_HAS_UNAME))
== 0 ||
(parsed_kws & MTREE_HAS_NOCHANGE) != 0)
archive_entry_set_uid(entry, st->st_uid);
if ((parsed_kws & MTREE_HAS_MTIME) == 0 ||
(parsed_kws & MTREE_HAS_NOCHANGE) != 0) {
#if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
archive_entry_set_mtime(entry, st->st_mtime,
st->st_mtimespec.tv_nsec);
#elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
archive_entry_set_mtime(entry, st->st_mtime,
st->st_mtim.tv_nsec);
#elif HAVE_STRUCT_STAT_ST_MTIME_N
archive_entry_set_mtime(entry, st->st_mtime,
st->st_mtime_n);
#elif HAVE_STRUCT_STAT_ST_UMTIME
archive_entry_set_mtime(entry, st->st_mtime,
st->st_umtime*1000);
#elif HAVE_STRUCT_STAT_ST_MTIME_USEC
archive_entry_set_mtime(entry, st->st_mtime,
st->st_mtime_usec*1000);
#else
archive_entry_set_mtime(entry, st->st_mtime, 0);
#endif
}
if ((parsed_kws & MTREE_HAS_NLINK) == 0 ||
(parsed_kws & MTREE_HAS_NOCHANGE) != 0)
archive_entry_set_nlink(entry, st->st_nlink);
if ((parsed_kws & MTREE_HAS_PERM) == 0 ||
(parsed_kws & MTREE_HAS_NOCHANGE) != 0)
archive_entry_set_perm(entry, st->st_mode);
if ((parsed_kws & MTREE_HAS_SIZE) == 0 ||
(parsed_kws & MTREE_HAS_NOCHANGE) != 0)
archive_entry_set_size(entry, st->st_size);
archive_entry_set_ino(entry, st->st_ino);
archive_entry_set_dev(entry, st->st_dev);
archive_entry_linkify(mtree->resolver, &entry,
&sparse_entry);
} else if (parsed_kws & MTREE_HAS_OPTIONAL) {
/*
* Couldn't open the entry, stat it or the on-disk type
* didn't match. If this entry is optional, just
* ignore it and read the next header entry.
*/
*use_next = 1;
return ARCHIVE_OK;
}
}
mtree->cur_size = archive_entry_size(entry);
mtree->offset = 0;
return r;
}
/*
* Each line contains a sequence of keywords.
*/
static int
parse_line(struct archive_read *a, struct archive_entry *entry,
struct mtree *mtree, struct mtree_entry *mp, int *parsed_kws)
{
struct mtree_option *iter;
int r = ARCHIVE_OK, r1;
for (iter = mp->options; iter != NULL; iter = iter->next) {
r1 = parse_keyword(a, mtree, entry, iter, parsed_kws);
if (r1 < r)
r = r1;
}
if (r == ARCHIVE_OK && (*parsed_kws & MTREE_HAS_TYPE) == 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Missing type keyword in mtree specification");
return (ARCHIVE_WARN);
}
return (r);
}
/*
* Device entries have one of the following forms:
* - raw dev_t
* - format,major,minor[,subdevice]
* When parsing succeeded, `pdev' will contain the appropriate dev_t value.
*/
/* strsep() is not in C90, but strcspn() is. */
/* Taken from http://unixpapa.com/incnote/string.html */
static char *
la_strsep(char **sp, const char *sep)
{
char *p, *s;
if (sp == NULL || *sp == NULL || **sp == '\0')
return(NULL);
s = *sp;
p = s + strcspn(s, sep);
if (*p != '\0')
*p++ = '\0';
*sp = p;
return(s);
}
static int
parse_device(dev_t *pdev, struct archive *a, char *val)
{
#define MAX_PACK_ARGS 3
unsigned long numbers[MAX_PACK_ARGS];
char *p, *dev;
int argc;
pack_t *pack;
dev_t result;
const char *error = NULL;
memset(pdev, 0, sizeof(*pdev));
if ((dev = strchr(val, ',')) != NULL) {
/*
* Device's major/minor are given in a specified format.
* Decode and pack it accordingly.
*/
*dev++ = '\0';
if ((pack = pack_find(val)) == NULL) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Unknown format `%s'", val);
return ARCHIVE_WARN;
}
argc = 0;
while ((p = la_strsep(&dev, ",")) != NULL) {
if (*p == '\0') {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Missing number");
return ARCHIVE_WARN;
}
if (argc >= MAX_PACK_ARGS) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Too many arguments");
return ARCHIVE_WARN;
}
numbers[argc++] = (unsigned long)mtree_atol(&p);
}
if (argc < 2) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Not enough arguments");
return ARCHIVE_WARN;
}
result = (*pack)(argc, numbers, &error);
if (error != NULL) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"%s", error);
return ARCHIVE_WARN;
}
} else {
/* file system raw value. */
result = (dev_t)mtree_atol(&val);
}
*pdev = result;
return ARCHIVE_OK;
#undef MAX_PACK_ARGS
}
/*
* Parse a single keyword and its value.
*/
static int
parse_keyword(struct archive_read *a, struct mtree *mtree,
struct archive_entry *entry, struct mtree_option *opt, int *parsed_kws)
{
char *val, *key;
key = opt->value;
if (*key == '\0')
return (ARCHIVE_OK);
if (strcmp(key, "nochange") == 0) {
*parsed_kws |= MTREE_HAS_NOCHANGE;
return (ARCHIVE_OK);
}
if (strcmp(key, "optional") == 0) {
*parsed_kws |= MTREE_HAS_OPTIONAL;
return (ARCHIVE_OK);
}
if (strcmp(key, "ignore") == 0) {
/*
* The mtree processing is not recursive, so
* recursion will only happen for explicitly listed
* entries.
*/
return (ARCHIVE_OK);
}
val = strchr(key, '=');
if (val == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Malformed attribute \"%s\" (%d)", key, key[0]);
return (ARCHIVE_WARN);
}
*val = '\0';
++val;
switch (key[0]) {
case 'c':
if (strcmp(key, "content") == 0
|| strcmp(key, "contents") == 0) {
parse_escapes(val, NULL);
archive_strcpy(&mtree->contents_name, val);
break;
}
if (strcmp(key, "cksum") == 0)
break;
case 'd':
if (strcmp(key, "device") == 0) {
/* stat(2) st_rdev field, e.g. the major/minor IDs
* of a char/block special file */
int r;
dev_t dev;
*parsed_kws |= MTREE_HAS_DEVICE;
r = parse_device(&dev, &a->archive, val);
if (r == ARCHIVE_OK)
archive_entry_set_rdev(entry, dev);
return r;
}
case 'f':
if (strcmp(key, "flags") == 0) {
*parsed_kws |= MTREE_HAS_FFLAGS;
archive_entry_copy_fflags_text(entry, val);
break;
}
case 'g':
if (strcmp(key, "gid") == 0) {
*parsed_kws |= MTREE_HAS_GID;
archive_entry_set_gid(entry, mtree_atol10(&val));
break;
}
if (strcmp(key, "gname") == 0) {
*parsed_kws |= MTREE_HAS_GNAME;
archive_entry_copy_gname(entry, val);
break;
}
case 'i':
if (strcmp(key, "inode") == 0) {
archive_entry_set_ino(entry, mtree_atol10(&val));
break;
}
case 'l':
if (strcmp(key, "link") == 0) {
archive_entry_copy_symlink(entry, val);
break;
}
case 'm':
if (strcmp(key, "md5") == 0 || strcmp(key, "md5digest") == 0)
break;
if (strcmp(key, "mode") == 0) {
if (val[0] >= '0' && val[0] <= '9') {
*parsed_kws |= MTREE_HAS_PERM;
archive_entry_set_perm(entry,
(mode_t)mtree_atol8(&val));
} else {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Symbolic mode \"%s\" unsupported", val);
return ARCHIVE_WARN;
}
break;
}
case 'n':
if (strcmp(key, "nlink") == 0) {
*parsed_kws |= MTREE_HAS_NLINK;
archive_entry_set_nlink(entry,
(unsigned int)mtree_atol10(&val));
break;
}
case 'r':
if (strcmp(key, "resdevice") == 0) {
/* stat(2) st_dev field, e.g. the device ID where the
* inode resides */
int r;
dev_t dev;
r = parse_device(&dev, &a->archive, val);
if (r == ARCHIVE_OK)
archive_entry_set_dev(entry, dev);
return r;
}
if (strcmp(key, "rmd160") == 0 ||
strcmp(key, "rmd160digest") == 0)
break;
case 's':
if (strcmp(key, "sha1") == 0 || strcmp(key, "sha1digest") == 0)
break;
if (strcmp(key, "sha256") == 0 ||
strcmp(key, "sha256digest") == 0)
break;
if (strcmp(key, "sha384") == 0 ||
strcmp(key, "sha384digest") == 0)
break;
if (strcmp(key, "sha512") == 0 ||
strcmp(key, "sha512digest") == 0)
break;
if (strcmp(key, "size") == 0) {
archive_entry_set_size(entry, mtree_atol10(&val));
break;
}
case 't':
if (strcmp(key, "tags") == 0) {
/*
* Comma delimited list of tags.
* Ignore the tags for now, but the interface
* should be extended to allow inclusion/exclusion.
*/
break;
}
if (strcmp(key, "time") == 0) {
int64_t m;
int64_t my_time_t_max = get_time_t_max();
int64_t my_time_t_min = get_time_t_min();
long ns = 0;
*parsed_kws |= MTREE_HAS_MTIME;
m = mtree_atol10(&val);
/* Replicate an old mtree bug:
* 123456789.1 represents 123456789
* seconds and 1 nanosecond. */
if (*val == '.') {
++val;
ns = (long)mtree_atol10(&val);
} else
ns = 0;
if (m > my_time_t_max)
m = my_time_t_max;
else if (m < my_time_t_min)
m = my_time_t_min;
archive_entry_set_mtime(entry, (time_t)m, ns);
break;
}
if (strcmp(key, "type") == 0) {
switch (val[0]) {
case 'b':
if (strcmp(val, "block") == 0) {
archive_entry_set_filetype(entry, AE_IFBLK);
break;
}
case 'c':
if (strcmp(val, "char") == 0) {
archive_entry_set_filetype(entry,
AE_IFCHR);
break;
}
case 'd':
if (strcmp(val, "dir") == 0) {
archive_entry_set_filetype(entry,
AE_IFDIR);
break;
}
case 'f':
if (strcmp(val, "fifo") == 0) {
archive_entry_set_filetype(entry,
AE_IFIFO);
break;
}
if (strcmp(val, "file") == 0) {
archive_entry_set_filetype(entry,
AE_IFREG);
break;
}
case 'l':
if (strcmp(val, "link") == 0) {
archive_entry_set_filetype(entry,
AE_IFLNK);
break;
}
default:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Unrecognized file type \"%s\"; "
"assuming \"file\"", val);
archive_entry_set_filetype(entry, AE_IFREG);
return (ARCHIVE_WARN);
}
*parsed_kws |= MTREE_HAS_TYPE;
break;
}
case 'u':
if (strcmp(key, "uid") == 0) {
*parsed_kws |= MTREE_HAS_UID;
archive_entry_set_uid(entry, mtree_atol10(&val));
break;
}
if (strcmp(key, "uname") == 0) {
*parsed_kws |= MTREE_HAS_UNAME;
archive_entry_copy_uname(entry, val);
break;
}
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Unrecognized key %s=%s", key, val);
return (ARCHIVE_WARN);
}
return (ARCHIVE_OK);
}
static int
read_data(struct archive_read *a, const void **buff, size_t *size,
int64_t *offset)
{
size_t bytes_to_read;
ssize_t bytes_read;
struct mtree *mtree;
mtree = (struct mtree *)(a->format->data);
if (mtree->fd < 0) {
*buff = NULL;
*offset = 0;
*size = 0;
return (ARCHIVE_EOF);
}
if (mtree->buff == NULL) {
mtree->buffsize = 64 * 1024;
mtree->buff = malloc(mtree->buffsize);
if (mtree->buff == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory");
return (ARCHIVE_FATAL);
}
}
*buff = mtree->buff;
*offset = mtree->offset;
if ((int64_t)mtree->buffsize > mtree->cur_size - mtree->offset)
bytes_to_read = (size_t)(mtree->cur_size - mtree->offset);
else
bytes_to_read = mtree->buffsize;
bytes_read = read(mtree->fd, mtree->buff, bytes_to_read);
if (bytes_read < 0) {
archive_set_error(&a->archive, errno, "Can't read");
return (ARCHIVE_WARN);
}
if (bytes_read == 0) {
*size = 0;
return (ARCHIVE_EOF);
}
mtree->offset += bytes_read;
*size = bytes_read;
return (ARCHIVE_OK);
}
/* Skip does nothing except possibly close the contents file. */
static int
skip(struct archive_read *a)
{
struct mtree *mtree;
mtree = (struct mtree *)(a->format->data);
if (mtree->fd >= 0) {
close(mtree->fd);
mtree->fd = -1;
}
return (ARCHIVE_OK);
}
/*
* Since parsing backslash sequences always makes strings shorter,
* we can always do this conversion in-place.
*/
static void
parse_escapes(char *src, struct mtree_entry *mentry)
{
char *dest = src;
char c;
if (mentry != NULL && strcmp(src, ".") == 0)
mentry->full = 1;
while (*src != '\0') {
c = *src++;
if (c == '/' && mentry != NULL)
mentry->full = 1;
if (c == '\\') {
switch (src[0]) {
case '0':
if (src[1] < '0' || src[1] > '7') {
c = 0;
++src;
break;
}
/* FALLTHROUGH */
case '1':
case '2':
case '3':
if (src[1] >= '0' && src[1] <= '7' &&
src[2] >= '0' && src[2] <= '7') {
c = (src[0] - '0') << 6;
c |= (src[1] - '0') << 3;
c |= (src[2] - '0');
src += 3;
}
break;
case 'a':
c = '\a';
++src;
break;
case 'b':
c = '\b';
++src;
break;
case 'f':
c = '\f';
++src;
break;
case 'n':
c = '\n';
++src;
break;
case 'r':
c = '\r';
++src;
break;
case 's':
c = ' ';
++src;
break;
case 't':
c = '\t';
++src;
break;
case 'v':
c = '\v';
++src;
break;
case '\\':
c = '\\';
++src;
break;
}
}
*dest++ = c;
}
*dest = '\0';
}
/*
* Note that this implementation does not (and should not!) obey
* locale settings; you cannot simply substitute strtol here, since
* it does obey locale.
*/
static int64_t
mtree_atol8(char **p)
{
int64_t l, limit, last_digit_limit;
int digit, base;
base = 8;
limit = INT64_MAX / base;
last_digit_limit = INT64_MAX % base;
l = 0;
digit = **p - '0';
while (digit >= 0 && digit < base) {
if (l>limit || (l == limit && digit > last_digit_limit)) {
l = INT64_MAX; /* Truncate on overflow. */
break;
}
l = (l * base) + digit;
digit = *++(*p) - '0';
}
return (l);
}
/*
* Note that this implementation does not (and should not!) obey
* locale settings; you cannot simply substitute strtol here, since
* it does obey locale.
*/
static int64_t
mtree_atol10(char **p)
{
int64_t l, limit, last_digit_limit;
int base, digit, sign;
base = 10;
if (**p == '-') {
sign = -1;
limit = ((uint64_t)(INT64_MAX) + 1) / base;
last_digit_limit = ((uint64_t)(INT64_MAX) + 1) % base;
++(*p);
} else {
sign = 1;
limit = INT64_MAX / base;
last_digit_limit = INT64_MAX % base;
}
l = 0;
digit = **p - '0';
while (digit >= 0 && digit < base) {
if (l > limit || (l == limit && digit > last_digit_limit))
return (sign < 0) ? INT64_MIN : INT64_MAX;
l = (l * base) + digit;
digit = *++(*p) - '0';
}
return (sign < 0) ? -l : l;
}
/* Parse a hex digit. */
static int
parsehex(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
else if (c >= 'a' && c <= 'f')
return c - 'a';
else if (c >= 'A' && c <= 'F')
return c - 'A';
else
return -1;
}
/*
* Note that this implementation does not (and should not!) obey
* locale settings; you cannot simply substitute strtol here, since
* it does obey locale.
*/
static int64_t
mtree_atol16(char **p)
{
int64_t l, limit, last_digit_limit;
int base, digit, sign;
base = 16;
if (**p == '-') {
sign = -1;
limit = ((uint64_t)(INT64_MAX) + 1) / base;
last_digit_limit = ((uint64_t)(INT64_MAX) + 1) % base;
++(*p);
} else {
sign = 1;
limit = INT64_MAX / base;
last_digit_limit = INT64_MAX % base;
}
l = 0;
digit = parsehex(**p);
while (digit >= 0 && digit < base) {
if (l > limit || (l == limit && digit > last_digit_limit))
return (sign < 0) ? INT64_MIN : INT64_MAX;
l = (l * base) + digit;
digit = parsehex(*++(*p));
}
return (sign < 0) ? -l : l;
}
static int64_t
mtree_atol(char **p)
{
if (**p != '0')
return mtree_atol10(p);
if ((*p)[1] == 'x' || (*p)[1] == 'X') {
*p += 2;
return mtree_atol16(p);
}
return mtree_atol8(p);
}
/*
* Returns length of line (including trailing newline)
* or negative on error. 'start' argument is updated to
* point to first character of line.
*/
static ssize_t
readline(struct archive_read *a, struct mtree *mtree, char **start,
ssize_t limit)
{
ssize_t bytes_read;
ssize_t total_size = 0;
ssize_t find_off = 0;
const void *t;
void *nl;
char *u;
/* Accumulate line in a line buffer. */
for (;;) {
/* Read some more. */
t = __archive_read_ahead(a, 1, &bytes_read);
if (t == NULL)
return (0);
if (bytes_read < 0)
return (ARCHIVE_FATAL);
nl = memchr(t, '\n', bytes_read);
/* If we found '\n', trim the read to end exactly there. */
if (nl != NULL) {
bytes_read = ((const char *)nl) - ((const char *)t) + 1;
}
if (total_size + bytes_read + 1 > limit) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Line too long");
return (ARCHIVE_FATAL);
}
if (archive_string_ensure(&mtree->line,
total_size + bytes_read + 1) == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate working buffer");
return (ARCHIVE_FATAL);
}
/* Append new bytes to string. */
memcpy(mtree->line.s + total_size, t, bytes_read);
__archive_read_consume(a, bytes_read);
total_size += bytes_read;
mtree->line.s[total_size] = '\0';
for (u = mtree->line.s + find_off; *u; ++u) {
if (u[0] == '\n') {
/* Ends with unescaped newline. */
*start = mtree->line.s;
return total_size;
} else if (u[0] == '#') {
/* Ends with comment sequence #...\n */
if (nl == NULL) {
/* But we've not found the \n yet */
break;
}
} else if (u[0] == '\\') {
if (u[1] == '\n') {
/* Trim escaped newline. */
total_size -= 2;
mtree->line.s[total_size] = '\0';
break;
} else if (u[1] != '\0') {
/* Skip the two-char escape sequence */
++u;
}
}
}
find_off = u - mtree->line.s;
}
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5361_1 |
crossvul-cpp_data_bad_800_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 "libavutil/pixdesc.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"
#include "unary.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] * (h+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 && a >= s->quarter_sample)
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_dpcm_macroblock(MpegEncContext *s, int16_t macroblock[256], int n)
{
int i, j, w, h, idx = 0;
int block_mean, rice_parameter, rice_prefix_code, rice_suffix_code,
dpcm_residual, left, top, topleft, min_left_top, max_left_top, p, p2, output;
h = 16 >> (n ? s->chroma_y_shift : 0);
w = 16 >> (n ? s->chroma_x_shift : 0);
block_mean = get_bits(&s->gb, s->avctx->bits_per_raw_sample);
if (block_mean == 0){
av_log(s->avctx, AV_LOG_ERROR, "Forbidden block_mean\n");
return AVERROR_INVALIDDATA;
}
s->last_dc[n] = block_mean * (1 << (s->dct_precision + s->intra_dc_precision));
rice_parameter = get_bits(&s->gb, 4);
if (rice_parameter == 0) {
av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_parameter\n");
return AVERROR_INVALIDDATA;
}
if (rice_parameter == 15)
rice_parameter = 0;
if (rice_parameter > 11) {
av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_parameter\n");
return AVERROR_INVALIDDATA;
}
for (i = 0; i < h; i++) {
output = 1 << (s->avctx->bits_per_raw_sample - 1);
top = 1 << (s->avctx->bits_per_raw_sample - 1);
for (j = 0; j < w; j++) {
left = output;
topleft = top;
rice_prefix_code = get_unary(&s->gb, 1, 12);
/* Escape */
if (rice_prefix_code == 11)
dpcm_residual = get_bits(&s->gb, s->avctx->bits_per_raw_sample);
else {
if (rice_prefix_code == 12) {
av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_prefix_code\n");
return AVERROR_INVALIDDATA;
}
rice_suffix_code = get_bitsz(&s->gb, rice_parameter);
dpcm_residual = (rice_prefix_code << rice_parameter) + rice_suffix_code;
}
/* Map to a signed residual */
if (dpcm_residual & 1)
dpcm_residual = (-1 * dpcm_residual) >> 1;
else
dpcm_residual = (dpcm_residual >> 1);
if (i != 0)
top = macroblock[idx-w];
p = left + top - topleft;
min_left_top = FFMIN(left, top);
if (p < min_left_top)
p = min_left_top;
max_left_top = FFMAX(left, top);
if (p > max_left_top)
p = max_left_top;
p2 = (FFMIN(min_left_top, topleft) + FFMAX(max_left_top, topleft)) >> 1;
if (p2 == p)
p2 = block_mean;
if (p2 > p)
dpcm_residual *= -1;
macroblock[idx++] = output = (dpcm_residual + p) & ((1 << s->avctx->bits_per_raw_sample) - 1);
}
}
return 0;
}
static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64])
{
int i;
s->dpcm_direction = 0;
/* 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");
s->dpcm_direction = get_bits1(&s->gb) ? -1 : 1;
for (i = 0; i < 3; i++) {
if (mpeg4_decode_dpcm_macroblock(s, (*s->dpcm_macroblock)[i], i) < 0)
return AVERROR_INVALIDDATA;
}
}
if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) {
next_start_code_studio(&s->gb);
return SLICE_END;
}
//vcon-stp9L1.bits (first frame)
if (get_bits_left(&s->gb) == 0)
return SLICE_END;
//vcon-stp2L1.bits, vcon-stp3L1.bits, vcon-stp6L1.bits, vcon-stp7L1.bits, vcon-stp8L1.bits, vcon-stp10L1.bits (first frame)
if (get_bits_left(&s->gb) < 8U && show_bits(&s->gb, get_bits_left(&s->gb)) == 0)
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->partitioned_frame = 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/bad_800_0 |
crossvul-cpp_data_bad_3946_4 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Remote Desktop Gateway (RDG)
*
* Copyright 2015 Denis Vincent <dvincent@devolutions.net>
*
* 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 <winpr/crt.h>
#include <winpr/synch.h>
#include <winpr/print.h>
#include <winpr/stream.h>
#include <winpr/winsock.h>
#include <freerdp/log.h>
#include <freerdp/error.h>
#include <freerdp/utils/ringbuffer.h>
#include "rdg.h"
#include "../proxy.h"
#include "../rdp.h"
#include "../../crypto/opensslcompat.h"
#include "rpc_fault.h"
#define TAG FREERDP_TAG("core.gateway.rdg")
/* HTTP channel response fields present flags. */
#define HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID 0x1
#define HTTP_CHANNEL_RESPONSE_OPTIONAL 0x2
#define HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT 0x4
/* HTTP extended auth. */
#define HTTP_EXTENDED_AUTH_NONE 0x0
#define HTTP_EXTENDED_AUTH_SC 0x1 /* Smart card authentication. */
#define HTTP_EXTENDED_AUTH_PAA 0x02 /* Pluggable authentication. */
#define HTTP_EXTENDED_AUTH_SSPI_NTLM 0x04 /* NTLM extended authentication. */
/* HTTP packet types. */
#define PKT_TYPE_HANDSHAKE_REQUEST 0x1
#define PKT_TYPE_HANDSHAKE_RESPONSE 0x2
#define PKT_TYPE_EXTENDED_AUTH_MSG 0x3
#define PKT_TYPE_TUNNEL_CREATE 0x4
#define PKT_TYPE_TUNNEL_RESPONSE 0x5
#define PKT_TYPE_TUNNEL_AUTH 0x6
#define PKT_TYPE_TUNNEL_AUTH_RESPONSE 0x7
#define PKT_TYPE_CHANNEL_CREATE 0x8
#define PKT_TYPE_CHANNEL_RESPONSE 0x9
#define PKT_TYPE_DATA 0xA
#define PKT_TYPE_SERVICE_MESSAGE 0xB
#define PKT_TYPE_REAUTH_MESSAGE 0xC
#define PKT_TYPE_KEEPALIVE 0xD
#define PKT_TYPE_CLOSE_CHANNEL 0x10
#define PKT_TYPE_CLOSE_CHANNEL_RESPONSE 0x11
/* HTTP tunnel auth fields present flags. */
#define HTTP_TUNNEL_AUTH_FIELD_SOH 0x1
/* HTTP tunnel auth response fields present flags. */
#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS 0x1
#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT 0x2
#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE 0x4
/* HTTP tunnel packet fields present flags. */
#define HTTP_TUNNEL_PACKET_FIELD_PAA_COOKIE 0x1
#define HTTP_TUNNEL_PACKET_FIELD_REAUTH 0x2
/* HTTP tunnel redir flags. */
#define HTTP_TUNNEL_REDIR_ENABLE_ALL 0x80000000
#define HTTP_TUNNEL_REDIR_DISABLE_ALL 0x40000000
#define HTTP_TUNNEL_REDIR_DISABLE_DRIVE 0x1
#define HTTP_TUNNEL_REDIR_DISABLE_PRINTER 0x2
#define HTTP_TUNNEL_REDIR_DISABLE_PORT 0x4
#define HTTP_TUNNEL_REDIR_DISABLE_CLIPBOARD 0x8
#define HTTP_TUNNEL_REDIR_DISABLE_PNP 0x10
/* HTTP tunnel response fields present flags. */
#define HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID 0x1
#define HTTP_TUNNEL_RESPONSE_FIELD_CAPS 0x2
#define HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ 0x4
#define HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG 0x10
/* HTTP capability type enumeration. */
#define HTTP_CAPABILITY_TYPE_QUAR_SOH 0x1
#define HTTP_CAPABILITY_IDLE_TIMEOUT 0x2
#define HTTP_CAPABILITY_MESSAGING_CONSENT_SIGN 0x4
#define HTTP_CAPABILITY_MESSAGING_SERVICE_MSG 0x8
#define HTTP_CAPABILITY_REAUTH 0x10
#define HTTP_CAPABILITY_UDP_TRANSPORT 0x20
struct rdp_rdg
{
rdpContext* context;
rdpSettings* settings;
BOOL attached;
BIO* frontBio;
rdpTls* tlsIn;
rdpTls* tlsOut;
rdpNtlm* ntlm;
HttpContext* http;
CRITICAL_SECTION writeSection;
UUID guid;
int state;
UINT16 packetRemainingCount;
UINT16 reserved1;
int timeout;
UINT16 extAuth;
UINT16 reserved2;
};
enum
{
RDG_CLIENT_STATE_INITIAL,
RDG_CLIENT_STATE_HANDSHAKE,
RDG_CLIENT_STATE_TUNNEL_CREATE,
RDG_CLIENT_STATE_TUNNEL_AUTHORIZE,
RDG_CLIENT_STATE_CHANNEL_CREATE,
RDG_CLIENT_STATE_OPENED,
};
#pragma pack(push, 1)
typedef struct rdg_packet_header
{
UINT16 type;
UINT16 reserved;
UINT32 packetLength;
} RdgPacketHeader;
#pragma pack(pop)
typedef struct
{
UINT32 code;
const char* name;
} t_err_mapping;
static const t_err_mapping tunnel_response_fields_present[] = {
{ HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID, "HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID" },
{ HTTP_TUNNEL_RESPONSE_FIELD_CAPS, "HTTP_TUNNEL_RESPONSE_FIELD_CAPS" },
{ HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ, "HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ" },
{ HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG, "HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG" }
};
static const t_err_mapping channel_response_fields_present[] = {
{ HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID, "HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID" },
{ HTTP_CHANNEL_RESPONSE_OPTIONAL, "HTTP_CHANNEL_RESPONSE_OPTIONAL" },
{ HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT, "HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT" }
};
static const t_err_mapping tunnel_authorization_response_fields_present[] = {
{ HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS, "HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS" },
{ HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT,
"HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT" },
{ HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE,
"HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE" }
};
static const t_err_mapping extended_auth[] = {
{ HTTP_EXTENDED_AUTH_NONE, "HTTP_EXTENDED_AUTH_NONE" },
{ HTTP_EXTENDED_AUTH_SC, "HTTP_EXTENDED_AUTH_SC" },
{ HTTP_EXTENDED_AUTH_PAA, "HTTP_EXTENDED_AUTH_PAA" },
{ HTTP_EXTENDED_AUTH_SSPI_NTLM, "HTTP_EXTENDED_AUTH_SSPI_NTLM" }
};
static const char* fields_present_to_string(UINT16 fieldsPresent, const t_err_mapping* map,
size_t elements)
{
size_t x = 0;
static char buffer[1024] = { 0 };
char fields[12];
memset(buffer, 0, sizeof(buffer));
for (x = 0; x < elements; x++)
{
if (buffer[0] != '\0')
strcat(buffer, "|");
if ((map[x].code & fieldsPresent) != 0)
strcat(buffer, map[x].name);
}
sprintf_s(fields, ARRAYSIZE(fields), " [%04" PRIx16 "]", fieldsPresent);
strcat(buffer, fields);
return buffer;
}
static const char* channel_response_fields_present_to_string(UINT16 fieldsPresent)
{
return fields_present_to_string(fieldsPresent, channel_response_fields_present,
ARRAYSIZE(channel_response_fields_present));
}
static const char* tunnel_response_fields_present_to_string(UINT16 fieldsPresent)
{
return fields_present_to_string(fieldsPresent, tunnel_response_fields_present,
ARRAYSIZE(tunnel_response_fields_present));
}
static const char* tunnel_authorization_response_fields_present_to_string(UINT16 fieldsPresent)
{
return fields_present_to_string(fieldsPresent, tunnel_authorization_response_fields_present,
ARRAYSIZE(tunnel_authorization_response_fields_present));
}
static const char* extended_auth_to_string(UINT16 auth)
{
if (auth == HTTP_EXTENDED_AUTH_NONE)
return "HTTP_EXTENDED_AUTH_NONE [0x0000]";
return fields_present_to_string(auth, extended_auth, ARRAYSIZE(extended_auth));
}
static BOOL rdg_write_packet(rdpRdg* rdg, wStream* sPacket)
{
size_t s;
int status;
wStream* sChunk;
char chunkSize[11];
sprintf_s(chunkSize, sizeof(chunkSize), "%" PRIXz "\r\n", Stream_Length(sPacket));
sChunk = Stream_New(NULL, strnlen(chunkSize, sizeof(chunkSize)) + Stream_Length(sPacket) + 2);
if (!sChunk)
return FALSE;
Stream_Write(sChunk, chunkSize, strnlen(chunkSize, sizeof(chunkSize)));
Stream_Write(sChunk, Stream_Buffer(sPacket), Stream_Length(sPacket));
Stream_Write(sChunk, "\r\n", 2);
Stream_SealLength(sChunk);
s = Stream_Length(sChunk);
if (s > INT_MAX)
return FALSE;
status = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);
Stream_Free(sChunk, TRUE);
if (status < 0)
return FALSE;
return TRUE;
}
static BOOL rdg_read_all(rdpTls* tls, BYTE* buffer, int size)
{
int status;
int readCount = 0;
BYTE* pBuffer = buffer;
while (readCount < size)
{
status = BIO_read(tls->bio, pBuffer, size - readCount);
if (status <= 0)
{
if (!BIO_should_retry(tls->bio))
return FALSE;
continue;
}
readCount += status;
pBuffer += status;
}
return TRUE;
}
static wStream* rdg_receive_packet(rdpRdg* rdg)
{
wStream* s;
const size_t header = sizeof(RdgPacketHeader);
size_t packetLength;
assert(header <= INT_MAX);
s = Stream_New(NULL, 1024);
if (!s)
return NULL;
if (!rdg_read_all(rdg->tlsOut, Stream_Buffer(s), header))
{
Stream_Free(s, TRUE);
return NULL;
}
Stream_Seek(s, 4);
Stream_Read_UINT32(s, packetLength);
if ((packetLength > INT_MAX) || !Stream_EnsureCapacity(s, packetLength))
{
Stream_Free(s, TRUE);
return NULL;
}
if (!rdg_read_all(rdg->tlsOut, Stream_Buffer(s) + header, (int)packetLength - (int)header))
{
Stream_Free(s, TRUE);
return NULL;
}
Stream_SetLength(s, packetLength);
return s;
}
static BOOL rdg_send_handshake(rdpRdg* rdg)
{
wStream* s;
BOOL status;
s = Stream_New(NULL, 14);
if (!s)
return FALSE;
Stream_Write_UINT16(s, PKT_TYPE_HANDSHAKE_REQUEST); /* Type (2 bytes) */
Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
Stream_Write_UINT32(s, 14); /* PacketLength (4 bytes) */
Stream_Write_UINT8(s, 1); /* VersionMajor (1 byte) */
Stream_Write_UINT8(s, 0); /* VersionMinor (1 byte) */
Stream_Write_UINT16(s, 0); /* ClientVersion (2 bytes), must be 0 */
Stream_Write_UINT16(s, rdg->extAuth); /* ExtendedAuthentication (2 bytes) */
Stream_SealLength(s);
status = rdg_write_packet(rdg, s);
Stream_Free(s, TRUE);
if (status)
{
rdg->state = RDG_CLIENT_STATE_HANDSHAKE;
}
return status;
}
static BOOL rdg_send_tunnel_request(rdpRdg* rdg)
{
wStream* s;
BOOL status;
UINT32 packetSize = 16;
UINT16 fieldsPresent = 0;
WCHAR* PAACookie = NULL;
int PAACookieLen = 0;
if (rdg->extAuth == HTTP_EXTENDED_AUTH_PAA)
{
PAACookieLen =
ConvertToUnicode(CP_UTF8, 0, rdg->settings->GatewayAccessToken, -1, &PAACookie, 0);
if (!PAACookie || (PAACookieLen < 0) || (PAACookieLen > UINT16_MAX / 2))
{
free(PAACookie);
return FALSE;
}
packetSize += 2 + (UINT32)PAACookieLen * sizeof(WCHAR);
fieldsPresent = HTTP_TUNNEL_PACKET_FIELD_PAA_COOKIE;
}
s = Stream_New(NULL, packetSize);
if (!s)
{
free(PAACookie);
return FALSE;
}
Stream_Write_UINT16(s, PKT_TYPE_TUNNEL_CREATE); /* Type (2 bytes) */
Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
Stream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */
Stream_Write_UINT32(s, HTTP_CAPABILITY_TYPE_QUAR_SOH); /* CapabilityFlags (4 bytes) */
Stream_Write_UINT16(s, fieldsPresent); /* FieldsPresent (2 bytes) */
Stream_Write_UINT16(s, 0); /* Reserved (2 bytes), must be 0 */
if (PAACookie)
{
Stream_Write_UINT16(s, (UINT16)PAACookieLen * 2); /* PAA cookie string length */
Stream_Write_UTF16_String(s, PAACookie, (size_t)PAACookieLen);
}
Stream_SealLength(s);
status = rdg_write_packet(rdg, s);
Stream_Free(s, TRUE);
free(PAACookie);
if (status)
{
rdg->state = RDG_CLIENT_STATE_TUNNEL_CREATE;
}
return status;
}
static BOOL rdg_send_tunnel_authorization(rdpRdg* rdg)
{
wStream* s;
BOOL status;
WCHAR* clientName = NULL;
UINT32 packetSize;
int clientNameLen =
ConvertToUnicode(CP_UTF8, 0, rdg->settings->ClientHostname, -1, &clientName, 0);
if (!clientName || (clientNameLen < 0) || (clientNameLen > UINT16_MAX / 2))
{
free(clientName);
return FALSE;
}
packetSize = 12 + (UINT32)clientNameLen * sizeof(WCHAR);
s = Stream_New(NULL, packetSize);
if (!s)
{
free(clientName);
return FALSE;
}
Stream_Write_UINT16(s, PKT_TYPE_TUNNEL_AUTH); /* Type (2 bytes) */
Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
Stream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */
Stream_Write_UINT16(s, 0); /* FieldsPresent (2 bytes) */
Stream_Write_UINT16(s, (UINT16)clientNameLen * 2); /* Client name string length */
Stream_Write_UTF16_String(s, clientName, (size_t)clientNameLen);
Stream_SealLength(s);
status = rdg_write_packet(rdg, s);
Stream_Free(s, TRUE);
free(clientName);
if (status)
{
rdg->state = RDG_CLIENT_STATE_TUNNEL_AUTHORIZE;
}
return status;
}
static BOOL rdg_send_channel_create(rdpRdg* rdg)
{
wStream* s = NULL;
BOOL status = FALSE;
WCHAR* serverName = NULL;
int serverNameLen =
ConvertToUnicode(CP_UTF8, 0, rdg->settings->ServerHostname, -1, &serverName, 0);
UINT32 packetSize = 16 + ((UINT32)serverNameLen) * 2;
if ((serverNameLen < 0) || (serverNameLen > UINT16_MAX / 2))
goto fail;
s = Stream_New(NULL, packetSize);
if (!s)
goto fail;
Stream_Write_UINT16(s, PKT_TYPE_CHANNEL_CREATE); /* Type (2 bytes) */
Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
Stream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */
Stream_Write_UINT8(s, 1); /* Number of resources. (1 byte) */
Stream_Write_UINT8(s, 0); /* Number of alternative resources (1 byte) */
Stream_Write_UINT16(s, (UINT16)rdg->settings->ServerPort); /* Resource port (2 bytes) */
Stream_Write_UINT16(s, 3); /* Protocol number (2 bytes) */
Stream_Write_UINT16(s, (UINT16)serverNameLen * 2);
Stream_Write_UTF16_String(s, serverName, (size_t)serverNameLen);
Stream_SealLength(s);
status = rdg_write_packet(rdg, s);
fail:
free(serverName);
Stream_Free(s, TRUE);
if (status)
rdg->state = RDG_CLIENT_STATE_CHANNEL_CREATE;
return status;
}
static BOOL rdg_set_ntlm_auth_header(rdpNtlm* ntlm, HttpRequest* request)
{
const SecBuffer* ntlmToken = ntlm_client_get_output_buffer(ntlm);
char* base64NtlmToken = NULL;
if (ntlmToken)
{
if (ntlmToken->cbBuffer > INT_MAX)
return FALSE;
base64NtlmToken = crypto_base64_encode(ntlmToken->pvBuffer, (int)ntlmToken->cbBuffer);
}
if (base64NtlmToken)
{
BOOL rc = http_request_set_auth_scheme(request, "NTLM") &&
http_request_set_auth_param(request, base64NtlmToken);
free(base64NtlmToken);
if (!rc)
return FALSE;
}
return TRUE;
}
static wStream* rdg_build_http_request(rdpRdg* rdg, const char* method,
const char* transferEncoding)
{
wStream* s = NULL;
HttpRequest* request = NULL;
const char* uri;
if (!rdg || !method)
return NULL;
uri = http_context_get_uri(rdg->http);
request = http_request_new();
if (!request)
return NULL;
if (!http_request_set_method(request, method) || !http_request_set_uri(request, uri))
goto out;
if (rdg->ntlm)
{
if (!rdg_set_ntlm_auth_header(rdg->ntlm, request))
goto out;
}
if (transferEncoding)
{
http_request_set_transfer_encoding(request, transferEncoding);
}
s = http_request_write(rdg->http, request);
out:
http_request_free(request);
if (s)
Stream_SealLength(s);
return s;
}
static BOOL rdg_handle_ntlm_challenge(rdpNtlm* ntlm, HttpResponse* response)
{
BOOL continueNeeded = FALSE;
size_t len;
const char* token64 = NULL;
int ntlmTokenLength = 0;
BYTE* ntlmTokenData = NULL;
long StatusCode;
if (!ntlm || !response)
return FALSE;
StatusCode = http_response_get_status_code(response);
if (StatusCode != HTTP_STATUS_DENIED)
{
WLog_DBG(TAG, "Unexpected NTLM challenge HTTP status: %ld", StatusCode);
return FALSE;
}
token64 = http_response_get_auth_token(response, "NTLM");
if (!token64)
return FALSE;
len = strlen(token64);
if (len > INT_MAX)
return FALSE;
crypto_base64_decode(token64, (int)len, &ntlmTokenData, &ntlmTokenLength);
if (ntlmTokenLength < 0)
{
free(ntlmTokenData);
return FALSE;
}
if (ntlmTokenData && ntlmTokenLength)
{
if (!ntlm_client_set_input_buffer(ntlm, FALSE, ntlmTokenData, (size_t)ntlmTokenLength))
return FALSE;
}
if (!ntlm_authenticate(ntlm, &continueNeeded))
return FALSE;
if (continueNeeded)
return FALSE;
return TRUE;
}
static BOOL rdg_skip_seed_payload(rdpTls* tls, SSIZE_T lastResponseLength)
{
BYTE seed_payload[10];
const size_t size = sizeof(seed_payload);
assert(size < SSIZE_MAX);
/* Per [MS-TSGU] 3.3.5.1 step 4, after final OK response RDG server sends
* random "seed" payload of limited size. In practice it's 10 bytes.
*/
if (lastResponseLength < (SSIZE_T)size)
{
if (!rdg_read_all(tls, seed_payload, size - lastResponseLength))
{
return FALSE;
}
}
return TRUE;
}
static BOOL rdg_process_handshake_response(rdpRdg* rdg, wStream* s)
{
UINT32 errorCode;
UINT16 serverVersion, extendedAuth;
BYTE verMajor, verMinor;
const char* error;
WLog_DBG(TAG, "Handshake response received");
if (rdg->state != RDG_CLIENT_STATE_HANDSHAKE)
{
return FALSE;
}
if (Stream_GetRemainingLength(s) < 10)
{
WLog_ERR(TAG, "[%s] Short packet %" PRIuz ", expected 10", __FUNCTION__,
Stream_GetRemainingLength(s));
return FALSE;
}
Stream_Read_UINT32(s, errorCode);
Stream_Read_UINT8(s, verMajor);
Stream_Read_UINT8(s, verMinor);
Stream_Read_UINT16(s, serverVersion);
Stream_Read_UINT16(s, extendedAuth);
error = rpc_error_to_string(errorCode);
WLog_DBG(TAG,
"errorCode=%s, verMajor=%" PRId8 ", verMinor=%" PRId8 ", serverVersion=%" PRId16
", extendedAuth=%s",
error, verMajor, verMinor, serverVersion, extended_auth_to_string(extendedAuth));
if (FAILED(errorCode))
{
WLog_ERR(TAG, "Handshake error %s", error);
freerdp_set_last_error_log(rdg->context, errorCode);
return FALSE;
}
return rdg_send_tunnel_request(rdg);
}
static BOOL rdg_process_tunnel_response(rdpRdg* rdg, wStream* s)
{
UINT16 serverVersion, fieldsPresent;
UINT32 errorCode;
const char* error;
WLog_DBG(TAG, "Tunnel response received");
if (rdg->state != RDG_CLIENT_STATE_TUNNEL_CREATE)
{
return FALSE;
}
if (Stream_GetRemainingLength(s) < 10)
{
WLog_ERR(TAG, "[%s] Short packet %" PRIuz ", expected 10", __FUNCTION__,
Stream_GetRemainingLength(s));
return FALSE;
}
Stream_Read_UINT16(s, serverVersion);
Stream_Read_UINT32(s, errorCode);
Stream_Read_UINT16(s, fieldsPresent);
Stream_Seek_UINT16(s); /* reserved */
error = rpc_error_to_string(errorCode);
WLog_DBG(TAG, "serverVersion=%" PRId16 ", errorCode=%s, fieldsPresent=%s", serverVersion, error,
tunnel_response_fields_present_to_string(fieldsPresent));
if (FAILED(errorCode))
{
WLog_ERR(TAG, "Tunnel creation error %s", error);
freerdp_set_last_error_log(rdg->context, errorCode);
return FALSE;
}
return rdg_send_tunnel_authorization(rdg);
}
static BOOL rdg_process_tunnel_authorization_response(rdpRdg* rdg, wStream* s)
{
UINT32 errorCode;
UINT16 fieldsPresent;
const char* error;
WLog_DBG(TAG, "Tunnel authorization received");
if (rdg->state != RDG_CLIENT_STATE_TUNNEL_AUTHORIZE)
{
return FALSE;
}
if (Stream_GetRemainingLength(s) < 8)
{
WLog_ERR(TAG, "[%s] Short packet %" PRIuz ", expected 8", __FUNCTION__,
Stream_GetRemainingLength(s));
return FALSE;
}
Stream_Read_UINT32(s, errorCode);
Stream_Read_UINT16(s, fieldsPresent);
Stream_Seek_UINT16(s); /* reserved */
error = rpc_error_to_string(errorCode);
WLog_DBG(TAG, "errorCode=%s, fieldsPresent=%s", error,
tunnel_authorization_response_fields_present_to_string(fieldsPresent));
if (FAILED(errorCode))
{
WLog_ERR(TAG, "Tunnel authorization error %s", error);
freerdp_set_last_error_log(rdg->context, errorCode);
return FALSE;
}
return rdg_send_channel_create(rdg);
}
static BOOL rdg_process_channel_response(rdpRdg* rdg, wStream* s)
{
UINT16 fieldsPresent;
UINT32 errorCode;
const char* error;
WLog_DBG(TAG, "Channel response received");
if (rdg->state != RDG_CLIENT_STATE_CHANNEL_CREATE)
{
return FALSE;
}
if (Stream_GetRemainingLength(s) < 8)
{
WLog_ERR(TAG, "[%s] Short packet %" PRIuz ", expected 8", __FUNCTION__,
Stream_GetRemainingLength(s));
return FALSE;
}
Stream_Read_UINT32(s, errorCode);
Stream_Read_UINT16(s, fieldsPresent);
Stream_Seek_UINT16(s); /* reserved */
error = rpc_error_to_string(errorCode);
WLog_DBG(TAG, "channel response errorCode=%s, fieldsPresent=%s", error,
channel_response_fields_present_to_string(fieldsPresent));
if (FAILED(errorCode))
{
WLog_ERR(TAG, "channel response errorCode=%s, fieldsPresent=%s", error,
channel_response_fields_present_to_string(fieldsPresent));
freerdp_set_last_error_log(rdg->context, errorCode);
return FALSE;
}
rdg->state = RDG_CLIENT_STATE_OPENED;
return TRUE;
}
static BOOL rdg_process_packet(rdpRdg* rdg, wStream* s)
{
BOOL status = TRUE;
UINT16 type;
UINT32 packetLength;
Stream_SetPosition(s, 0);
if (Stream_GetRemainingLength(s) < 8)
{
WLog_ERR(TAG, "[%s] Short packet %" PRIuz ", expected 8", __FUNCTION__,
Stream_GetRemainingLength(s));
return FALSE;
}
Stream_Read_UINT16(s, type);
Stream_Seek_UINT16(s); /* reserved */
Stream_Read_UINT32(s, packetLength);
if (Stream_Length(s) < packetLength)
{
WLog_ERR(TAG, "[%s] Short packet %" PRIuz ", expected %" PRIuz, __FUNCTION__,
Stream_Length(s), packetLength);
return FALSE;
}
switch (type)
{
case PKT_TYPE_HANDSHAKE_RESPONSE:
status = rdg_process_handshake_response(rdg, s);
break;
case PKT_TYPE_TUNNEL_RESPONSE:
status = rdg_process_tunnel_response(rdg, s);
break;
case PKT_TYPE_TUNNEL_AUTH_RESPONSE:
status = rdg_process_tunnel_authorization_response(rdg, s);
break;
case PKT_TYPE_CHANNEL_RESPONSE:
status = rdg_process_channel_response(rdg, s);
break;
case PKT_TYPE_DATA:
WLog_ERR(TAG, "[%s] Unexpected packet type DATA", __FUNCTION__);
return FALSE;
}
return status;
}
DWORD rdg_get_event_handles(rdpRdg* rdg, HANDLE* events, DWORD count)
{
DWORD nCount = 0;
assert(rdg != NULL);
if (rdg->tlsOut && rdg->tlsOut->bio)
{
if (events && (nCount < count))
{
BIO_get_event(rdg->tlsOut->bio, &events[nCount]);
nCount++;
}
else
return 0;
}
if (rdg->tlsIn && rdg->tlsIn->bio)
{
if (events && (nCount < count))
{
BIO_get_event(rdg->tlsIn->bio, &events[nCount]);
nCount++;
}
else
return 0;
}
return nCount;
}
static BOOL rdg_get_gateway_credentials(rdpContext* context)
{
rdpSettings* settings = context->settings;
freerdp* instance = context->instance;
if (!settings->GatewayPassword || !settings->GatewayUsername ||
!strlen(settings->GatewayPassword) || !strlen(settings->GatewayUsername))
{
if (freerdp_shall_disconnect(instance))
return FALSE;
if (!instance->GatewayAuthenticate)
{
freerdp_set_last_error_log(context, FREERDP_ERROR_CONNECT_NO_OR_MISSING_CREDENTIALS);
return FALSE;
}
else
{
BOOL proceed =
instance->GatewayAuthenticate(instance, &settings->GatewayUsername,
&settings->GatewayPassword, &settings->GatewayDomain);
if (!proceed)
{
freerdp_set_last_error_log(context,
FREERDP_ERROR_CONNECT_NO_OR_MISSING_CREDENTIALS);
return FALSE;
}
if (settings->GatewayUseSameCredentials)
{
if (settings->GatewayUsername)
{
free(settings->Username);
if (!(settings->Username = _strdup(settings->GatewayUsername)))
return FALSE;
}
if (settings->GatewayDomain)
{
free(settings->Domain);
if (!(settings->Domain = _strdup(settings->GatewayDomain)))
return FALSE;
}
if (settings->GatewayPassword)
{
free(settings->Password);
if (!(settings->Password = _strdup(settings->GatewayPassword)))
return FALSE;
}
}
}
}
return TRUE;
}
static BOOL rdg_ntlm_init(rdpRdg* rdg, rdpTls* tls)
{
BOOL continueNeeded = FALSE;
rdpContext* context = rdg->context;
rdpSettings* settings = context->settings;
rdg->ntlm = ntlm_new();
if (!rdg->ntlm)
return FALSE;
if (!rdg_get_gateway_credentials(context))
return FALSE;
if (!ntlm_client_init(rdg->ntlm, TRUE, settings->GatewayUsername, settings->GatewayDomain,
settings->GatewayPassword, tls->Bindings))
return FALSE;
if (!ntlm_client_make_spn(rdg->ntlm, _T("HTTP"), settings->GatewayHostname))
return FALSE;
if (!ntlm_authenticate(rdg->ntlm, &continueNeeded))
return FALSE;
return continueNeeded;
}
static BOOL rdg_send_http_request(rdpRdg* rdg, rdpTls* tls, const char* method,
const char* transferEncoding)
{
size_t sz;
wStream* s = NULL;
int status = -1;
s = rdg_build_http_request(rdg, method, transferEncoding);
if (!s)
return FALSE;
sz = Stream_Length(s);
if (sz <= INT_MAX)
status = tls_write_all(tls, Stream_Buffer(s), (int)sz);
Stream_Free(s, TRUE);
return (status >= 0);
}
static BOOL rdg_tls_connect(rdpRdg* rdg, rdpTls* tls, const char* peerAddress, int timeout)
{
int sockfd = 0;
long status = 0;
BIO* socketBio = NULL;
BIO* bufferedBio = NULL;
rdpSettings* settings = rdg->settings;
const char* peerHostname = settings->GatewayHostname;
UINT16 peerPort = (UINT16)settings->GatewayPort;
const char *proxyUsername, *proxyPassword;
BOOL isProxyConnection =
proxy_prepare(settings, &peerHostname, &peerPort, &proxyUsername, &proxyPassword);
if (settings->GatewayPort > UINT16_MAX)
return FALSE;
sockfd = freerdp_tcp_connect(rdg->context, settings, peerAddress ? peerAddress : peerHostname,
peerPort, timeout);
if (sockfd < 0)
{
return FALSE;
}
socketBio = BIO_new(BIO_s_simple_socket());
if (!socketBio)
{
closesocket((SOCKET)sockfd);
return FALSE;
}
BIO_set_fd(socketBio, sockfd, BIO_CLOSE);
bufferedBio = BIO_new(BIO_s_buffered_socket());
if (!bufferedBio)
{
BIO_free_all(socketBio);
return FALSE;
}
bufferedBio = BIO_push(bufferedBio, socketBio);
status = BIO_set_nonblock(bufferedBio, TRUE);
if (isProxyConnection)
{
if (!proxy_connect(settings, bufferedBio, proxyUsername, proxyPassword,
settings->GatewayHostname, (UINT16)settings->GatewayPort))
{
BIO_free_all(bufferedBio);
return FALSE;
}
}
if (!status)
{
BIO_free_all(bufferedBio);
return FALSE;
}
tls->hostname = settings->GatewayHostname;
tls->port = (int)settings->GatewayPort;
tls->isGatewayTransport = TRUE;
status = tls_connect(tls, bufferedBio);
if (status < 1)
{
rdpContext* context = rdg->context;
if (status < 0)
{
freerdp_set_last_error_if_not(context, FREERDP_ERROR_TLS_CONNECT_FAILED);
}
else
{
freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_CANCELLED);
}
return FALSE;
}
return (status >= 1);
}
static BOOL rdg_establish_data_connection(rdpRdg* rdg, rdpTls* tls, const char* method,
const char* peerAddress, int timeout, BOOL* rpcFallback)
{
HttpResponse* response = NULL;
long statusCode;
SSIZE_T bodyLength;
long StatusCode;
if (!rdg_tls_connect(rdg, tls, peerAddress, timeout))
return FALSE;
if (rdg->extAuth == HTTP_EXTENDED_AUTH_NONE)
{
if (!rdg_ntlm_init(rdg, tls))
return FALSE;
if (!rdg_send_http_request(rdg, tls, method, NULL))
return FALSE;
response = http_response_recv(tls, TRUE);
if (!response)
return FALSE;
StatusCode = http_response_get_status_code(response);
switch (StatusCode)
{
case HTTP_STATUS_NOT_FOUND:
{
WLog_INFO(TAG, "RD Gateway does not support HTTP transport.");
if (rpcFallback)
*rpcFallback = TRUE;
http_response_free(response);
return FALSE;
}
default:
break;
}
if (!rdg_handle_ntlm_challenge(rdg->ntlm, response))
{
http_response_free(response);
return FALSE;
}
http_response_free(response);
}
if (!rdg_send_http_request(rdg, tls, method, NULL))
return FALSE;
ntlm_free(rdg->ntlm);
rdg->ntlm = NULL;
response = http_response_recv(tls, TRUE);
if (!response)
return FALSE;
statusCode = http_response_get_status_code(response);
bodyLength = http_response_get_body_length(response);
http_response_free(response);
WLog_DBG(TAG, "%s authorization result: %d", method, statusCode);
switch (statusCode)
{
case HTTP_STATUS_OK:
break;
case HTTP_STATUS_DENIED:
freerdp_set_last_error_log(rdg->context, FREERDP_ERROR_CONNECT_ACCESS_DENIED);
return FALSE;
default:
return FALSE;
}
if (strcmp(method, "RDG_OUT_DATA") == 0)
{
if (!rdg_skip_seed_payload(tls, bodyLength))
return FALSE;
}
else
{
if (!rdg_send_http_request(rdg, tls, method, "chunked"))
return FALSE;
}
return TRUE;
}
static BOOL rdg_tunnel_connect(rdpRdg* rdg)
{
BOOL status;
wStream* s;
rdg_send_handshake(rdg);
while (rdg->state < RDG_CLIENT_STATE_OPENED)
{
status = FALSE;
s = rdg_receive_packet(rdg);
if (s)
{
status = rdg_process_packet(rdg, s);
Stream_Free(s, TRUE);
}
if (!status)
{
rdg->context->rdp->transport->layer = TRANSPORT_LAYER_CLOSED;
return FALSE;
}
}
return TRUE;
}
BOOL rdg_connect(rdpRdg* rdg, int timeout, BOOL* rpcFallback)
{
BOOL status;
SOCKET outConnSocket = 0;
char* peerAddress = NULL;
assert(rdg != NULL);
status =
rdg_establish_data_connection(rdg, rdg->tlsOut, "RDG_OUT_DATA", NULL, timeout, rpcFallback);
if (status)
{
/* Establish IN connection with the same peer/server as OUT connection,
* even when server hostname resolves to different IP addresses.
*/
BIO_get_socket(rdg->tlsOut->underlying, &outConnSocket);
peerAddress = freerdp_tcp_get_peer_address(outConnSocket);
status = rdg_establish_data_connection(rdg, rdg->tlsIn, "RDG_IN_DATA", peerAddress, timeout,
NULL);
free(peerAddress);
}
if (!status)
{
rdg->context->rdp->transport->layer = TRANSPORT_LAYER_CLOSED;
return FALSE;
}
status = rdg_tunnel_connect(rdg);
if (!status)
return FALSE;
return TRUE;
}
static int rdg_write_data_packet(rdpRdg* rdg, const BYTE* buf, int isize)
{
int status;
size_t s;
wStream* sChunk;
size_t size = (size_t)isize;
size_t packetSize = size + 10;
char chunkSize[11];
if ((isize < 0) || (isize > UINT16_MAX))
return -1;
if (size < 1)
return 0;
sprintf_s(chunkSize, sizeof(chunkSize), "%" PRIxz "\r\n", packetSize);
sChunk = Stream_New(NULL, strnlen(chunkSize, sizeof(chunkSize)) + packetSize + 2);
if (!sChunk)
return -1;
Stream_Write(sChunk, chunkSize, strnlen(chunkSize, sizeof(chunkSize)));
Stream_Write_UINT16(sChunk, PKT_TYPE_DATA); /* Type */
Stream_Write_UINT16(sChunk, 0); /* Reserved */
Stream_Write_UINT32(sChunk, (UINT32)packetSize); /* Packet length */
Stream_Write_UINT16(sChunk, (UINT16)size); /* Data size */
Stream_Write(sChunk, buf, size); /* Data */
Stream_Write(sChunk, "\r\n", 2);
Stream_SealLength(sChunk);
s = Stream_Length(sChunk);
if (s > INT_MAX)
return -1;
status = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);
Stream_Free(sChunk, TRUE);
if (status < 0)
return -1;
return (int)size;
}
static BOOL rdg_process_close_packet(rdpRdg* rdg)
{
int status = -1;
size_t s;
wStream* sChunk;
UINT32 packetSize = 12;
char chunkSize[11];
int chunkLen = sprintf_s(chunkSize, sizeof(chunkSize), "%" PRIx32 "\r\n", packetSize);
if (chunkLen < 0)
return FALSE;
sChunk = Stream_New(NULL, (size_t)chunkLen + packetSize + 2);
if (!sChunk)
return FALSE;
Stream_Write(sChunk, chunkSize, (size_t)chunkLen);
Stream_Write_UINT16(sChunk, PKT_TYPE_CLOSE_CHANNEL_RESPONSE); /* Type */
Stream_Write_UINT16(sChunk, 0); /* Reserved */
Stream_Write_UINT32(sChunk, packetSize); /* Packet length */
Stream_Write_UINT32(sChunk, 0); /* Status code */
Stream_Write(sChunk, "\r\n", 2);
Stream_SealLength(sChunk);
s = Stream_Length(sChunk);
if (s <= INT_MAX)
status = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);
Stream_Free(sChunk, TRUE);
return (status < 0 ? FALSE : TRUE);
}
static BOOL rdg_process_keep_alive_packet(rdpRdg* rdg)
{
int status = -1;
size_t s;
wStream* sChunk;
size_t packetSize = 8;
char chunkSize[11];
int chunkLen = sprintf_s(chunkSize, sizeof(chunkSize), "%" PRIxz "\r\n", packetSize);
if ((chunkLen < 0) || (packetSize > UINT32_MAX))
return FALSE;
sChunk = Stream_New(NULL, (size_t)chunkLen + packetSize + 2);
if (!sChunk)
return FALSE;
Stream_Write(sChunk, chunkSize, (size_t)chunkLen);
Stream_Write_UINT16(sChunk, PKT_TYPE_KEEPALIVE); /* Type */
Stream_Write_UINT16(sChunk, 0); /* Reserved */
Stream_Write_UINT32(sChunk, (UINT32)packetSize); /* Packet length */
Stream_Write(sChunk, "\r\n", 2);
Stream_SealLength(sChunk);
s = Stream_Length(sChunk);
if (s <= INT_MAX)
status = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);
Stream_Free(sChunk, TRUE);
return (status < 0 ? FALSE : TRUE);
}
static BOOL rdg_process_unknown_packet(rdpRdg* rdg, int type)
{
WINPR_UNUSED(rdg);
WINPR_UNUSED(type);
WLog_WARN(TAG, "Unknown Control Packet received: %X", type);
return TRUE;
}
static BOOL rdg_process_control_packet(rdpRdg* rdg, int type, size_t packetLength)
{
wStream* s = NULL;
size_t readCount = 0;
int status;
size_t payloadSize = packetLength - sizeof(RdgPacketHeader);
if (packetLength < sizeof(RdgPacketHeader))
return FALSE;
assert(sizeof(RdgPacketHeader) < INT_MAX);
if (payloadSize)
{
s = Stream_New(NULL, payloadSize);
if (!s)
return FALSE;
while (readCount < payloadSize)
{
status =
BIO_read(rdg->tlsOut->bio, Stream_Pointer(s), (int)payloadSize - (int)readCount);
if (status <= 0)
{
if (!BIO_should_retry(rdg->tlsOut->bio))
{
Stream_Free(s, TRUE);
return FALSE;
}
continue;
}
Stream_Seek(s, (size_t)status);
readCount += (size_t)status;
if (readCount > INT_MAX)
{
Stream_Free(s, TRUE);
return FALSE;
}
}
}
switch (type)
{
case PKT_TYPE_CLOSE_CHANNEL:
EnterCriticalSection(&rdg->writeSection);
status = rdg_process_close_packet(rdg);
LeaveCriticalSection(&rdg->writeSection);
break;
case PKT_TYPE_KEEPALIVE:
EnterCriticalSection(&rdg->writeSection);
status = rdg_process_keep_alive_packet(rdg);
LeaveCriticalSection(&rdg->writeSection);
break;
default:
status = rdg_process_unknown_packet(rdg, type);
break;
}
Stream_Free(s, TRUE);
return status;
}
static int rdg_read_data_packet(rdpRdg* rdg, BYTE* buffer, int size)
{
RdgPacketHeader header;
size_t readCount = 0;
int readSize;
int status;
if (!rdg->packetRemainingCount)
{
assert(sizeof(RdgPacketHeader) < INT_MAX);
while (readCount < sizeof(RdgPacketHeader))
{
status = BIO_read(rdg->tlsOut->bio, (BYTE*)(&header) + readCount,
(int)sizeof(RdgPacketHeader) - (int)readCount);
if (status <= 0)
{
if (!BIO_should_retry(rdg->tlsOut->bio))
return -1;
if (!readCount)
return 0;
BIO_wait_read(rdg->tlsOut->bio, 50);
continue;
}
readCount += (size_t)status;
if (readCount > INT_MAX)
return -1;
}
if (header.type != PKT_TYPE_DATA)
{
status = rdg_process_control_packet(rdg, header.type, header.packetLength);
if (!status)
return -1;
return 0;
}
readCount = 0;
while (readCount < 2)
{
status = BIO_read(rdg->tlsOut->bio, (BYTE*)(&rdg->packetRemainingCount) + readCount,
2 - (int)readCount);
if (status < 0)
{
if (!BIO_should_retry(rdg->tlsOut->bio))
return -1;
BIO_wait_read(rdg->tlsOut->bio, 50);
continue;
}
readCount += (size_t)status;
}
}
readSize = (rdg->packetRemainingCount < size ? rdg->packetRemainingCount : size);
status = BIO_read(rdg->tlsOut->bio, buffer, readSize);
if (status <= 0)
{
if (!BIO_should_retry(rdg->tlsOut->bio))
{
return -1;
}
return 0;
}
rdg->packetRemainingCount -= status;
return status;
}
static int rdg_bio_write(BIO* bio, const char* buf, int num)
{
int status;
rdpRdg* rdg = (rdpRdg*)BIO_get_data(bio);
BIO_clear_flags(bio, BIO_FLAGS_WRITE);
EnterCriticalSection(&rdg->writeSection);
status = rdg_write_data_packet(rdg, (const BYTE*)buf, num);
LeaveCriticalSection(&rdg->writeSection);
if (status < 0)
{
BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
return -1;
}
else if (status < num)
{
BIO_set_flags(bio, BIO_FLAGS_WRITE);
WSASetLastError(WSAEWOULDBLOCK);
}
else
{
BIO_set_flags(bio, BIO_FLAGS_WRITE);
}
return status;
}
static int rdg_bio_read(BIO* bio, char* buf, int size)
{
int status;
rdpRdg* rdg = (rdpRdg*)BIO_get_data(bio);
status = rdg_read_data_packet(rdg, (BYTE*)buf, size);
if (status < 0)
{
BIO_clear_retry_flags(bio);
return -1;
}
else if (status == 0)
{
BIO_set_retry_read(bio);
WSASetLastError(WSAEWOULDBLOCK);
return -1;
}
else
{
BIO_set_flags(bio, BIO_FLAGS_READ);
}
return status;
}
static int rdg_bio_puts(BIO* bio, const char* str)
{
WINPR_UNUSED(bio);
WINPR_UNUSED(str);
return -2;
}
static int rdg_bio_gets(BIO* bio, char* str, int size)
{
WINPR_UNUSED(bio);
WINPR_UNUSED(str);
WINPR_UNUSED(size);
return -2;
}
static long rdg_bio_ctrl(BIO* bio, int cmd, long arg1, void* arg2)
{
long status = -1;
rdpRdg* rdg = (rdpRdg*)BIO_get_data(bio);
rdpTls* tlsOut = rdg->tlsOut;
rdpTls* tlsIn = rdg->tlsIn;
if (cmd == BIO_CTRL_FLUSH)
{
(void)BIO_flush(tlsOut->bio);
(void)BIO_flush(tlsIn->bio);
status = 1;
}
else if (cmd == BIO_C_SET_NONBLOCK)
{
status = 1;
}
else if (cmd == BIO_C_READ_BLOCKED)
{
BIO* bio = tlsOut->bio;
status = BIO_read_blocked(bio);
}
else if (cmd == BIO_C_WRITE_BLOCKED)
{
BIO* bio = tlsIn->bio;
status = BIO_write_blocked(bio);
}
else if (cmd == BIO_C_WAIT_READ)
{
int timeout = (int)arg1;
BIO* bio = tlsOut->bio;
if (BIO_read_blocked(bio))
return BIO_wait_read(bio, timeout);
else if (BIO_write_blocked(bio))
return BIO_wait_write(bio, timeout);
else
status = 1;
}
else if (cmd == BIO_C_WAIT_WRITE)
{
int timeout = (int)arg1;
BIO* bio = tlsIn->bio;
if (BIO_write_blocked(bio))
status = BIO_wait_write(bio, timeout);
else if (BIO_read_blocked(bio))
status = BIO_wait_read(bio, timeout);
else
status = 1;
}
else if (cmd == BIO_C_GET_EVENT || cmd == BIO_C_GET_FD)
{
/*
* A note about BIO_C_GET_FD:
* Even if two FDs are part of RDG, only one FD can be returned here.
*
* In FreeRDP, BIO FDs are only used for polling, so it is safe to use the outgoing FD only
*
* See issue #3602
*/
status = BIO_ctrl(tlsOut->bio, cmd, arg1, arg2);
}
return status;
}
static int rdg_bio_new(BIO* bio)
{
BIO_set_init(bio, 1);
BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
return 1;
}
static int rdg_bio_free(BIO* bio)
{
WINPR_UNUSED(bio);
return 1;
}
static BIO_METHOD* BIO_s_rdg(void)
{
static BIO_METHOD* bio_methods = NULL;
if (bio_methods == NULL)
{
if (!(bio_methods = BIO_meth_new(BIO_TYPE_TSG, "RDGateway")))
return NULL;
BIO_meth_set_write(bio_methods, rdg_bio_write);
BIO_meth_set_read(bio_methods, rdg_bio_read);
BIO_meth_set_puts(bio_methods, rdg_bio_puts);
BIO_meth_set_gets(bio_methods, rdg_bio_gets);
BIO_meth_set_ctrl(bio_methods, rdg_bio_ctrl);
BIO_meth_set_create(bio_methods, rdg_bio_new);
BIO_meth_set_destroy(bio_methods, rdg_bio_free);
}
return bio_methods;
}
rdpRdg* rdg_new(rdpContext* context)
{
rdpRdg* rdg;
RPC_CSTR stringUuid;
char bracedUuid[40];
RPC_STATUS rpcStatus;
if (!context)
return NULL;
rdg = (rdpRdg*)calloc(1, sizeof(rdpRdg));
if (rdg)
{
rdg->state = RDG_CLIENT_STATE_INITIAL;
rdg->context = context;
rdg->settings = rdg->context->settings;
rdg->extAuth = HTTP_EXTENDED_AUTH_NONE;
if (rdg->settings->GatewayAccessToken)
rdg->extAuth = HTTP_EXTENDED_AUTH_PAA;
UuidCreate(&rdg->guid);
rpcStatus = UuidToStringA(&rdg->guid, &stringUuid);
if (rpcStatus == RPC_S_OUT_OF_MEMORY)
goto rdg_alloc_error;
sprintf_s(bracedUuid, sizeof(bracedUuid), "{%s}", stringUuid);
RpcStringFreeA(&stringUuid);
rdg->tlsOut = tls_new(rdg->settings);
if (!rdg->tlsOut)
goto rdg_alloc_error;
rdg->tlsIn = tls_new(rdg->settings);
if (!rdg->tlsIn)
goto rdg_alloc_error;
rdg->http = http_context_new();
if (!rdg->http)
goto rdg_alloc_error;
if (!http_context_set_uri(rdg->http, "/remoteDesktopGateway/") ||
!http_context_set_accept(rdg->http, "*/*") ||
!http_context_set_cache_control(rdg->http, "no-cache") ||
!http_context_set_pragma(rdg->http, "no-cache") ||
!http_context_set_connection(rdg->http, "Keep-Alive") ||
!http_context_set_user_agent(rdg->http, "MS-RDGateway/1.0") ||
!http_context_set_host(rdg->http, rdg->settings->GatewayHostname) ||
!http_context_set_rdg_connection_id(rdg->http, bracedUuid))
{
goto rdg_alloc_error;
}
if (rdg->extAuth != HTTP_EXTENDED_AUTH_NONE)
{
switch (rdg->extAuth)
{
case HTTP_EXTENDED_AUTH_PAA:
if (!http_context_set_rdg_auth_scheme(rdg->http, "PAA"))
goto rdg_alloc_error;
break;
default:
WLog_DBG(TAG, "RDG extended authentication method %d not supported",
rdg->extAuth);
}
}
rdg->frontBio = BIO_new(BIO_s_rdg());
if (!rdg->frontBio)
goto rdg_alloc_error;
BIO_set_data(rdg->frontBio, rdg);
InitializeCriticalSection(&rdg->writeSection);
}
return rdg;
rdg_alloc_error:
rdg_free(rdg);
return NULL;
}
void rdg_free(rdpRdg* rdg)
{
if (!rdg)
return;
tls_free(rdg->tlsOut);
tls_free(rdg->tlsIn);
http_context_free(rdg->http);
ntlm_free(rdg->ntlm);
if (!rdg->attached)
BIO_free_all(rdg->frontBio);
DeleteCriticalSection(&rdg->writeSection);
free(rdg);
}
BIO* rdg_get_front_bio_and_take_ownership(rdpRdg* rdg)
{
if (!rdg)
return NULL;
rdg->attached = TRUE;
return rdg->frontBio;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3946_4 |
crossvul-cpp_data_bad_2725_0 | /*
* Copyright: (c) 2000 United States Government as represented by the
* Secretary of the Navy. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. The names of the authors may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: AFS RX printer */
/*
* This code unmangles RX packets. RX is the mutant form of RPC that AFS
* uses to communicate between clients and servers.
*
* In this code, I mainly concern myself with decoding the AFS calls, not
* with the guts of RX, per se.
*
* Bah. If I never look at rx_packet.h again, it will be too soon.
*
* Ken Hornstein <kenh@cmf.nrl.navy.mil>
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip.h"
#define FS_RX_PORT 7000
#define CB_RX_PORT 7001
#define PROT_RX_PORT 7002
#define VLDB_RX_PORT 7003
#define KAUTH_RX_PORT 7004
#define VOL_RX_PORT 7005
#define ERROR_RX_PORT 7006 /* Doesn't seem to be used */
#define BOS_RX_PORT 7007
#define AFSNAMEMAX 256
#define AFSOPAQUEMAX 1024
#define PRNAMEMAX 64
#define VLNAMEMAX 65
#define KANAMEMAX 64
#define BOSNAMEMAX 256
#define PRSFS_READ 1 /* Read files */
#define PRSFS_WRITE 2 /* Write files */
#define PRSFS_INSERT 4 /* Insert files into a directory */
#define PRSFS_LOOKUP 8 /* Lookup files into a directory */
#define PRSFS_DELETE 16 /* Delete files */
#define PRSFS_LOCK 32 /* Lock files */
#define PRSFS_ADMINISTER 64 /* Change ACL's */
struct rx_header {
uint32_t epoch;
uint32_t cid;
uint32_t callNumber;
uint32_t seq;
uint32_t serial;
uint8_t type;
#define RX_PACKET_TYPE_DATA 1
#define RX_PACKET_TYPE_ACK 2
#define RX_PACKET_TYPE_BUSY 3
#define RX_PACKET_TYPE_ABORT 4
#define RX_PACKET_TYPE_ACKALL 5
#define RX_PACKET_TYPE_CHALLENGE 6
#define RX_PACKET_TYPE_RESPONSE 7
#define RX_PACKET_TYPE_DEBUG 8
#define RX_PACKET_TYPE_PARAMS 9
#define RX_PACKET_TYPE_VERSION 13
uint8_t flags;
#define RX_CLIENT_INITIATED 1
#define RX_REQUEST_ACK 2
#define RX_LAST_PACKET 4
#define RX_MORE_PACKETS 8
#define RX_FREE_PACKET 16
#define RX_SLOW_START_OK 32
#define RX_JUMBO_PACKET 32
uint8_t userStatus;
uint8_t securityIndex;
uint16_t spare; /* How clever: even though the AFS */
uint16_t serviceId; /* header files indicate that the */
}; /* serviceId is first, it's really */
/* encoded _after_ the spare field */
/* I wasted a day figuring that out! */
#define NUM_RX_FLAGS 7
#define RX_MAXACKS 255
struct rx_ackPacket {
uint16_t bufferSpace; /* Number of packet buffers available */
uint16_t maxSkew; /* Max diff between ack'd packet and */
/* highest packet received */
uint32_t firstPacket; /* The first packet in ack list */
uint32_t previousPacket; /* Previous packet recv'd (obsolete) */
uint32_t serial; /* # of packet that prompted the ack */
uint8_t reason; /* Reason for acknowledgement */
uint8_t nAcks; /* Number of acknowledgements */
uint8_t acks[RX_MAXACKS]; /* Up to RX_MAXACKS acknowledgements */
};
/*
* Values for the acks array
*/
#define RX_ACK_TYPE_NACK 0 /* Don't have this packet */
#define RX_ACK_TYPE_ACK 1 /* I have this packet */
static const struct tok rx_types[] = {
{ RX_PACKET_TYPE_DATA, "data" },
{ RX_PACKET_TYPE_ACK, "ack" },
{ RX_PACKET_TYPE_BUSY, "busy" },
{ RX_PACKET_TYPE_ABORT, "abort" },
{ RX_PACKET_TYPE_ACKALL, "ackall" },
{ RX_PACKET_TYPE_CHALLENGE, "challenge" },
{ RX_PACKET_TYPE_RESPONSE, "response" },
{ RX_PACKET_TYPE_DEBUG, "debug" },
{ RX_PACKET_TYPE_PARAMS, "params" },
{ RX_PACKET_TYPE_VERSION, "version" },
{ 0, NULL },
};
static const struct double_tok {
int flag; /* Rx flag */
int packetType; /* Packet type */
const char *s; /* Flag string */
} rx_flags[] = {
{ RX_CLIENT_INITIATED, 0, "client-init" },
{ RX_REQUEST_ACK, 0, "req-ack" },
{ RX_LAST_PACKET, 0, "last-pckt" },
{ RX_MORE_PACKETS, 0, "more-pckts" },
{ RX_FREE_PACKET, 0, "free-pckt" },
{ RX_SLOW_START_OK, RX_PACKET_TYPE_ACK, "slow-start" },
{ RX_JUMBO_PACKET, RX_PACKET_TYPE_DATA, "jumbogram" }
};
static const struct tok fs_req[] = {
{ 130, "fetch-data" },
{ 131, "fetch-acl" },
{ 132, "fetch-status" },
{ 133, "store-data" },
{ 134, "store-acl" },
{ 135, "store-status" },
{ 136, "remove-file" },
{ 137, "create-file" },
{ 138, "rename" },
{ 139, "symlink" },
{ 140, "link" },
{ 141, "makedir" },
{ 142, "rmdir" },
{ 143, "oldsetlock" },
{ 144, "oldextlock" },
{ 145, "oldrellock" },
{ 146, "get-stats" },
{ 147, "give-cbs" },
{ 148, "get-vlinfo" },
{ 149, "get-vlstats" },
{ 150, "set-vlstats" },
{ 151, "get-rootvl" },
{ 152, "check-token" },
{ 153, "get-time" },
{ 154, "nget-vlinfo" },
{ 155, "bulk-stat" },
{ 156, "setlock" },
{ 157, "extlock" },
{ 158, "rellock" },
{ 159, "xstat-ver" },
{ 160, "get-xstat" },
{ 161, "dfs-lookup" },
{ 162, "dfs-flushcps" },
{ 163, "dfs-symlink" },
{ 220, "residency" },
{ 65536, "inline-bulk-status" },
{ 65537, "fetch-data-64" },
{ 65538, "store-data-64" },
{ 65539, "give-up-all-cbs" },
{ 65540, "get-caps" },
{ 65541, "cb-rx-conn-addr" },
{ 0, NULL },
};
static const struct tok cb_req[] = {
{ 204, "callback" },
{ 205, "initcb" },
{ 206, "probe" },
{ 207, "getlock" },
{ 208, "getce" },
{ 209, "xstatver" },
{ 210, "getxstat" },
{ 211, "initcb2" },
{ 212, "whoareyou" },
{ 213, "initcb3" },
{ 214, "probeuuid" },
{ 215, "getsrvprefs" },
{ 216, "getcellservdb" },
{ 217, "getlocalcell" },
{ 218, "getcacheconf" },
{ 65536, "getce64" },
{ 65537, "getcellbynum" },
{ 65538, "tellmeaboutyourself" },
{ 0, NULL },
};
static const struct tok pt_req[] = {
{ 500, "new-user" },
{ 501, "where-is-it" },
{ 502, "dump-entry" },
{ 503, "add-to-group" },
{ 504, "name-to-id" },
{ 505, "id-to-name" },
{ 506, "delete" },
{ 507, "remove-from-group" },
{ 508, "get-cps" },
{ 509, "new-entry" },
{ 510, "list-max" },
{ 511, "set-max" },
{ 512, "list-entry" },
{ 513, "change-entry" },
{ 514, "list-elements" },
{ 515, "same-mbr-of" },
{ 516, "set-fld-sentry" },
{ 517, "list-owned" },
{ 518, "get-cps2" },
{ 519, "get-host-cps" },
{ 520, "update-entry" },
{ 521, "list-entries" },
{ 530, "list-super-groups" },
{ 0, NULL },
};
static const struct tok vldb_req[] = {
{ 501, "create-entry" },
{ 502, "delete-entry" },
{ 503, "get-entry-by-id" },
{ 504, "get-entry-by-name" },
{ 505, "get-new-volume-id" },
{ 506, "replace-entry" },
{ 507, "update-entry" },
{ 508, "setlock" },
{ 509, "releaselock" },
{ 510, "list-entry" },
{ 511, "list-attrib" },
{ 512, "linked-list" },
{ 513, "get-stats" },
{ 514, "probe" },
{ 515, "get-addrs" },
{ 516, "change-addr" },
{ 517, "create-entry-n" },
{ 518, "get-entry-by-id-n" },
{ 519, "get-entry-by-name-n" },
{ 520, "replace-entry-n" },
{ 521, "list-entry-n" },
{ 522, "list-attrib-n" },
{ 523, "linked-list-n" },
{ 524, "update-entry-by-name" },
{ 525, "create-entry-u" },
{ 526, "get-entry-by-id-u" },
{ 527, "get-entry-by-name-u" },
{ 528, "replace-entry-u" },
{ 529, "list-entry-u" },
{ 530, "list-attrib-u" },
{ 531, "linked-list-u" },
{ 532, "regaddr" },
{ 533, "get-addrs-u" },
{ 534, "list-attrib-n2" },
{ 0, NULL },
};
static const struct tok kauth_req[] = {
{ 1, "auth-old" },
{ 21, "authenticate" },
{ 22, "authenticate-v2" },
{ 2, "change-pw" },
{ 3, "get-ticket-old" },
{ 23, "get-ticket" },
{ 4, "set-pw" },
{ 5, "set-fields" },
{ 6, "create-user" },
{ 7, "delete-user" },
{ 8, "get-entry" },
{ 9, "list-entry" },
{ 10, "get-stats" },
{ 11, "debug" },
{ 12, "get-pw" },
{ 13, "get-random-key" },
{ 14, "unlock" },
{ 15, "lock-status" },
{ 0, NULL },
};
static const struct tok vol_req[] = {
{ 100, "create-volume" },
{ 101, "delete-volume" },
{ 102, "restore" },
{ 103, "forward" },
{ 104, "end-trans" },
{ 105, "clone" },
{ 106, "set-flags" },
{ 107, "get-flags" },
{ 108, "trans-create" },
{ 109, "dump" },
{ 110, "get-nth-volume" },
{ 111, "set-forwarding" },
{ 112, "get-name" },
{ 113, "get-status" },
{ 114, "sig-restore" },
{ 115, "list-partitions" },
{ 116, "list-volumes" },
{ 117, "set-id-types" },
{ 118, "monitor" },
{ 119, "partition-info" },
{ 120, "reclone" },
{ 121, "list-one-volume" },
{ 122, "nuke" },
{ 123, "set-date" },
{ 124, "x-list-volumes" },
{ 125, "x-list-one-volume" },
{ 126, "set-info" },
{ 127, "x-list-partitions" },
{ 128, "forward-multiple" },
{ 65536, "convert-ro" },
{ 65537, "get-size" },
{ 65538, "dump-v2" },
{ 0, NULL },
};
static const struct tok bos_req[] = {
{ 80, "create-bnode" },
{ 81, "delete-bnode" },
{ 82, "set-status" },
{ 83, "get-status" },
{ 84, "enumerate-instance" },
{ 85, "get-instance-info" },
{ 86, "get-instance-parm" },
{ 87, "add-superuser" },
{ 88, "delete-superuser" },
{ 89, "list-superusers" },
{ 90, "list-keys" },
{ 91, "add-key" },
{ 92, "delete-key" },
{ 93, "set-cell-name" },
{ 94, "get-cell-name" },
{ 95, "get-cell-host" },
{ 96, "add-cell-host" },
{ 97, "delete-cell-host" },
{ 98, "set-t-status" },
{ 99, "shutdown-all" },
{ 100, "restart-all" },
{ 101, "startup-all" },
{ 102, "set-noauth-flag" },
{ 103, "re-bozo" },
{ 104, "restart" },
{ 105, "start-bozo-install" },
{ 106, "uninstall" },
{ 107, "get-dates" },
{ 108, "exec" },
{ 109, "prune" },
{ 110, "set-restart-time" },
{ 111, "get-restart-time" },
{ 112, "start-bozo-log" },
{ 113, "wait-all" },
{ 114, "get-instance-strings" },
{ 115, "get-restricted" },
{ 116, "set-restricted" },
{ 0, NULL },
};
static const struct tok ubik_req[] = {
{ 10000, "vote-beacon" },
{ 10001, "vote-debug-old" },
{ 10002, "vote-sdebug-old" },
{ 10003, "vote-getsyncsite" },
{ 10004, "vote-debug" },
{ 10005, "vote-sdebug" },
{ 10006, "vote-xdebug" },
{ 10007, "vote-xsdebug" },
{ 20000, "disk-begin" },
{ 20001, "disk-commit" },
{ 20002, "disk-lock" },
{ 20003, "disk-write" },
{ 20004, "disk-getversion" },
{ 20005, "disk-getfile" },
{ 20006, "disk-sendfile" },
{ 20007, "disk-abort" },
{ 20008, "disk-releaselocks" },
{ 20009, "disk-truncate" },
{ 20010, "disk-probe" },
{ 20011, "disk-writev" },
{ 20012, "disk-interfaceaddr" },
{ 20013, "disk-setversion" },
{ 0, NULL },
};
#define VOTE_LOW 10000
#define VOTE_HIGH 10007
#define DISK_LOW 20000
#define DISK_HIGH 20013
static const struct tok cb_types[] = {
{ 1, "exclusive" },
{ 2, "shared" },
{ 3, "dropped" },
{ 0, NULL },
};
static const struct tok ubik_lock_types[] = {
{ 1, "read" },
{ 2, "write" },
{ 3, "wait" },
{ 0, NULL },
};
static const char *voltype[] = { "read-write", "read-only", "backup" };
static const struct tok afs_fs_errors[] = {
{ 101, "salvage volume" },
{ 102, "no such vnode" },
{ 103, "no such volume" },
{ 104, "volume exist" },
{ 105, "no service" },
{ 106, "volume offline" },
{ 107, "voline online" },
{ 108, "diskfull" },
{ 109, "diskquota exceeded" },
{ 110, "volume busy" },
{ 111, "volume moved" },
{ 112, "AFS IO error" },
{ 0xffffff9c, "restarting fileserver" }, /* -100, sic! */
{ 0, NULL }
};
/*
* Reasons for acknowledging a packet
*/
static const struct tok rx_ack_reasons[] = {
{ 1, "ack requested" },
{ 2, "duplicate packet" },
{ 3, "out of sequence" },
{ 4, "exceeds window" },
{ 5, "no buffer space" },
{ 6, "ping" },
{ 7, "ping response" },
{ 8, "delay" },
{ 9, "idle" },
{ 0, NULL },
};
/*
* Cache entries we keep around so we can figure out the RX opcode
* numbers for replies. This allows us to make sense of RX reply packets.
*/
struct rx_cache_entry {
uint32_t callnum; /* Call number (net order) */
struct in_addr client; /* client IP address (net order) */
struct in_addr server; /* server IP address (net order) */
int dport; /* server port (host order) */
u_short serviceId; /* Service identifier (net order) */
uint32_t opcode; /* RX opcode (host order) */
};
#define RX_CACHE_SIZE 64
static struct rx_cache_entry rx_cache[RX_CACHE_SIZE];
static int rx_cache_next = 0;
static int rx_cache_hint = 0;
static void rx_cache_insert(netdissect_options *, const u_char *, const struct ip *, int);
static int rx_cache_find(const struct rx_header *, const struct ip *,
int, int32_t *);
static void fs_print(netdissect_options *, const u_char *, int);
static void fs_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void acl_print(netdissect_options *, u_char *, int, u_char *);
static void cb_print(netdissect_options *, const u_char *, int);
static void cb_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void prot_print(netdissect_options *, const u_char *, int);
static void prot_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void vldb_print(netdissect_options *, const u_char *, int);
static void vldb_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void kauth_print(netdissect_options *, const u_char *, int);
static void kauth_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void vol_print(netdissect_options *, const u_char *, int);
static void vol_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void bos_print(netdissect_options *, const u_char *, int);
static void bos_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void ubik_print(netdissect_options *, const u_char *);
static void ubik_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void rx_ack_print(netdissect_options *, const u_char *, int);
static int is_ubik(uint32_t);
/*
* Handle the rx-level packet. See if we know what port it's going to so
* we can peek at the afs call inside
*/
void
rx_print(netdissect_options *ndo,
register const u_char *bp, int length, int sport, int dport,
const u_char *bp2)
{
register const struct rx_header *rxh;
int i;
int32_t opcode;
if (ndo->ndo_snapend - bp < (int)sizeof (struct rx_header)) {
ND_PRINT((ndo, " [|rx] (%d)", length));
return;
}
rxh = (const struct rx_header *) bp;
ND_PRINT((ndo, " rx %s", tok2str(rx_types, "type %d", rxh->type)));
if (ndo->ndo_vflag) {
int firstflag = 0;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, " cid %08x call# %d",
(int) EXTRACT_32BITS(&rxh->cid),
(int) EXTRACT_32BITS(&rxh->callNumber)));
ND_PRINT((ndo, " seq %d ser %d",
(int) EXTRACT_32BITS(&rxh->seq),
(int) EXTRACT_32BITS(&rxh->serial)));
if (ndo->ndo_vflag > 2)
ND_PRINT((ndo, " secindex %d serviceid %hu",
(int) rxh->securityIndex,
EXTRACT_16BITS(&rxh->serviceId)));
if (ndo->ndo_vflag > 1)
for (i = 0; i < NUM_RX_FLAGS; i++) {
if (rxh->flags & rx_flags[i].flag &&
(!rx_flags[i].packetType ||
rxh->type == rx_flags[i].packetType)) {
if (!firstflag) {
firstflag = 1;
ND_PRINT((ndo, " "));
} else {
ND_PRINT((ndo, ","));
}
ND_PRINT((ndo, "<%s>", rx_flags[i].s));
}
}
}
/*
* Try to handle AFS calls that we know about. Check the destination
* port and make sure it's a data packet. Also, make sure the
* seq number is 1 (because otherwise it's a continuation packet,
* and we can't interpret that). Also, seems that reply packets
* do not have the client-init flag set, so we check for that
* as well.
*/
if (rxh->type == RX_PACKET_TYPE_DATA &&
EXTRACT_32BITS(&rxh->seq) == 1 &&
rxh->flags & RX_CLIENT_INITIATED) {
/*
* Insert this call into the call cache table, so we
* have a chance to print out replies
*/
rx_cache_insert(ndo, bp, (const struct ip *) bp2, dport);
switch (dport) {
case FS_RX_PORT: /* AFS file service */
fs_print(ndo, bp, length);
break;
case CB_RX_PORT: /* AFS callback service */
cb_print(ndo, bp, length);
break;
case PROT_RX_PORT: /* AFS protection service */
prot_print(ndo, bp, length);
break;
case VLDB_RX_PORT: /* AFS VLDB service */
vldb_print(ndo, bp, length);
break;
case KAUTH_RX_PORT: /* AFS Kerberos auth service */
kauth_print(ndo, bp, length);
break;
case VOL_RX_PORT: /* AFS Volume service */
vol_print(ndo, bp, length);
break;
case BOS_RX_PORT: /* AFS BOS service */
bos_print(ndo, bp, length);
break;
default:
;
}
/*
* If it's a reply (client-init is _not_ set, but seq is one)
* then look it up in the cache. If we find it, call the reply
* printing functions Note that we handle abort packets here,
* because printing out the return code can be useful at times.
*/
} else if (((rxh->type == RX_PACKET_TYPE_DATA &&
EXTRACT_32BITS(&rxh->seq) == 1) ||
rxh->type == RX_PACKET_TYPE_ABORT) &&
(rxh->flags & RX_CLIENT_INITIATED) == 0 &&
rx_cache_find(rxh, (const struct ip *) bp2,
sport, &opcode)) {
switch (sport) {
case FS_RX_PORT: /* AFS file service */
fs_reply_print(ndo, bp, length, opcode);
break;
case CB_RX_PORT: /* AFS callback service */
cb_reply_print(ndo, bp, length, opcode);
break;
case PROT_RX_PORT: /* AFS PT service */
prot_reply_print(ndo, bp, length, opcode);
break;
case VLDB_RX_PORT: /* AFS VLDB service */
vldb_reply_print(ndo, bp, length, opcode);
break;
case KAUTH_RX_PORT: /* AFS Kerberos auth service */
kauth_reply_print(ndo, bp, length, opcode);
break;
case VOL_RX_PORT: /* AFS Volume service */
vol_reply_print(ndo, bp, length, opcode);
break;
case BOS_RX_PORT: /* AFS BOS service */
bos_reply_print(ndo, bp, length, opcode);
break;
default:
;
}
/*
* If it's an RX ack packet, then use the appropriate ack decoding
* function (there isn't any service-specific information in the
* ack packet, so we can use one for all AFS services)
*/
} else if (rxh->type == RX_PACKET_TYPE_ACK)
rx_ack_print(ndo, bp, length);
ND_PRINT((ndo, " (%d)", length));
}
/*
* Insert an entry into the cache. Taken from print-nfs.c
*/
static void
rx_cache_insert(netdissect_options *ndo,
const u_char *bp, const struct ip *ip, int dport)
{
struct rx_cache_entry *rxent;
const struct rx_header *rxh = (const struct rx_header *) bp;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t)))
return;
rxent = &rx_cache[rx_cache_next];
if (++rx_cache_next >= RX_CACHE_SIZE)
rx_cache_next = 0;
rxent->callnum = rxh->callNumber;
UNALIGNED_MEMCPY(&rxent->client, &ip->ip_src, sizeof(uint32_t));
UNALIGNED_MEMCPY(&rxent->server, &ip->ip_dst, sizeof(uint32_t));
rxent->dport = dport;
rxent->serviceId = rxh->serviceId;
rxent->opcode = EXTRACT_32BITS(bp + sizeof(struct rx_header));
}
/*
* Lookup an entry in the cache. Also taken from print-nfs.c
*
* Note that because this is a reply, we're looking at the _source_
* port.
*/
static int
rx_cache_find(const struct rx_header *rxh, const struct ip *ip, int sport,
int32_t *opcode)
{
int i;
struct rx_cache_entry *rxent;
uint32_t clip;
uint32_t sip;
UNALIGNED_MEMCPY(&clip, &ip->ip_dst, sizeof(uint32_t));
UNALIGNED_MEMCPY(&sip, &ip->ip_src, sizeof(uint32_t));
/* Start the search where we last left off */
i = rx_cache_hint;
do {
rxent = &rx_cache[i];
if (rxent->callnum == rxh->callNumber &&
rxent->client.s_addr == clip &&
rxent->server.s_addr == sip &&
rxent->serviceId == rxh->serviceId &&
rxent->dport == sport) {
/* We got a match! */
rx_cache_hint = i;
*opcode = rxent->opcode;
return(1);
}
if (++i >= RX_CACHE_SIZE)
i = 0;
} while (i != rx_cache_hint);
/* Our search failed */
return(0);
}
/*
* These extrememly grody macros handle the printing of various AFS stuff.
*/
#define FIDOUT() { unsigned long n1, n2, n3; \
ND_TCHECK2(bp[0], sizeof(int32_t) * 3); \
n1 = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
n2 = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
n3 = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
ND_PRINT((ndo, " fid %d/%d/%d", (int) n1, (int) n2, (int) n3)); \
}
#define STROUT(MAX) { unsigned int _i; \
ND_TCHECK2(bp[0], sizeof(int32_t)); \
_i = EXTRACT_32BITS(bp); \
if (_i > (MAX)) \
goto trunc; \
bp += sizeof(int32_t); \
ND_PRINT((ndo, " \"")); \
if (fn_printn(ndo, bp, _i, ndo->ndo_snapend)) \
goto trunc; \
ND_PRINT((ndo, "\"")); \
bp += ((_i + sizeof(int32_t) - 1) / sizeof(int32_t)) * sizeof(int32_t); \
}
#define INTOUT() { int _i; \
ND_TCHECK2(bp[0], sizeof(int32_t)); \
_i = (int) EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
ND_PRINT((ndo, " %d", _i)); \
}
#define UINTOUT() { unsigned long _i; \
ND_TCHECK2(bp[0], sizeof(int32_t)); \
_i = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
ND_PRINT((ndo, " %lu", _i)); \
}
#define UINT64OUT() { uint64_t _i; \
ND_TCHECK2(bp[0], sizeof(uint64_t)); \
_i = EXTRACT_64BITS(bp); \
bp += sizeof(uint64_t); \
ND_PRINT((ndo, " %" PRIu64, _i)); \
}
#define DATEOUT() { time_t _t; struct tm *tm; char str[256]; \
ND_TCHECK2(bp[0], sizeof(int32_t)); \
_t = (time_t) EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
tm = localtime(&_t); \
strftime(str, 256, "%Y/%m/%d %H:%M:%S", tm); \
ND_PRINT((ndo, " %s", str)); \
}
#define STOREATTROUT() { unsigned long mask, _i; \
ND_TCHECK2(bp[0], (sizeof(int32_t)*6)); \
mask = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \
if (mask) ND_PRINT((ndo, " StoreStatus")); \
if (mask & 1) { ND_PRINT((ndo, " date")); DATEOUT(); } \
else bp += sizeof(int32_t); \
_i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \
if (mask & 2) ND_PRINT((ndo, " owner %lu", _i)); \
_i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \
if (mask & 4) ND_PRINT((ndo, " group %lu", _i)); \
_i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \
if (mask & 8) ND_PRINT((ndo, " mode %lo", _i & 07777)); \
_i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \
if (mask & 16) ND_PRINT((ndo, " segsize %lu", _i)); \
/* undocumented in 3.3 docu */ \
if (mask & 1024) ND_PRINT((ndo, " fsync")); \
}
#define UBIK_VERSIONOUT() {int32_t epoch; int32_t counter; \
ND_TCHECK2(bp[0], sizeof(int32_t) * 2); \
epoch = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
counter = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
ND_PRINT((ndo, " %d.%d", epoch, counter)); \
}
#define AFSUUIDOUT() {uint32_t temp; int _i; \
ND_TCHECK2(bp[0], 11*sizeof(uint32_t)); \
temp = EXTRACT_32BITS(bp); \
bp += sizeof(uint32_t); \
ND_PRINT((ndo, " %08x", temp)); \
temp = EXTRACT_32BITS(bp); \
bp += sizeof(uint32_t); \
ND_PRINT((ndo, "%04x", temp)); \
temp = EXTRACT_32BITS(bp); \
bp += sizeof(uint32_t); \
ND_PRINT((ndo, "%04x", temp)); \
for (_i = 0; _i < 8; _i++) { \
temp = EXTRACT_32BITS(bp); \
bp += sizeof(uint32_t); \
ND_PRINT((ndo, "%02x", (unsigned char) temp)); \
} \
}
/*
* This is the sickest one of all
*/
#define VECOUT(MAX) { u_char *sp; \
u_char s[AFSNAMEMAX]; \
int k; \
if ((MAX) + 1 > sizeof(s)) \
goto trunc; \
ND_TCHECK2(bp[0], (MAX) * sizeof(int32_t)); \
sp = s; \
for (k = 0; k < (MAX); k++) { \
*sp++ = (u_char) EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
} \
s[(MAX)] = '\0'; \
ND_PRINT((ndo, " \"")); \
fn_print(ndo, s, NULL); \
ND_PRINT((ndo, "\"")); \
}
#define DESTSERVEROUT() { unsigned long n1, n2, n3; \
ND_TCHECK2(bp[0], sizeof(int32_t) * 3); \
n1 = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
n2 = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
n3 = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
ND_PRINT((ndo, " server %d:%d:%d", (int) n1, (int) n2, (int) n3)); \
}
/*
* Handle calls to the AFS file service (fs)
*/
static void
fs_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
int fs_op;
unsigned long i;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from fsint/afsint.xg
*/
fs_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " fs call %s", tok2str(fs_req, "op#%d", fs_op)));
/*
* Print out arguments to some of the AFS calls. This stuff is
* all from afsint.xg
*/
bp += sizeof(struct rx_header) + 4;
/*
* Sigh. This is gross. Ritchie forgive me.
*/
switch (fs_op) {
case 130: /* Fetch data */
FIDOUT();
ND_PRINT((ndo, " offset"));
UINTOUT();
ND_PRINT((ndo, " length"));
UINTOUT();
break;
case 131: /* Fetch ACL */
case 132: /* Fetch Status */
case 143: /* Old set lock */
case 144: /* Old extend lock */
case 145: /* Old release lock */
case 156: /* Set lock */
case 157: /* Extend lock */
case 158: /* Release lock */
FIDOUT();
break;
case 135: /* Store status */
FIDOUT();
STOREATTROUT();
break;
case 133: /* Store data */
FIDOUT();
STOREATTROUT();
ND_PRINT((ndo, " offset"));
UINTOUT();
ND_PRINT((ndo, " length"));
UINTOUT();
ND_PRINT((ndo, " flen"));
UINTOUT();
break;
case 134: /* Store ACL */
{
char a[AFSOPAQUEMAX+1];
FIDOUT();
ND_TCHECK2(bp[0], 4);
i = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_TCHECK2(bp[0], i);
i = min(AFSOPAQUEMAX, i);
strncpy(a, (const char *) bp, i);
a[i] = '\0';
acl_print(ndo, (u_char *) a, sizeof(a), (u_char *) a + i);
break;
}
case 137: /* Create file */
case 141: /* MakeDir */
FIDOUT();
STROUT(AFSNAMEMAX);
STOREATTROUT();
break;
case 136: /* Remove file */
case 142: /* Remove directory */
FIDOUT();
STROUT(AFSNAMEMAX);
break;
case 138: /* Rename file */
ND_PRINT((ndo, " old"));
FIDOUT();
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " new"));
FIDOUT();
STROUT(AFSNAMEMAX);
break;
case 139: /* Symlink */
FIDOUT();
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " link to"));
STROUT(AFSNAMEMAX);
break;
case 140: /* Link */
FIDOUT();
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " link to"));
FIDOUT();
break;
case 148: /* Get volume info */
STROUT(AFSNAMEMAX);
break;
case 149: /* Get volume stats */
case 150: /* Set volume stats */
ND_PRINT((ndo, " volid"));
UINTOUT();
break;
case 154: /* New get volume info */
ND_PRINT((ndo, " volname"));
STROUT(AFSNAMEMAX);
break;
case 155: /* Bulk stat */
case 65536: /* Inline bulk stat */
{
unsigned long j;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (i = 0; i < j; i++) {
FIDOUT();
if (i != j - 1)
ND_PRINT((ndo, ","));
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
case 65537: /* Fetch data 64 */
FIDOUT();
ND_PRINT((ndo, " offset"));
UINT64OUT();
ND_PRINT((ndo, " length"));
UINT64OUT();
break;
case 65538: /* Store data 64 */
FIDOUT();
STOREATTROUT();
ND_PRINT((ndo, " offset"));
UINT64OUT();
ND_PRINT((ndo, " length"));
UINT64OUT();
ND_PRINT((ndo, " flen"));
UINT64OUT();
break;
case 65541: /* CallBack rx conn address */
ND_PRINT((ndo, " addr"));
UINTOUT();
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|fs]"));
}
/*
* Handle replies to the AFS file service
*/
static void
fs_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
unsigned long i;
const struct rx_header *rxh;
if (length <= (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from fsint/afsint.xg
*/
ND_PRINT((ndo, " fs reply %s", tok2str(fs_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, interpret the response
*/
if (rxh->type == RX_PACKET_TYPE_DATA) {
switch (opcode) {
case 131: /* Fetch ACL */
{
char a[AFSOPAQUEMAX+1];
ND_TCHECK2(bp[0], 4);
i = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_TCHECK2(bp[0], i);
i = min(AFSOPAQUEMAX, i);
strncpy(a, (const char *) bp, i);
a[i] = '\0';
acl_print(ndo, (u_char *) a, sizeof(a), (u_char *) a + i);
break;
}
case 137: /* Create file */
case 141: /* MakeDir */
ND_PRINT((ndo, " new"));
FIDOUT();
break;
case 151: /* Get root volume */
ND_PRINT((ndo, " root volume"));
STROUT(AFSNAMEMAX);
break;
case 153: /* Get time */
DATEOUT();
break;
default:
;
}
} else if (rxh->type == RX_PACKET_TYPE_ABORT) {
/*
* Otherwise, just print out the return code
*/
ND_TCHECK2(bp[0], sizeof(int32_t));
i = (int) EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_PRINT((ndo, " error %s", tok2str(afs_fs_errors, "#%d", i)));
} else {
ND_PRINT((ndo, " strange fs reply of type %d", rxh->type));
}
return;
trunc:
ND_PRINT((ndo, " [|fs]"));
}
/*
* Print out an AFS ACL string. An AFS ACL is a string that has the
* following format:
*
* <positive> <negative>
* <uid1> <aclbits1>
* ....
*
* "positive" and "negative" are integers which contain the number of
* positive and negative ACL's in the string. The uid/aclbits pair are
* ASCII strings containing the UID/PTS record and an ASCII number
* representing a logical OR of all the ACL permission bits
*/
static void
acl_print(netdissect_options *ndo,
u_char *s, int maxsize, u_char *end)
{
int pos, neg, acl;
int n, i;
char *user;
char fmt[1024];
if ((user = (char *)malloc(maxsize)) == NULL)
return;
if (sscanf((char *) s, "%d %d\n%n", &pos, &neg, &n) != 2)
goto finish;
s += n;
if (s > end)
goto finish;
/*
* This wacky order preserves the order used by the "fs" command
*/
#define ACLOUT(acl) \
ND_PRINT((ndo, "%s%s%s%s%s%s%s", \
acl & PRSFS_READ ? "r" : "", \
acl & PRSFS_LOOKUP ? "l" : "", \
acl & PRSFS_INSERT ? "i" : "", \
acl & PRSFS_DELETE ? "d" : "", \
acl & PRSFS_WRITE ? "w" : "", \
acl & PRSFS_LOCK ? "k" : "", \
acl & PRSFS_ADMINISTER ? "a" : ""));
for (i = 0; i < pos; i++) {
snprintf(fmt, sizeof(fmt), "%%%ds %%d\n%%n", maxsize - 1);
if (sscanf((char *) s, fmt, user, &acl, &n) != 2)
goto finish;
s += n;
ND_PRINT((ndo, " +{"));
fn_print(ndo, (u_char *)user, NULL);
ND_PRINT((ndo, " "));
ACLOUT(acl);
ND_PRINT((ndo, "}"));
if (s > end)
goto finish;
}
for (i = 0; i < neg; i++) {
snprintf(fmt, sizeof(fmt), "%%%ds %%d\n%%n", maxsize - 1);
if (sscanf((char *) s, fmt, user, &acl, &n) != 2)
goto finish;
s += n;
ND_PRINT((ndo, " -{"));
fn_print(ndo, (u_char *)user, NULL);
ND_PRINT((ndo, " "));
ACLOUT(acl);
ND_PRINT((ndo, "}"));
if (s > end)
goto finish;
}
finish:
free(user);
return;
}
#undef ACLOUT
/*
* Handle calls to the AFS callback service
*/
static void
cb_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
int cb_op;
unsigned long i;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from fsint/afscbint.xg
*/
cb_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " cb call %s", tok2str(cb_req, "op#%d", cb_op)));
bp += sizeof(struct rx_header) + 4;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from fsint/afscbint.xg
*/
switch (cb_op) {
case 204: /* Callback */
{
unsigned long j, t;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (i = 0; i < j; i++) {
FIDOUT();
if (i != j - 1)
ND_PRINT((ndo, ","));
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
if (j != 0)
ND_PRINT((ndo, ";"));
for (i = 0; i < j; i++) {
ND_PRINT((ndo, " ver"));
INTOUT();
ND_PRINT((ndo, " expires"));
DATEOUT();
ND_TCHECK2(bp[0], 4);
t = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
tok2str(cb_types, "type %d", t);
}
}
case 214: {
ND_PRINT((ndo, " afsuuid"));
AFSUUIDOUT();
break;
}
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|cb]"));
}
/*
* Handle replies to the AFS Callback Service
*/
static void
cb_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
const struct rx_header *rxh;
if (length <= (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from fsint/afscbint.xg
*/
ND_PRINT((ndo, " cb reply %s", tok2str(cb_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, interpret the response.
*/
if (rxh->type == RX_PACKET_TYPE_DATA)
switch (opcode) {
case 213: /* InitCallBackState3 */
AFSUUIDOUT();
break;
default:
;
}
else {
/*
* Otherwise, just print out the return code
*/
ND_PRINT((ndo, " errcode"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|cb]"));
}
/*
* Handle calls to the AFS protection database server
*/
static void
prot_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
unsigned long i;
int pt_op;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from ptserver/ptint.xg
*/
pt_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " pt"));
if (is_ubik(pt_op)) {
ubik_print(ndo, bp);
return;
}
ND_PRINT((ndo, " call %s", tok2str(pt_req, "op#%d", pt_op)));
/*
* Decode some of the arguments to the PT calls
*/
bp += sizeof(struct rx_header) + 4;
switch (pt_op) {
case 500: /* I New User */
STROUT(PRNAMEMAX);
ND_PRINT((ndo, " id"));
INTOUT();
ND_PRINT((ndo, " oldid"));
INTOUT();
break;
case 501: /* Where is it */
case 506: /* Delete */
case 508: /* Get CPS */
case 512: /* List entry */
case 514: /* List elements */
case 517: /* List owned */
case 518: /* Get CPS2 */
case 519: /* Get host CPS */
case 530: /* List super groups */
ND_PRINT((ndo, " id"));
INTOUT();
break;
case 502: /* Dump entry */
ND_PRINT((ndo, " pos"));
INTOUT();
break;
case 503: /* Add to group */
case 507: /* Remove from group */
case 515: /* Is a member of? */
ND_PRINT((ndo, " uid"));
INTOUT();
ND_PRINT((ndo, " gid"));
INTOUT();
break;
case 504: /* Name to ID */
{
unsigned long j;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
/*
* Who designed this chicken-shit protocol?
*
* Each character is stored as a 32-bit
* integer!
*/
for (i = 0; i < j; i++) {
VECOUT(PRNAMEMAX);
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
break;
case 505: /* Id to name */
{
unsigned long j;
ND_PRINT((ndo, " ids:"));
ND_TCHECK2(bp[0], 4);
i = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (j = 0; j < i; j++)
INTOUT();
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
break;
case 509: /* New entry */
STROUT(PRNAMEMAX);
ND_PRINT((ndo, " flag"));
INTOUT();
ND_PRINT((ndo, " oid"));
INTOUT();
break;
case 511: /* Set max */
ND_PRINT((ndo, " id"));
INTOUT();
ND_PRINT((ndo, " gflag"));
INTOUT();
break;
case 513: /* Change entry */
ND_PRINT((ndo, " id"));
INTOUT();
STROUT(PRNAMEMAX);
ND_PRINT((ndo, " oldid"));
INTOUT();
ND_PRINT((ndo, " newid"));
INTOUT();
break;
case 520: /* Update entry */
ND_PRINT((ndo, " id"));
INTOUT();
STROUT(PRNAMEMAX);
break;
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|pt]"));
}
/*
* Handle replies to the AFS protection service
*/
static void
prot_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
const struct rx_header *rxh;
unsigned long i;
if (length < (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from ptserver/ptint.xg. Check to see if it's a
* Ubik call, however.
*/
ND_PRINT((ndo, " pt"));
if (is_ubik(opcode)) {
ubik_reply_print(ndo, bp, length, opcode);
return;
}
ND_PRINT((ndo, " reply %s", tok2str(pt_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, interpret the response
*/
if (rxh->type == RX_PACKET_TYPE_DATA)
switch (opcode) {
case 504: /* Name to ID */
{
unsigned long j;
ND_PRINT((ndo, " ids:"));
ND_TCHECK2(bp[0], 4);
i = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (j = 0; j < i; j++)
INTOUT();
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
break;
case 505: /* ID to name */
{
unsigned long j;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
/*
* Who designed this chicken-shit protocol?
*
* Each character is stored as a 32-bit
* integer!
*/
for (i = 0; i < j; i++) {
VECOUT(PRNAMEMAX);
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
break;
case 508: /* Get CPS */
case 514: /* List elements */
case 517: /* List owned */
case 518: /* Get CPS2 */
case 519: /* Get host CPS */
{
unsigned long j;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (i = 0; i < j; i++) {
INTOUT();
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
break;
case 510: /* List max */
ND_PRINT((ndo, " maxuid"));
INTOUT();
ND_PRINT((ndo, " maxgid"));
INTOUT();
break;
default:
;
}
else {
/*
* Otherwise, just print out the return code
*/
ND_PRINT((ndo, " errcode"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|pt]"));
}
/*
* Handle calls to the AFS volume location database service
*/
static void
vldb_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
int vldb_op;
unsigned long i;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from vlserver/vldbint.xg
*/
vldb_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " vldb"));
if (is_ubik(vldb_op)) {
ubik_print(ndo, bp);
return;
}
ND_PRINT((ndo, " call %s", tok2str(vldb_req, "op#%d", vldb_op)));
/*
* Decode some of the arguments to the VLDB calls
*/
bp += sizeof(struct rx_header) + 4;
switch (vldb_op) {
case 501: /* Create new volume */
case 517: /* Create entry N */
VECOUT(VLNAMEMAX);
break;
case 502: /* Delete entry */
case 503: /* Get entry by ID */
case 507: /* Update entry */
case 508: /* Set lock */
case 509: /* Release lock */
case 518: /* Get entry by ID N */
ND_PRINT((ndo, " volid"));
INTOUT();
ND_TCHECK2(bp[0], sizeof(int32_t));
i = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
if (i <= 2)
ND_PRINT((ndo, " type %s", voltype[i]));
break;
case 504: /* Get entry by name */
case 519: /* Get entry by name N */
case 524: /* Update entry by name */
case 527: /* Get entry by name U */
STROUT(VLNAMEMAX);
break;
case 505: /* Get new vol id */
ND_PRINT((ndo, " bump"));
INTOUT();
break;
case 506: /* Replace entry */
case 520: /* Replace entry N */
ND_PRINT((ndo, " volid"));
INTOUT();
ND_TCHECK2(bp[0], sizeof(int32_t));
i = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
if (i <= 2)
ND_PRINT((ndo, " type %s", voltype[i]));
VECOUT(VLNAMEMAX);
break;
case 510: /* List entry */
case 521: /* List entry N */
ND_PRINT((ndo, " index"));
INTOUT();
break;
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|vldb]"));
}
/*
* Handle replies to the AFS volume location database service
*/
static void
vldb_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
const struct rx_header *rxh;
unsigned long i;
if (length < (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from vlserver/vldbint.xg. Check to see if it's a
* Ubik call, however.
*/
ND_PRINT((ndo, " vldb"));
if (is_ubik(opcode)) {
ubik_reply_print(ndo, bp, length, opcode);
return;
}
ND_PRINT((ndo, " reply %s", tok2str(vldb_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, interpret the response
*/
if (rxh->type == RX_PACKET_TYPE_DATA)
switch (opcode) {
case 510: /* List entry */
ND_PRINT((ndo, " count"));
INTOUT();
ND_PRINT((ndo, " nextindex"));
INTOUT();
case 503: /* Get entry by id */
case 504: /* Get entry by name */
{ unsigned long nservers, j;
VECOUT(VLNAMEMAX);
ND_TCHECK2(bp[0], sizeof(int32_t));
bp += sizeof(int32_t);
ND_PRINT((ndo, " numservers"));
ND_TCHECK2(bp[0], sizeof(int32_t));
nservers = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_PRINT((ndo, " %lu", nservers));
ND_PRINT((ndo, " servers"));
for (i = 0; i < 8; i++) {
ND_TCHECK2(bp[0], sizeof(int32_t));
if (i < nservers)
ND_PRINT((ndo, " %s",
intoa(((const struct in_addr *) bp)->s_addr)));
bp += sizeof(int32_t);
}
ND_PRINT((ndo, " partitions"));
for (i = 0; i < 8; i++) {
ND_TCHECK2(bp[0], sizeof(int32_t));
j = EXTRACT_32BITS(bp);
if (i < nservers && j <= 26)
ND_PRINT((ndo, " %c", 'a' + (int)j));
else if (i < nservers)
ND_PRINT((ndo, " %lu", j));
bp += sizeof(int32_t);
}
ND_TCHECK2(bp[0], 8 * sizeof(int32_t));
bp += 8 * sizeof(int32_t);
ND_PRINT((ndo, " rwvol"));
UINTOUT();
ND_PRINT((ndo, " rovol"));
UINTOUT();
ND_PRINT((ndo, " backup"));
UINTOUT();
}
break;
case 505: /* Get new volume ID */
ND_PRINT((ndo, " newvol"));
UINTOUT();
break;
case 521: /* List entry */
case 529: /* List entry U */
ND_PRINT((ndo, " count"));
INTOUT();
ND_PRINT((ndo, " nextindex"));
INTOUT();
case 518: /* Get entry by ID N */
case 519: /* Get entry by name N */
{ unsigned long nservers, j;
VECOUT(VLNAMEMAX);
ND_PRINT((ndo, " numservers"));
ND_TCHECK2(bp[0], sizeof(int32_t));
nservers = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_PRINT((ndo, " %lu", nservers));
ND_PRINT((ndo, " servers"));
for (i = 0; i < 13; i++) {
ND_TCHECK2(bp[0], sizeof(int32_t));
if (i < nservers)
ND_PRINT((ndo, " %s",
intoa(((const struct in_addr *) bp)->s_addr)));
bp += sizeof(int32_t);
}
ND_PRINT((ndo, " partitions"));
for (i = 0; i < 13; i++) {
ND_TCHECK2(bp[0], sizeof(int32_t));
j = EXTRACT_32BITS(bp);
if (i < nservers && j <= 26)
ND_PRINT((ndo, " %c", 'a' + (int)j));
else if (i < nservers)
ND_PRINT((ndo, " %lu", j));
bp += sizeof(int32_t);
}
ND_TCHECK2(bp[0], 13 * sizeof(int32_t));
bp += 13 * sizeof(int32_t);
ND_PRINT((ndo, " rwvol"));
UINTOUT();
ND_PRINT((ndo, " rovol"));
UINTOUT();
ND_PRINT((ndo, " backup"));
UINTOUT();
}
break;
case 526: /* Get entry by ID U */
case 527: /* Get entry by name U */
{ unsigned long nservers, j;
VECOUT(VLNAMEMAX);
ND_PRINT((ndo, " numservers"));
ND_TCHECK2(bp[0], sizeof(int32_t));
nservers = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_PRINT((ndo, " %lu", nservers));
ND_PRINT((ndo, " servers"));
for (i = 0; i < 13; i++) {
if (i < nservers) {
ND_PRINT((ndo, " afsuuid"));
AFSUUIDOUT();
} else {
ND_TCHECK2(bp[0], 44);
bp += 44;
}
}
ND_TCHECK2(bp[0], 4 * 13);
bp += 4 * 13;
ND_PRINT((ndo, " partitions"));
for (i = 0; i < 13; i++) {
ND_TCHECK2(bp[0], sizeof(int32_t));
j = EXTRACT_32BITS(bp);
if (i < nservers && j <= 26)
ND_PRINT((ndo, " %c", 'a' + (int)j));
else if (i < nservers)
ND_PRINT((ndo, " %lu", j));
bp += sizeof(int32_t);
}
ND_TCHECK2(bp[0], 13 * sizeof(int32_t));
bp += 13 * sizeof(int32_t);
ND_PRINT((ndo, " rwvol"));
UINTOUT();
ND_PRINT((ndo, " rovol"));
UINTOUT();
ND_PRINT((ndo, " backup"));
UINTOUT();
}
default:
;
}
else {
/*
* Otherwise, just print out the return code
*/
ND_PRINT((ndo, " errcode"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|vldb]"));
}
/*
* Handle calls to the AFS Kerberos Authentication service
*/
static void
kauth_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
int kauth_op;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from kauth/kauth.rg
*/
kauth_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " kauth"));
if (is_ubik(kauth_op)) {
ubik_print(ndo, bp);
return;
}
ND_PRINT((ndo, " call %s", tok2str(kauth_req, "op#%d", kauth_op)));
/*
* Decode some of the arguments to the KA calls
*/
bp += sizeof(struct rx_header) + 4;
switch (kauth_op) {
case 1: /* Authenticate old */
case 21: /* Authenticate */
case 22: /* Authenticate-V2 */
case 2: /* Change PW */
case 5: /* Set fields */
case 6: /* Create user */
case 7: /* Delete user */
case 8: /* Get entry */
case 14: /* Unlock */
case 15: /* Lock status */
ND_PRINT((ndo, " principal"));
STROUT(KANAMEMAX);
STROUT(KANAMEMAX);
break;
case 3: /* GetTicket-old */
case 23: /* GetTicket */
{
int i;
ND_PRINT((ndo, " kvno"));
INTOUT();
ND_PRINT((ndo, " domain"));
STROUT(KANAMEMAX);
ND_TCHECK2(bp[0], sizeof(int32_t));
i = (int) EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_TCHECK2(bp[0], i);
bp += i;
ND_PRINT((ndo, " principal"));
STROUT(KANAMEMAX);
STROUT(KANAMEMAX);
break;
}
case 4: /* Set Password */
ND_PRINT((ndo, " principal"));
STROUT(KANAMEMAX);
STROUT(KANAMEMAX);
ND_PRINT((ndo, " kvno"));
INTOUT();
break;
case 12: /* Get password */
ND_PRINT((ndo, " name"));
STROUT(KANAMEMAX);
break;
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|kauth]"));
}
/*
* Handle replies to the AFS Kerberos Authentication Service
*/
static void
kauth_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
const struct rx_header *rxh;
if (length <= (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from kauth/kauth.rg
*/
ND_PRINT((ndo, " kauth"));
if (is_ubik(opcode)) {
ubik_reply_print(ndo, bp, length, opcode);
return;
}
ND_PRINT((ndo, " reply %s", tok2str(kauth_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, interpret the response.
*/
if (rxh->type == RX_PACKET_TYPE_DATA)
/* Well, no, not really. Leave this for later */
;
else {
/*
* Otherwise, just print out the return code
*/
ND_PRINT((ndo, " errcode"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|kauth]"));
}
/*
* Handle calls to the AFS Volume location service
*/
static void
vol_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
int vol_op;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from volser/volint.xg
*/
vol_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " vol call %s", tok2str(vol_req, "op#%d", vol_op)));
bp += sizeof(struct rx_header) + 4;
switch (vol_op) {
case 100: /* Create volume */
ND_PRINT((ndo, " partition"));
UINTOUT();
ND_PRINT((ndo, " name"));
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " type"));
UINTOUT();
ND_PRINT((ndo, " parent"));
UINTOUT();
break;
case 101: /* Delete volume */
case 107: /* Get flags */
ND_PRINT((ndo, " trans"));
UINTOUT();
break;
case 102: /* Restore */
ND_PRINT((ndo, " totrans"));
UINTOUT();
ND_PRINT((ndo, " flags"));
UINTOUT();
break;
case 103: /* Forward */
ND_PRINT((ndo, " fromtrans"));
UINTOUT();
ND_PRINT((ndo, " fromdate"));
DATEOUT();
DESTSERVEROUT();
ND_PRINT((ndo, " desttrans"));
INTOUT();
break;
case 104: /* End trans */
ND_PRINT((ndo, " trans"));
UINTOUT();
break;
case 105: /* Clone */
ND_PRINT((ndo, " trans"));
UINTOUT();
ND_PRINT((ndo, " purgevol"));
UINTOUT();
ND_PRINT((ndo, " newtype"));
UINTOUT();
ND_PRINT((ndo, " newname"));
STROUT(AFSNAMEMAX);
break;
case 106: /* Set flags */
ND_PRINT((ndo, " trans"));
UINTOUT();
ND_PRINT((ndo, " flags"));
UINTOUT();
break;
case 108: /* Trans create */
ND_PRINT((ndo, " vol"));
UINTOUT();
ND_PRINT((ndo, " partition"));
UINTOUT();
ND_PRINT((ndo, " flags"));
UINTOUT();
break;
case 109: /* Dump */
case 655537: /* Get size */
ND_PRINT((ndo, " fromtrans"));
UINTOUT();
ND_PRINT((ndo, " fromdate"));
DATEOUT();
break;
case 110: /* Get n-th volume */
ND_PRINT((ndo, " index"));
UINTOUT();
break;
case 111: /* Set forwarding */
ND_PRINT((ndo, " tid"));
UINTOUT();
ND_PRINT((ndo, " newsite"));
UINTOUT();
break;
case 112: /* Get name */
case 113: /* Get status */
ND_PRINT((ndo, " tid"));
break;
case 114: /* Signal restore */
ND_PRINT((ndo, " name"));
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " type"));
UINTOUT();
ND_PRINT((ndo, " pid"));
UINTOUT();
ND_PRINT((ndo, " cloneid"));
UINTOUT();
break;
case 116: /* List volumes */
ND_PRINT((ndo, " partition"));
UINTOUT();
ND_PRINT((ndo, " flags"));
UINTOUT();
break;
case 117: /* Set id types */
ND_PRINT((ndo, " tid"));
UINTOUT();
ND_PRINT((ndo, " name"));
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " type"));
UINTOUT();
ND_PRINT((ndo, " pid"));
UINTOUT();
ND_PRINT((ndo, " clone"));
UINTOUT();
ND_PRINT((ndo, " backup"));
UINTOUT();
break;
case 119: /* Partition info */
ND_PRINT((ndo, " name"));
STROUT(AFSNAMEMAX);
break;
case 120: /* Reclone */
ND_PRINT((ndo, " tid"));
UINTOUT();
break;
case 121: /* List one volume */
case 122: /* Nuke volume */
case 124: /* Extended List volumes */
case 125: /* Extended List one volume */
case 65536: /* Convert RO to RW volume */
ND_PRINT((ndo, " partid"));
UINTOUT();
ND_PRINT((ndo, " volid"));
UINTOUT();
break;
case 123: /* Set date */
ND_PRINT((ndo, " tid"));
UINTOUT();
ND_PRINT((ndo, " date"));
DATEOUT();
break;
case 126: /* Set info */
ND_PRINT((ndo, " tid"));
UINTOUT();
break;
case 128: /* Forward multiple */
ND_PRINT((ndo, " fromtrans"));
UINTOUT();
ND_PRINT((ndo, " fromdate"));
DATEOUT();
{
unsigned long i, j;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (i = 0; i < j; i++) {
DESTSERVEROUT();
if (i != j - 1)
ND_PRINT((ndo, ","));
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
break;
case 65538: /* Dump version 2 */
ND_PRINT((ndo, " fromtrans"));
UINTOUT();
ND_PRINT((ndo, " fromdate"));
DATEOUT();
ND_PRINT((ndo, " flags"));
UINTOUT();
break;
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|vol]"));
}
/*
* Handle replies to the AFS Volume Service
*/
static void
vol_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
const struct rx_header *rxh;
if (length <= (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from volser/volint.xg
*/
ND_PRINT((ndo, " vol reply %s", tok2str(vol_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, interpret the response.
*/
if (rxh->type == RX_PACKET_TYPE_DATA) {
switch (opcode) {
case 100: /* Create volume */
ND_PRINT((ndo, " volid"));
UINTOUT();
ND_PRINT((ndo, " trans"));
UINTOUT();
break;
case 104: /* End transaction */
UINTOUT();
break;
case 105: /* Clone */
ND_PRINT((ndo, " newvol"));
UINTOUT();
break;
case 107: /* Get flags */
UINTOUT();
break;
case 108: /* Transaction create */
ND_PRINT((ndo, " trans"));
UINTOUT();
break;
case 110: /* Get n-th volume */
ND_PRINT((ndo, " volume"));
UINTOUT();
ND_PRINT((ndo, " partition"));
UINTOUT();
break;
case 112: /* Get name */
STROUT(AFSNAMEMAX);
break;
case 113: /* Get status */
ND_PRINT((ndo, " volid"));
UINTOUT();
ND_PRINT((ndo, " nextuniq"));
UINTOUT();
ND_PRINT((ndo, " type"));
UINTOUT();
ND_PRINT((ndo, " parentid"));
UINTOUT();
ND_PRINT((ndo, " clone"));
UINTOUT();
ND_PRINT((ndo, " backup"));
UINTOUT();
ND_PRINT((ndo, " restore"));
UINTOUT();
ND_PRINT((ndo, " maxquota"));
UINTOUT();
ND_PRINT((ndo, " minquota"));
UINTOUT();
ND_PRINT((ndo, " owner"));
UINTOUT();
ND_PRINT((ndo, " create"));
DATEOUT();
ND_PRINT((ndo, " access"));
DATEOUT();
ND_PRINT((ndo, " update"));
DATEOUT();
ND_PRINT((ndo, " expire"));
DATEOUT();
ND_PRINT((ndo, " backup"));
DATEOUT();
ND_PRINT((ndo, " copy"));
DATEOUT();
break;
case 115: /* Old list partitions */
break;
case 116: /* List volumes */
case 121: /* List one volume */
{
unsigned long i, j;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (i = 0; i < j; i++) {
ND_PRINT((ndo, " name"));
VECOUT(32);
ND_PRINT((ndo, " volid"));
UINTOUT();
ND_PRINT((ndo, " type"));
bp += sizeof(int32_t) * 21;
if (i != j - 1)
ND_PRINT((ndo, ","));
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
break;
default:
;
}
} else {
/*
* Otherwise, just print out the return code
*/
ND_PRINT((ndo, " errcode"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|vol]"));
}
/*
* Handle calls to the AFS BOS service
*/
static void
bos_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
int bos_op;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from bozo/bosint.xg
*/
bos_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " bos call %s", tok2str(bos_req, "op#%d", bos_op)));
/*
* Decode some of the arguments to the BOS calls
*/
bp += sizeof(struct rx_header) + 4;
switch (bos_op) {
case 80: /* Create B node */
ND_PRINT((ndo, " type"));
STROUT(BOSNAMEMAX);
ND_PRINT((ndo, " instance"));
STROUT(BOSNAMEMAX);
break;
case 81: /* Delete B node */
case 83: /* Get status */
case 85: /* Get instance info */
case 87: /* Add super user */
case 88: /* Delete super user */
case 93: /* Set cell name */
case 96: /* Add cell host */
case 97: /* Delete cell host */
case 104: /* Restart */
case 106: /* Uninstall */
case 108: /* Exec */
case 112: /* Getlog */
case 114: /* Get instance strings */
STROUT(BOSNAMEMAX);
break;
case 82: /* Set status */
case 98: /* Set T status */
STROUT(BOSNAMEMAX);
ND_PRINT((ndo, " status"));
INTOUT();
break;
case 86: /* Get instance parm */
STROUT(BOSNAMEMAX);
ND_PRINT((ndo, " num"));
INTOUT();
break;
case 84: /* Enumerate instance */
case 89: /* List super users */
case 90: /* List keys */
case 91: /* Add key */
case 92: /* Delete key */
case 95: /* Get cell host */
INTOUT();
break;
case 105: /* Install */
STROUT(BOSNAMEMAX);
ND_PRINT((ndo, " size"));
INTOUT();
ND_PRINT((ndo, " flags"));
INTOUT();
ND_PRINT((ndo, " date"));
INTOUT();
break;
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|bos]"));
}
/*
* Handle replies to the AFS BOS Service
*/
static void
bos_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
const struct rx_header *rxh;
if (length <= (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from volser/volint.xg
*/
ND_PRINT((ndo, " bos reply %s", tok2str(bos_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, interpret the response.
*/
if (rxh->type == RX_PACKET_TYPE_DATA)
/* Well, no, not really. Leave this for later */
;
else {
/*
* Otherwise, just print out the return code
*/
ND_PRINT((ndo, " errcode"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|bos]"));
}
/*
* Check to see if this is a Ubik opcode.
*/
static int
is_ubik(uint32_t opcode)
{
if ((opcode >= VOTE_LOW && opcode <= VOTE_HIGH) ||
(opcode >= DISK_LOW && opcode <= DISK_HIGH))
return(1);
else
return(0);
}
/*
* Handle Ubik opcodes to any one of the replicated database services
*/
static void
ubik_print(netdissect_options *ndo,
register const u_char *bp)
{
int ubik_op;
int32_t temp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from ubik/ubik_int.xg
*/
ubik_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " ubik call %s", tok2str(ubik_req, "op#%d", ubik_op)));
/*
* Decode some of the arguments to the Ubik calls
*/
bp += sizeof(struct rx_header) + 4;
switch (ubik_op) {
case 10000: /* Beacon */
ND_TCHECK2(bp[0], 4);
temp = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_PRINT((ndo, " syncsite %s", temp ? "yes" : "no"));
ND_PRINT((ndo, " votestart"));
DATEOUT();
ND_PRINT((ndo, " dbversion"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
break;
case 10003: /* Get sync site */
ND_PRINT((ndo, " site"));
UINTOUT();
break;
case 20000: /* Begin */
case 20001: /* Commit */
case 20007: /* Abort */
case 20008: /* Release locks */
case 20010: /* Writev */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
break;
case 20002: /* Lock */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " file"));
INTOUT();
ND_PRINT((ndo, " pos"));
INTOUT();
ND_PRINT((ndo, " length"));
INTOUT();
temp = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
tok2str(ubik_lock_types, "type %d", temp);
break;
case 20003: /* Write */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " file"));
INTOUT();
ND_PRINT((ndo, " pos"));
INTOUT();
break;
case 20005: /* Get file */
ND_PRINT((ndo, " file"));
INTOUT();
break;
case 20006: /* Send file */
ND_PRINT((ndo, " file"));
INTOUT();
ND_PRINT((ndo, " length"));
INTOUT();
ND_PRINT((ndo, " dbversion"));
UBIK_VERSIONOUT();
break;
case 20009: /* Truncate */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " file"));
INTOUT();
ND_PRINT((ndo, " length"));
INTOUT();
break;
case 20012: /* Set version */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " oldversion"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " newversion"));
UBIK_VERSIONOUT();
break;
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|ubik]"));
}
/*
* Handle Ubik replies to any one of the replicated database services
*/
static void
ubik_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
const struct rx_header *rxh;
if (length < (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the ubik call we're invoking. This table was gleaned
* from ubik/ubik_int.xg
*/
ND_PRINT((ndo, " ubik reply %s", tok2str(ubik_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, print out the arguments to the Ubik calls
*/
if (rxh->type == RX_PACKET_TYPE_DATA)
switch (opcode) {
case 10000: /* Beacon */
ND_PRINT((ndo, " vote no"));
break;
case 20004: /* Get version */
ND_PRINT((ndo, " dbversion"));
UBIK_VERSIONOUT();
break;
default:
;
}
/*
* Otherwise, print out "yes" it it was a beacon packet (because
* that's how yes votes are returned, go figure), otherwise
* just print out the error code.
*/
else
switch (opcode) {
case 10000: /* Beacon */
ND_PRINT((ndo, " vote yes until"));
DATEOUT();
break;
default:
ND_PRINT((ndo, " errcode"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|ubik]"));
}
/*
* Handle RX ACK packets.
*/
static void
rx_ack_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
const struct rx_ackPacket *rxa;
int i, start, last;
uint32_t firstPacket;
if (length < (int)sizeof(struct rx_header))
return;
bp += sizeof(struct rx_header);
/*
* This may seem a little odd .... the rx_ackPacket structure
* contains an array of individual packet acknowledgements
* (used for selective ack/nack), but since it's variable in size,
* we don't want to truncate based on the size of the whole
* rx_ackPacket structure.
*/
ND_TCHECK2(bp[0], sizeof(struct rx_ackPacket) - RX_MAXACKS);
rxa = (const struct rx_ackPacket *) bp;
bp += (sizeof(struct rx_ackPacket) - RX_MAXACKS);
/*
* Print out a few useful things from the ack packet structure
*/
if (ndo->ndo_vflag > 2)
ND_PRINT((ndo, " bufspace %d maxskew %d",
(int) EXTRACT_16BITS(&rxa->bufferSpace),
(int) EXTRACT_16BITS(&rxa->maxSkew)));
firstPacket = EXTRACT_32BITS(&rxa->firstPacket);
ND_PRINT((ndo, " first %d serial %d reason %s",
firstPacket, EXTRACT_32BITS(&rxa->serial),
tok2str(rx_ack_reasons, "#%d", (int) rxa->reason)));
/*
* Okay, now we print out the ack array. The way _this_ works
* is that we start at "first", and step through the ack array.
* If we have a contiguous range of acks/nacks, try to
* collapse them into a range.
*
* If you're really clever, you might have noticed that this
* doesn't seem quite correct. Specifically, due to structure
* padding, sizeof(struct rx_ackPacket) - RX_MAXACKS won't actually
* yield the start of the ack array (because RX_MAXACKS is 255
* and the structure will likely get padded to a 2 or 4 byte
* boundary). However, this is the way it's implemented inside
* of AFS - the start of the extra fields are at
* sizeof(struct rx_ackPacket) - RX_MAXACKS + nAcks, which _isn't_
* the exact start of the ack array. Sigh. That's why we aren't
* using bp, but instead use rxa->acks[]. But nAcks gets added
* to bp after this, so bp ends up at the right spot. Go figure.
*/
if (rxa->nAcks != 0) {
ND_TCHECK2(bp[0], rxa->nAcks);
/*
* Sigh, this is gross, but it seems to work to collapse
* ranges correctly.
*/
for (i = 0, start = last = -2; i < rxa->nAcks; i++)
if (rxa->acks[i] == RX_ACK_TYPE_ACK) {
/*
* I figured this deserved _some_ explanation.
* First, print "acked" and the packet seq
* number if this is the first time we've
* seen an acked packet.
*/
if (last == -2) {
ND_PRINT((ndo, " acked %d", firstPacket + i));
start = i;
}
/*
* Otherwise, if there is a skip in
* the range (such as an nacked packet in
* the middle of some acked packets),
* then print the current packet number
* seperated from the last number by
* a comma.
*/
else if (last != i - 1) {
ND_PRINT((ndo, ",%d", firstPacket + i));
start = i;
}
/*
* We always set last to the value of
* the last ack we saw. Conversely, start
* is set to the value of the first ack
* we saw in a range.
*/
last = i;
/*
* Okay, this bit a code gets executed when
* we hit a nack ... in _this_ case we
* want to print out the range of packets
* that were acked, so we need to print
* the _previous_ packet number seperated
* from the first by a dash (-). Since we
* already printed the first packet above,
* just print the final packet. Don't
* do this if there will be a single-length
* range.
*/
} else if (last == i - 1 && start != last)
ND_PRINT((ndo, "-%d", firstPacket + i - 1));
/*
* So, what's going on here? We ran off the end of the
* ack list, and if we got a range we need to finish it up.
* So we need to determine if the last packet in the list
* was an ack (if so, then last will be set to it) and
* we need to see if the last range didn't start with the
* last packet (because if it _did_, then that would mean
* that the packet number has already been printed and
* we don't need to print it again).
*/
if (last == i - 1 && start != last)
ND_PRINT((ndo, "-%d", firstPacket + i - 1));
/*
* Same as above, just without comments
*/
for (i = 0, start = last = -2; i < rxa->nAcks; i++)
if (rxa->acks[i] == RX_ACK_TYPE_NACK) {
if (last == -2) {
ND_PRINT((ndo, " nacked %d", firstPacket + i));
start = i;
} else if (last != i - 1) {
ND_PRINT((ndo, ",%d", firstPacket + i));
start = i;
}
last = i;
} else if (last == i - 1 && start != last)
ND_PRINT((ndo, "-%d", firstPacket + i - 1));
if (last == i - 1 && start != last)
ND_PRINT((ndo, "-%d", firstPacket + i - 1));
bp += rxa->nAcks;
}
/*
* These are optional fields; depending on your version of AFS,
* you may or may not see them
*/
#define TRUNCRET(n) if (ndo->ndo_snapend - bp + 1 <= n) return;
if (ndo->ndo_vflag > 1) {
TRUNCRET(4);
ND_PRINT((ndo, " ifmtu"));
INTOUT();
TRUNCRET(4);
ND_PRINT((ndo, " maxmtu"));
INTOUT();
TRUNCRET(4);
ND_PRINT((ndo, " rwind"));
INTOUT();
TRUNCRET(4);
ND_PRINT((ndo, " maxpackets"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|ack]"));
}
#undef TRUNCRET
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2725_0 |
crossvul-cpp_data_bad_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)
csum = csum_sub(csum,
csum_partial(skb_transport_header(skb) + tlen,
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/bad_3176_0 |
crossvul-cpp_data_good_4831_0 | ////////////////////////////////////////////////////////////////////////////
// **** WAVPACK **** //
// Hybrid Lossless Wavefile Compressor //
// Copyright (c) 1998 - 2016 David Bryant. //
// All Rights Reserved. //
// Distributed under the BSD Software License (see license.txt) //
////////////////////////////////////////////////////////////////////////////
// open_utils.c
// This module provides all the code required to open an existing WavPack file
// for reading by using a reader callback mechanism (NOT a filename). This
// includes the code required to find and parse WavPack blocks, process any
// included metadata, and queue up the bitstreams containing the encoded audio
// data. It does not the actual code to unpack audio data and this was done so
// that programs that just want to query WavPack files for information (like,
// for example, taggers) don't need to link in a lot of unnecessary code.
#include <stdlib.h>
#include <string.h>
#include "wavpack_local.h"
// This function is identical to WavpackOpenFileInput() except that instead
// of providing a filename to open, the caller provides a pointer to a set of
// reader callbacks and instances of up to two streams. The first of these
// streams is required and contains the regular WavPack data stream; the second
// contains the "correction" file if desired. Unlike the standard open
// function which handles the correction file transparently, in this case it
// is the responsibility of the caller to be aware of correction files.
static int seek_eof_information (WavpackContext *wpc, int64_t *final_index, int get_wrapper);
WavpackContext *WavpackOpenFileInputEx64 (WavpackStreamReader64 *reader, void *wv_id, void *wvc_id, char *error, int flags, int norm_offset)
{
WavpackContext *wpc = malloc (sizeof (WavpackContext));
WavpackStream *wps;
int num_blocks = 0;
unsigned char first_byte;
uint32_t bcount;
if (!wpc) {
if (error) strcpy (error, "can't allocate memory");
return NULL;
}
CLEAR (*wpc);
wpc->wv_in = wv_id;
wpc->wvc_in = wvc_id;
wpc->reader = reader;
wpc->total_samples = -1;
wpc->norm_offset = norm_offset;
wpc->max_streams = OLD_MAX_STREAMS; // use this until overwritten with actual number
wpc->open_flags = flags;
wpc->filelen = wpc->reader->get_length (wpc->wv_in);
#ifndef NO_TAGS
if ((flags & (OPEN_TAGS | OPEN_EDIT_TAGS)) && wpc->reader->can_seek (wpc->wv_in)) {
load_tag (wpc);
wpc->reader->set_pos_abs (wpc->wv_in, 0);
if ((flags & OPEN_EDIT_TAGS) && !editable_tag (&wpc->m_tag)) {
if (error) strcpy (error, "can't edit tags located at the beginning of files!");
return WavpackCloseFile (wpc);
}
}
#endif
if (wpc->reader->read_bytes (wpc->wv_in, &first_byte, 1) != 1) {
if (error) strcpy (error, "can't read all of WavPack file!");
return WavpackCloseFile (wpc);
}
wpc->reader->push_back_byte (wpc->wv_in, first_byte);
if (first_byte == 'R') {
#ifdef ENABLE_LEGACY
return open_file3 (wpc, error);
#else
if (error) strcpy (error, "this legacy WavPack file is deprecated, use version 4.80.0 to transcode");
return WavpackCloseFile (wpc);
#endif
}
wpc->streams = malloc ((wpc->num_streams = 1) * sizeof (wpc->streams [0]));
if (!wpc->streams) {
if (error) strcpy (error, "can't allocate memory");
return WavpackCloseFile (wpc);
}
wpc->streams [0] = wps = malloc (sizeof (WavpackStream));
if (!wps) {
if (error) strcpy (error, "can't allocate memory");
return WavpackCloseFile (wpc);
}
CLEAR (*wps);
while (!wps->wphdr.block_samples) {
wpc->filepos = wpc->reader->get_pos (wpc->wv_in);
bcount = read_next_header (wpc->reader, wpc->wv_in, &wps->wphdr);
if (bcount == (uint32_t) -1 ||
(!wps->wphdr.block_samples && num_blocks++ > 16)) {
if (error) strcpy (error, "not compatible with this version of WavPack file!");
return WavpackCloseFile (wpc);
}
wpc->filepos += bcount;
wps->blockbuff = malloc (wps->wphdr.ckSize + 8);
if (!wps->blockbuff) {
if (error) strcpy (error, "can't allocate memory");
return WavpackCloseFile (wpc);
}
memcpy (wps->blockbuff, &wps->wphdr, 32);
if (wpc->reader->read_bytes (wpc->wv_in, wps->blockbuff + 32, wps->wphdr.ckSize - 24) != wps->wphdr.ckSize - 24) {
if (error) strcpy (error, "can't read all of WavPack file!");
return WavpackCloseFile (wpc);
}
// if block does not verify, flag error, free buffer, and continue
if (!WavpackVerifySingleBlock (wps->blockbuff, !(flags & OPEN_NO_CHECKSUM))) {
wps->wphdr.block_samples = 0;
free (wps->blockbuff);
wps->blockbuff = NULL;
wpc->crc_errors++;
continue;
}
wps->init_done = FALSE;
if (wps->wphdr.block_samples) {
if (flags & OPEN_STREAMING)
SET_BLOCK_INDEX (wps->wphdr, 0);
else if (wpc->total_samples == -1) {
if (GET_BLOCK_INDEX (wps->wphdr) || GET_TOTAL_SAMPLES (wps->wphdr) == -1) {
wpc->initial_index = GET_BLOCK_INDEX (wps->wphdr);
SET_BLOCK_INDEX (wps->wphdr, 0);
if (wpc->reader->can_seek (wpc->wv_in)) {
int64_t final_index = -1;
seek_eof_information (wpc, &final_index, FALSE);
if (final_index != -1)
wpc->total_samples = final_index - wpc->initial_index;
}
}
else
wpc->total_samples = GET_TOTAL_SAMPLES (wps->wphdr);
}
}
else if (wpc->total_samples == -1 && !GET_BLOCK_INDEX (wps->wphdr) && GET_TOTAL_SAMPLES (wps->wphdr))
wpc->total_samples = GET_TOTAL_SAMPLES (wps->wphdr);
if (wpc->wvc_in && wps->wphdr.block_samples && (wps->wphdr.flags & HYBRID_FLAG)) {
unsigned char ch;
if (wpc->reader->read_bytes (wpc->wvc_in, &ch, 1) == 1) {
wpc->reader->push_back_byte (wpc->wvc_in, ch);
wpc->file2len = wpc->reader->get_length (wpc->wvc_in);
wpc->wvc_flag = TRUE;
}
}
if (wpc->wvc_flag && !read_wvc_block (wpc)) {
if (error) strcpy (error, "not compatible with this version of correction file!");
return WavpackCloseFile (wpc);
}
if (!wps->init_done && !unpack_init (wpc)) {
if (error) strcpy (error, wpc->error_message [0] ? wpc->error_message :
"not compatible with this version of WavPack file!");
return WavpackCloseFile (wpc);
}
wps->init_done = TRUE;
}
wpc->config.flags &= ~0xff;
wpc->config.flags |= wps->wphdr.flags & 0xff;
if (!wpc->config.num_channels) {
wpc->config.num_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2;
wpc->config.channel_mask = 0x5 - wpc->config.num_channels;
}
if ((flags & OPEN_2CH_MAX) && !(wps->wphdr.flags & FINAL_BLOCK))
wpc->reduced_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2;
if (wps->wphdr.flags & DSD_FLAG) {
#ifdef ENABLE_DSD
if (flags & OPEN_DSD_NATIVE) {
wpc->config.bytes_per_sample = 1;
wpc->config.bits_per_sample = 8;
}
else if (flags & OPEN_DSD_AS_PCM) {
wpc->decimation_context = decimate_dsd_init (wpc->reduced_channels ?
wpc->reduced_channels : wpc->config.num_channels);
wpc->config.bytes_per_sample = 3;
wpc->config.bits_per_sample = 24;
}
else {
if (error) strcpy (error, "not configured to handle DSD WavPack files!");
return WavpackCloseFile (wpc);
}
#else
if (error) strcpy (error, "not configured to handle DSD WavPack files!");
return WavpackCloseFile (wpc);
#endif
}
else {
wpc->config.bytes_per_sample = (wps->wphdr.flags & BYTES_STORED) + 1;
wpc->config.float_norm_exp = wps->float_norm_exp;
wpc->config.bits_per_sample = (wpc->config.bytes_per_sample * 8) -
((wps->wphdr.flags & SHIFT_MASK) >> SHIFT_LSB);
}
if (!wpc->config.sample_rate) {
if (!wps->wphdr.block_samples || (wps->wphdr.flags & SRATE_MASK) == SRATE_MASK)
wpc->config.sample_rate = 44100;
else
wpc->config.sample_rate = sample_rates [(wps->wphdr.flags & SRATE_MASK) >> SRATE_LSB];
}
return wpc;
}
// This function returns the major version number of the WavPack program
// (or library) that created the open file. Currently, this can be 1 to 5.
// Minor versions are not recorded in WavPack files.
int WavpackGetVersion (WavpackContext *wpc)
{
if (wpc) {
#ifdef ENABLE_LEGACY
if (wpc->stream3)
return get_version3 (wpc);
#endif
return wpc->version_five ? 5 : 4;
}
return 0;
}
// Return the file format specified in the call to WavpackSetFileInformation()
// when the file was created. For all files created prior to WavPack 5.0 this
// will 0 (WP_FORMAT_WAV).
unsigned char WavpackGetFileFormat (WavpackContext *wpc)
{
return wpc->file_format;
}
// Return a string representing the recommended file extension for the open
// WavPack file. For all files created prior to WavPack 5.0 this will be "wav",
// even for raw files with no RIFF into. This string is specified in the
// call to WavpackSetFileInformation() when the file was created.
char *WavpackGetFileExtension (WavpackContext *wpc)
{
if (wpc && wpc->file_extension [0])
return wpc->file_extension;
else
return "wav";
}
// This function initializes everything required to unpack a WavPack block
// and must be called before unpack_samples() is called to obtain audio data.
// It is assumed that the WavpackHeader has been read into the wps->wphdr
// (in the current WavpackStream) and that the entire block has been read at
// wps->blockbuff. If a correction file is available (wpc->wvc_flag = TRUE)
// then the corresponding correction block must be read into wps->block2buff
// and its WavpackHeader has overwritten the header at wps->wphdr. This is
// where all the metadata blocks are scanned including those that contain
// bitstream data.
static int read_metadata_buff (WavpackMetadata *wpmd, unsigned char *blockbuff, unsigned char **buffptr);
static int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd);
static void bs_open_read (Bitstream *bs, void *buffer_start, void *buffer_end);
int unpack_init (WavpackContext *wpc)
{
WavpackStream *wps = wpc->streams [wpc->current_stream];
unsigned char *blockptr, *block2ptr;
WavpackMetadata wpmd;
wps->num_terms = 0;
wps->mute_error = FALSE;
wps->crc = wps->crc_x = 0xffffffff;
wps->dsd.ready = 0;
CLEAR (wps->wvbits);
CLEAR (wps->wvcbits);
CLEAR (wps->wvxbits);
CLEAR (wps->decorr_passes);
CLEAR (wps->dc);
CLEAR (wps->w);
if (!(wps->wphdr.flags & MONO_FLAG) && wpc->config.num_channels && wps->wphdr.block_samples &&
(wpc->reduced_channels == 1 || wpc->config.num_channels == 1)) {
wps->mute_error = TRUE;
return FALSE;
}
if ((wps->wphdr.flags & UNKNOWN_FLAGS) || (wps->wphdr.flags & MONO_DATA) == MONO_DATA) {
wps->mute_error = TRUE;
return FALSE;
}
blockptr = wps->blockbuff + sizeof (WavpackHeader);
while (read_metadata_buff (&wpmd, wps->blockbuff, &blockptr))
if (!process_metadata (wpc, &wpmd)) {
wps->mute_error = TRUE;
return FALSE;
}
if (wps->wphdr.block_samples && wpc->wvc_flag && wps->block2buff) {
block2ptr = wps->block2buff + sizeof (WavpackHeader);
while (read_metadata_buff (&wpmd, wps->block2buff, &block2ptr))
if (!process_metadata (wpc, &wpmd)) {
wps->mute_error = TRUE;
return FALSE;
}
}
if (wps->wphdr.block_samples && ((wps->wphdr.flags & DSD_FLAG) ? !wps->dsd.ready : !bs_is_open (&wps->wvbits))) {
if (bs_is_open (&wps->wvcbits))
strcpy (wpc->error_message, "can't unpack correction files alone!");
wps->mute_error = TRUE;
return FALSE;
}
if (wps->wphdr.block_samples && !bs_is_open (&wps->wvxbits)) {
if ((wps->wphdr.flags & INT32_DATA) && wps->int32_sent_bits)
wpc->lossy_blocks = TRUE;
if ((wps->wphdr.flags & FLOAT_DATA) &&
wps->float_flags & (FLOAT_EXCEPTIONS | FLOAT_ZEROS_SENT | FLOAT_SHIFT_SENT | FLOAT_SHIFT_SAME))
wpc->lossy_blocks = TRUE;
}
if (wps->wphdr.block_samples)
wps->sample_index = GET_BLOCK_INDEX (wps->wphdr);
return TRUE;
}
//////////////////////////////// matadata handlers ///////////////////////////////
// These functions handle specific metadata types and are called directly
// during WavPack block parsing by process_metadata() at the bottom.
// This function initialzes the main bitstream for audio samples, which must
// be in the "wv" file.
static int init_wv_bitstream (WavpackStream *wps, WavpackMetadata *wpmd)
{
if (!wpmd->byte_length || (wpmd->byte_length & 1))
return FALSE;
bs_open_read (&wps->wvbits, wpmd->data, (unsigned char *) wpmd->data + wpmd->byte_length);
return TRUE;
}
// This function initialzes the "correction" bitstream for audio samples,
// which currently must be in the "wvc" file.
static int init_wvc_bitstream (WavpackStream *wps, WavpackMetadata *wpmd)
{
if (!wpmd->byte_length || (wpmd->byte_length & 1))
return FALSE;
bs_open_read (&wps->wvcbits, wpmd->data, (unsigned char *) wpmd->data + wpmd->byte_length);
return TRUE;
}
// This function initialzes the "extra" bitstream for audio samples which
// contains the information required to losslessly decompress 32-bit float data
// or integer data that exceeds 24 bits. This bitstream is in the "wv" file
// for pure lossless data or the "wvc" file for hybrid lossless. This data
// would not be used for hybrid lossy mode. There is also a 32-bit CRC stored
// in the first 4 bytes of these blocks.
static int init_wvx_bitstream (WavpackStream *wps, WavpackMetadata *wpmd)
{
unsigned char *cp = wpmd->data;
if (wpmd->byte_length <= 4 || (wpmd->byte_length & 1))
return FALSE;
wps->crc_wvx = *cp++;
wps->crc_wvx |= (int32_t) *cp++ << 8;
wps->crc_wvx |= (int32_t) *cp++ << 16;
wps->crc_wvx |= (int32_t) *cp++ << 24;
bs_open_read (&wps->wvxbits, cp, (unsigned char *) wpmd->data + wpmd->byte_length);
return TRUE;
}
// Read the int32 data from the specified metadata into the specified stream.
// This data is used for integer data that has more than 24 bits of magnitude
// or, in some cases, used to eliminate redundant bits from any audio stream.
static int read_int32_info (WavpackStream *wps, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
char *byteptr = wpmd->data;
if (bytecnt != 4)
return FALSE;
wps->int32_sent_bits = *byteptr++;
wps->int32_zeros = *byteptr++;
wps->int32_ones = *byteptr++;
wps->int32_dups = *byteptr;
return TRUE;
}
static int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
char *byteptr = wpmd->data;
if (bytecnt != 4)
return FALSE;
wps->float_flags = *byteptr++;
wps->float_shift = *byteptr++;
wps->float_max_exp = *byteptr++;
wps->float_norm_exp = *byteptr;
return TRUE;
}
// Read multichannel information from metadata. The first byte is the total
// number of channels and the following bytes represent the channel_mask
// as described for Microsoft WAVEFORMATEX.
static int read_channel_info (WavpackContext *wpc, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length, shift = 0, mask_bits;
unsigned char *byteptr = wpmd->data;
uint32_t mask = 0;
if (!bytecnt || bytecnt > 7)
return FALSE;
if (!wpc->config.num_channels) {
// if bytecnt is 6 or 7 we are using new configuration with "unlimited" streams
if (bytecnt >= 6) {
wpc->config.num_channels = (byteptr [0] | ((byteptr [2] & 0xf) << 8)) + 1;
wpc->max_streams = (byteptr [1] | ((byteptr [2] & 0xf0) << 4)) + 1;
if (wpc->config.num_channels < wpc->max_streams)
return FALSE;
byteptr += 3;
mask = *byteptr++;
mask |= (uint32_t) *byteptr++ << 8;
mask |= (uint32_t) *byteptr++ << 16;
if (bytecnt == 7) // this was introduced in 5.0
mask |= (uint32_t) *byteptr << 24;
}
else {
wpc->config.num_channels = *byteptr++;
while (--bytecnt) {
mask |= (uint32_t) *byteptr++ << shift;
shift += 8;
}
}
if (wpc->config.num_channels > wpc->max_streams * 2)
return FALSE;
wpc->config.channel_mask = mask;
for (mask_bits = 0; mask; mask >>= 1)
if ((mask & 1) && ++mask_bits > wpc->config.num_channels)
return FALSE;
}
return TRUE;
}
// Read multichannel identity information from metadata. Data is an array of
// unsigned characters representing any channels in the file that DO NOT
// match one the 18 Microsoft standard channels (and are represented in the
// channel mask). A value of 0 is not allowed and 0xff means an unknown or
// undefined channel identity.
static int read_channel_identities (WavpackContext *wpc, WavpackMetadata *wpmd)
{
if (!wpc->channel_identities) {
wpc->channel_identities = malloc (wpmd->byte_length + 1);
memcpy (wpc->channel_identities, wpmd->data, wpmd->byte_length);
wpc->channel_identities [wpmd->byte_length] = 0;
}
return TRUE;
}
// Read configuration information from metadata.
static int read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
unsigned char *byteptr = wpmd->data;
if (bytecnt >= 3) {
wpc->config.flags &= 0xff;
wpc->config.flags |= (int32_t) *byteptr++ << 8;
wpc->config.flags |= (int32_t) *byteptr++ << 16;
wpc->config.flags |= (int32_t) *byteptr++ << 24;
bytecnt -= 3;
if (bytecnt && (wpc->config.flags & CONFIG_EXTRA_MODE)) {
wpc->config.xmode = *byteptr++;
bytecnt--;
}
// we used an extra config byte here for the 5.0.0 alpha, so still
// honor it now (but this has been replaced with NEW_CONFIG)
if (bytecnt) {
wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr;
wpc->version_five = 1;
}
}
return TRUE;
}
// Read "new" configuration information from metadata.
static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
unsigned char *byteptr = wpmd->data;
wpc->version_five = 1; // just having this block signals version 5.0
wpc->file_format = wpc->config.qmode = wpc->channel_layout = 0;
if (wpc->channel_reordering) {
free (wpc->channel_reordering);
wpc->channel_reordering = NULL;
}
// if there's any data, the first two bytes are file_format and qmode flags
if (bytecnt >= 2) {
wpc->file_format = *byteptr++;
wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++;
bytecnt -= 2;
// another byte indicates a channel layout
if (bytecnt) {
int nchans, i;
wpc->channel_layout = (int32_t) *byteptr++ << 16;
bytecnt--;
// another byte means we have a channel count for the layout and maybe a reordering
if (bytecnt) {
wpc->channel_layout += nchans = *byteptr++;
bytecnt--;
// any more means there's a reordering string
if (bytecnt) {
if (bytecnt > nchans)
return FALSE;
wpc->channel_reordering = malloc (nchans);
// note that redundant reordering info is not stored, so we fill in the rest
if (wpc->channel_reordering) {
for (i = 0; i < nchans; ++i)
if (bytecnt) {
wpc->channel_reordering [i] = *byteptr++;
if (wpc->channel_reordering [i] >= nchans) // make sure index is in range
wpc->channel_reordering [i] = 0;
bytecnt--;
}
else
wpc->channel_reordering [i] = i;
}
}
}
else
wpc->channel_layout += wpc->config.num_channels;
}
}
return TRUE;
}
// Read non-standard sampling rate from metadata.
static int read_sample_rate (WavpackContext *wpc, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
unsigned char *byteptr = wpmd->data;
if (bytecnt == 3 || bytecnt == 4) {
wpc->config.sample_rate = (int32_t) *byteptr++;
wpc->config.sample_rate |= (int32_t) *byteptr++ << 8;
wpc->config.sample_rate |= (int32_t) *byteptr++ << 16;
// for sampling rates > 16777215 (non-audio probably, or ...)
if (bytecnt == 4)
wpc->config.sample_rate |= (int32_t) (*byteptr & 0x7f) << 24;
}
return TRUE;
}
// Read wrapper data from metadata. Currently, this consists of the RIFF
// header and trailer that wav files contain around the audio data but could
// be used for other formats as well. Because WavPack files contain all the
// information required for decoding and playback, this data can probably
// be ignored except when an exact wavefile restoration is needed.
static int read_wrapper_data (WavpackContext *wpc, WavpackMetadata *wpmd)
{
if ((wpc->open_flags & OPEN_WRAPPER) && wpc->wrapper_bytes < MAX_WRAPPER_BYTES && wpmd->byte_length) {
wpc->wrapper_data = realloc (wpc->wrapper_data, wpc->wrapper_bytes + wpmd->byte_length);
if (!wpc->wrapper_data)
return FALSE;
memcpy (wpc->wrapper_data + wpc->wrapper_bytes, wpmd->data, wpmd->byte_length);
wpc->wrapper_bytes += wpmd->byte_length;
}
return TRUE;
}
static int read_metadata_buff (WavpackMetadata *wpmd, unsigned char *blockbuff, unsigned char **buffptr)
{
WavpackHeader *wphdr = (WavpackHeader *) blockbuff;
unsigned char *buffend = blockbuff + wphdr->ckSize + 8;
if (buffend - *buffptr < 2)
return FALSE;
wpmd->id = *(*buffptr)++;
wpmd->byte_length = *(*buffptr)++ << 1;
if (wpmd->id & ID_LARGE) {
wpmd->id &= ~ID_LARGE;
if (buffend - *buffptr < 2)
return FALSE;
wpmd->byte_length += *(*buffptr)++ << 9;
wpmd->byte_length += *(*buffptr)++ << 17;
}
if (wpmd->id & ID_ODD_SIZE) {
if (!wpmd->byte_length) // odd size and zero length makes no sense
return FALSE;
wpmd->id &= ~ID_ODD_SIZE;
wpmd->byte_length--;
}
if (wpmd->byte_length) {
if (buffend - *buffptr < wpmd->byte_length + (wpmd->byte_length & 1)) {
wpmd->data = NULL;
return FALSE;
}
wpmd->data = *buffptr;
(*buffptr) += wpmd->byte_length + (wpmd->byte_length & 1);
}
else
wpmd->data = NULL;
return TRUE;
}
static int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd)
{
WavpackStream *wps = wpc->streams [wpc->current_stream];
switch (wpmd->id) {
case ID_DUMMY:
return TRUE;
case ID_DECORR_TERMS:
return read_decorr_terms (wps, wpmd);
case ID_DECORR_WEIGHTS:
return read_decorr_weights (wps, wpmd);
case ID_DECORR_SAMPLES:
return read_decorr_samples (wps, wpmd);
case ID_ENTROPY_VARS:
return read_entropy_vars (wps, wpmd);
case ID_HYBRID_PROFILE:
return read_hybrid_profile (wps, wpmd);
case ID_SHAPING_WEIGHTS:
return read_shaping_info (wps, wpmd);
case ID_FLOAT_INFO:
return read_float_info (wps, wpmd);
case ID_INT32_INFO:
return read_int32_info (wps, wpmd);
case ID_CHANNEL_INFO:
return read_channel_info (wpc, wpmd);
case ID_CHANNEL_IDENTITIES:
return read_channel_identities (wpc, wpmd);
case ID_CONFIG_BLOCK:
return read_config_info (wpc, wpmd);
case ID_NEW_CONFIG_BLOCK:
return read_new_config_info (wpc, wpmd);
case ID_SAMPLE_RATE:
return read_sample_rate (wpc, wpmd);
case ID_WV_BITSTREAM:
return init_wv_bitstream (wps, wpmd);
case ID_WVC_BITSTREAM:
return init_wvc_bitstream (wps, wpmd);
case ID_WVX_BITSTREAM:
return init_wvx_bitstream (wps, wpmd);
case ID_DSD_BLOCK:
#ifdef ENABLE_DSD
return init_dsd_block (wpc, wpmd);
#else
strcpy (wpc->error_message, "not configured to handle DSD WavPack files!");
return FALSE;
#endif
case ID_ALT_HEADER: case ID_ALT_TRAILER:
if (!(wpc->open_flags & OPEN_ALT_TYPES))
return TRUE;
case ID_RIFF_HEADER: case ID_RIFF_TRAILER:
return read_wrapper_data (wpc, wpmd);
case ID_ALT_MD5_CHECKSUM:
if (!(wpc->open_flags & OPEN_ALT_TYPES))
return TRUE;
case ID_MD5_CHECKSUM:
if (wpmd->byte_length == 16) {
memcpy (wpc->config.md5_checksum, wpmd->data, 16);
wpc->config.flags |= CONFIG_MD5_CHECKSUM;
wpc->config.md5_read = 1;
}
return TRUE;
case ID_ALT_EXTENSION:
if (wpmd->byte_length && wpmd->byte_length < sizeof (wpc->file_extension)) {
memcpy (wpc->file_extension, wpmd->data, wpmd->byte_length);
wpc->file_extension [wpmd->byte_length] = 0;
}
return TRUE;
// we don't actually verify the checksum here (it's done right after the
// block is read), but it's a good indicator of version 5 files
case ID_BLOCK_CHECKSUM:
wpc->version_five = 1;
return TRUE;
default:
return (wpmd->id & ID_OPTIONAL_DATA) ? TRUE : FALSE;
}
}
//////////////////////////////// bitstream management ///////////////////////////////
// Open the specified BitStream and associate with the specified buffer.
static void bs_read (Bitstream *bs);
static void bs_open_read (Bitstream *bs, void *buffer_start, void *buffer_end)
{
bs->error = bs->sr = bs->bc = 0;
bs->ptr = (bs->buf = buffer_start) - 1;
bs->end = buffer_end;
bs->wrap = bs_read;
}
// This function is only called from the getbit() and getbits() macros when
// the BitStream has been exhausted and more data is required. Sinve these
// bistreams no longer access files, this function simple sets an error and
// resets the buffer.
static void bs_read (Bitstream *bs)
{
bs->ptr = bs->buf;
bs->error = 1;
}
// This function is called to close the bitstream. It returns the number of
// full bytes actually read as bits.
uint32_t bs_close_read (Bitstream *bs)
{
uint32_t bytes_read;
if (bs->bc < sizeof (*(bs->ptr)) * 8)
bs->ptr++;
bytes_read = (uint32_t)(bs->ptr - bs->buf) * sizeof (*(bs->ptr));
if (!(bytes_read & 1))
++bytes_read;
CLEAR (*bs);
return bytes_read;
}
// Normally the trailing wrapper will not be available when a WavPack file is first
// opened for reading because it is stored in the final block of the file. This
// function forces a seek to the end of the file to pick up any trailing wrapper
// stored there (then use WavPackGetWrapper**() to obtain). This can obviously only
// be used for seekable files (not pipes) and is not available for pre-4.0 WavPack
// files.
void WavpackSeekTrailingWrapper (WavpackContext *wpc)
{
if ((wpc->open_flags & OPEN_WRAPPER) &&
wpc->reader->can_seek (wpc->wv_in) && !wpc->stream3)
seek_eof_information (wpc, NULL, TRUE);
}
// Get any MD5 checksum stored in the metadata (should be called after reading
// last sample or an extra seek will occur). A return value of FALSE indicates
// that no MD5 checksum was stored.
int WavpackGetMD5Sum (WavpackContext *wpc, unsigned char data [16])
{
if (wpc->config.flags & CONFIG_MD5_CHECKSUM) {
if (!wpc->config.md5_read && wpc->reader->can_seek (wpc->wv_in))
seek_eof_information (wpc, NULL, FALSE);
if (wpc->config.md5_read) {
memcpy (data, wpc->config.md5_checksum, 16);
return TRUE;
}
}
return FALSE;
}
// Read from current file position until a valid 32-byte WavPack 4.0 header is
// found and read into the specified pointer. The number of bytes skipped is
// returned. If no WavPack header is found within 1 meg, then a -1 is returned
// to indicate the error. No additional bytes are read past the header and it
// is returned in the processor's native endian mode. Seeking is not required.
uint32_t read_next_header (WavpackStreamReader64 *reader, void *id, WavpackHeader *wphdr)
{
unsigned char buffer [sizeof (*wphdr)], *sp = buffer + sizeof (*wphdr), *ep = sp;
uint32_t bytes_skipped = 0;
int bleft;
while (1) {
if (sp < ep) {
bleft = (int)(ep - sp);
memmove (buffer, sp, bleft);
}
else
bleft = 0;
if (reader->read_bytes (id, buffer + bleft, sizeof (*wphdr) - bleft) != sizeof (*wphdr) - bleft)
return -1;
sp = buffer;
if (*sp++ == 'w' && *sp == 'v' && *++sp == 'p' && *++sp == 'k' &&
!(*++sp & 1) && sp [2] < 16 && !sp [3] && (sp [2] || sp [1] || *sp >= 24) && sp [5] == 4 &&
sp [4] >= (MIN_STREAM_VERS & 0xff) && sp [4] <= (MAX_STREAM_VERS & 0xff) && sp [18] < 3 && !sp [19]) {
memcpy (wphdr, buffer, sizeof (*wphdr));
WavpackLittleEndianToNative (wphdr, WavpackHeaderFormat);
return bytes_skipped;
}
while (sp < ep && *sp != 'w')
sp++;
if ((bytes_skipped += (uint32_t)(sp - buffer)) > 1024 * 1024)
return -1;
}
}
// Compare the regular wv file block header to a potential matching wvc
// file block header and return action code based on analysis:
//
// 0 = use wvc block (assuming rest of block is readable)
// 1 = bad match; try to read next wvc block
// -1 = bad match; ignore wvc file for this block and backup fp (if
// possible) and try to use this block next time
static int match_wvc_header (WavpackHeader *wv_hdr, WavpackHeader *wvc_hdr)
{
if (GET_BLOCK_INDEX (*wv_hdr) == GET_BLOCK_INDEX (*wvc_hdr) &&
wv_hdr->block_samples == wvc_hdr->block_samples) {
int wvi = 0, wvci = 0;
if (wv_hdr->flags == wvc_hdr->flags)
return 0;
if (wv_hdr->flags & INITIAL_BLOCK)
wvi -= 1;
if (wv_hdr->flags & FINAL_BLOCK)
wvi += 1;
if (wvc_hdr->flags & INITIAL_BLOCK)
wvci -= 1;
if (wvc_hdr->flags & FINAL_BLOCK)
wvci += 1;
return (wvci - wvi < 0) ? 1 : -1;
}
if (((GET_BLOCK_INDEX (*wvc_hdr) - GET_BLOCK_INDEX (*wv_hdr)) << 24) < 0)
return 1;
else
return -1;
}
// Read the wvc block that matches the regular wv block that has been
// read for the current stream. If an exact match is not found then
// we either keep reading or back up and (possibly) use the block
// later. The skip_wvc flag is set if not matching wvc block is found
// so that we can still decode using only the lossy version (although
// we flag this as an error). A return of FALSE indicates a serious
// error (not just that we missed one wvc block).
int read_wvc_block (WavpackContext *wpc)
{
WavpackStream *wps = wpc->streams [wpc->current_stream];
int64_t bcount, file2pos;
WavpackHeader orig_wphdr;
WavpackHeader wphdr;
int compare_result;
while (1) {
file2pos = wpc->reader->get_pos (wpc->wvc_in);
bcount = read_next_header (wpc->reader, wpc->wvc_in, &wphdr);
if (bcount == (uint32_t) -1) {
wps->wvc_skip = TRUE;
wpc->crc_errors++;
return FALSE;
}
memcpy (&orig_wphdr, &wphdr, 32); // save original header for verify step
if (wpc->open_flags & OPEN_STREAMING)
SET_BLOCK_INDEX (wphdr, wps->sample_index = 0);
else
SET_BLOCK_INDEX (wphdr, GET_BLOCK_INDEX (wphdr) - wpc->initial_index);
if (wphdr.flags & INITIAL_BLOCK)
wpc->file2pos = file2pos + bcount;
compare_result = match_wvc_header (&wps->wphdr, &wphdr);
if (!compare_result) {
wps->block2buff = malloc (wphdr.ckSize + 8);
if (!wps->block2buff)
return FALSE;
if (wpc->reader->read_bytes (wpc->wvc_in, wps->block2buff + 32, wphdr.ckSize - 24) !=
wphdr.ckSize - 24) {
free (wps->block2buff);
wps->block2buff = NULL;
wps->wvc_skip = TRUE;
wpc->crc_errors++;
return FALSE;
}
memcpy (wps->block2buff, &orig_wphdr, 32);
// don't use corrupt blocks
if (!WavpackVerifySingleBlock (wps->block2buff, !(wpc->open_flags & OPEN_NO_CHECKSUM))) {
free (wps->block2buff);
wps->block2buff = NULL;
wps->wvc_skip = TRUE;
wpc->crc_errors++;
return TRUE;
}
wps->wvc_skip = FALSE;
memcpy (wps->block2buff, &wphdr, 32);
memcpy (&wps->wphdr, &wphdr, 32);
return TRUE;
}
else if (compare_result == -1) {
wps->wvc_skip = TRUE;
wpc->reader->set_pos_rel (wpc->wvc_in, -32, SEEK_CUR);
wpc->crc_errors++;
return TRUE;
}
}
}
// This function is used to seek to end of a file to obtain certain information
// that is stored there at the file creation time because it is not known at
// the start. This includes the MD5 sum and and trailing part of the file
// wrapper, and in some rare cases may include the total number of samples in
// the file (although we usually try to back up and write that at the front of
// the file). Note this function restores the file position to its original
// location (and obviously requires a seekable file). The normal return value
// is TRUE indicating no errors, although this does not actually mean that any
// information was retrieved. An error return of FALSE usually means the file
// terminated unexpectedly. Note that this could be used to get all three
// types of information in one go, but it's not actually used that way now.
static int seek_eof_information (WavpackContext *wpc, int64_t *final_index, int get_wrapper)
{
int64_t restore_pos, last_pos = -1;
WavpackStreamReader64 *reader = wpc->reader;
int alt_types = wpc->open_flags & OPEN_ALT_TYPES;
uint32_t blocks = 0, audio_blocks = 0;
void *id = wpc->wv_in;
WavpackHeader wphdr;
restore_pos = reader->get_pos (id); // we restore file position when done
// start 1MB from the end-of-file, or from the start if the file is not that big
if (reader->get_length (id) > 1048576LL)
reader->set_pos_rel (id, -1048576, SEEK_END);
else
reader->set_pos_abs (id, 0);
// Note that we go backward (without parsing inside blocks) until we find a block
// with audio (careful to not get stuck in a loop). Only then do we go forward
// parsing all blocks in their entirety.
while (1) {
uint32_t bcount = read_next_header (reader, id, &wphdr);
int64_t current_pos = reader->get_pos (id);
// if we just got to the same place as last time, we're stuck and need to give up
if (current_pos == last_pos) {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
last_pos = current_pos;
// We enter here if we just read 1 MB without seeing any WavPack block headers.
// Since WavPack blocks are < 1 MB, that means we're in a big APE tag, or we got
// to the end-of-file.
if (bcount == (uint32_t) -1) {
// if we have not seen any blocks at all yet, back up almost 2 MB (or to the
// beginning of the file) and try again
if (!blocks) {
if (current_pos > 2000000LL)
reader->set_pos_rel (id, -2000000, SEEK_CUR);
else
reader->set_pos_abs (id, 0);
continue;
}
// if we have seen WavPack blocks, then this means we've done all we can do here
reader->set_pos_abs (id, restore_pos);
return TRUE;
}
blocks++;
// If the block has audio samples, calculate a final index, although this is not
// final since this may not be the last block with audio. On the other hand, if
// this block does not have audio, and we haven't seen one with audio, we have
// to go back some more.
if (wphdr.block_samples) {
if (final_index)
*final_index = GET_BLOCK_INDEX (wphdr) + wphdr.block_samples;
audio_blocks++;
}
else if (!audio_blocks) {
if (current_pos > 1048576LL)
reader->set_pos_rel (id, -1048576, SEEK_CUR);
else
reader->set_pos_abs (id, 0);
continue;
}
// at this point we have seen at least one block with audio, so we parse the
// entire block looking for MD5 metadata or (conditionally) trailing wrappers
bcount = wphdr.ckSize - sizeof (WavpackHeader) + 8;
while (bcount >= 2) {
unsigned char meta_id, c1, c2;
uint32_t meta_bc, meta_size;
if (reader->read_bytes (id, &meta_id, 1) != 1 ||
reader->read_bytes (id, &c1, 1) != 1) {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
meta_bc = c1 << 1;
bcount -= 2;
if (meta_id & ID_LARGE) {
if (bcount < 2 || reader->read_bytes (id, &c1, 1) != 1 ||
reader->read_bytes (id, &c2, 1) != 1) {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17);
bcount -= 2;
}
meta_size = (meta_id & ID_ODD_SIZE) ? meta_bc - 1 : meta_bc;
meta_id &= ID_UNIQUE;
if (get_wrapper && (meta_id == ID_RIFF_TRAILER || (alt_types && meta_id == ID_ALT_TRAILER)) && meta_bc) {
wpc->wrapper_data = realloc (wpc->wrapper_data, wpc->wrapper_bytes + meta_bc);
if (!wpc->wrapper_data) {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
if (reader->read_bytes (id, wpc->wrapper_data + wpc->wrapper_bytes, meta_bc) == meta_bc)
wpc->wrapper_bytes += meta_size;
else {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
}
else if (meta_id == ID_MD5_CHECKSUM || (alt_types && meta_id == ID_ALT_MD5_CHECKSUM)) {
if (meta_bc == 16 && bcount >= 16) {
if (reader->read_bytes (id, wpc->config.md5_checksum, 16) == 16)
wpc->config.md5_read = TRUE;
else {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
}
else
reader->set_pos_rel (id, meta_bc, SEEK_CUR);
}
else
reader->set_pos_rel (id, meta_bc, SEEK_CUR);
bcount -= meta_bc;
}
}
}
// Quickly verify the referenced block. It is assumed that the WavPack header has been converted
// to native endian format. If a block checksum is performed, that is done in little-endian
// (file) format. It is also assumed that the caller has made sure that the block length
// indicated in the header is correct (we won't overflow the buffer). If a checksum is present,
// then it is checked, otherwise we just check that all the metadata blocks are formatted
// correctly (without looking at their contents). Returns FALSE for bad block.
int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum)
{
WavpackHeader *wphdr = (WavpackHeader *) buffer;
uint32_t checksum_passed = 0, bcount, meta_bc;
unsigned char *dp, meta_id, c1, c2;
if (strncmp (wphdr->ckID, "wvpk", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader))
return FALSE;
bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8;
dp = (unsigned char *)(wphdr + 1);
while (bcount >= 2) {
meta_id = *dp++;
c1 = *dp++;
meta_bc = c1 << 1;
bcount -= 2;
if (meta_id & ID_LARGE) {
if (bcount < 2)
return FALSE;
c1 = *dp++;
c2 = *dp++;
meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17);
bcount -= 2;
}
if (bcount < meta_bc)
return FALSE;
if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) {
#ifdef BITSTREAM_SHORTS
uint16_t *csptr = (uint16_t*) buffer;
#else
unsigned char *csptr = buffer;
#endif
int wcount = (int)(dp - 2 - buffer) >> 1;
uint32_t csum = (uint32_t) -1;
if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4)
return FALSE;
#ifdef BITSTREAM_SHORTS
while (wcount--)
csum = (csum * 3) + *csptr++;
#else
WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat);
while (wcount--) {
csum = (csum * 3) + csptr [0] + (csptr [1] << 8);
csptr += 2;
}
WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat);
#endif
if (meta_bc == 4) {
if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff) || *dp++ != ((csum >> 16) & 0xff) || *dp++ != ((csum >> 24) & 0xff))
return FALSE;
}
else {
csum ^= csum >> 16;
if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff))
return FALSE;
}
checksum_passed++;
}
bcount -= meta_bc;
dp += meta_bc;
}
return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4831_0 |
crossvul-cpp_data_bad_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 = 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 = 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/bad_3142_0 |
crossvul-cpp_data_good_140_0 | /* radare - LGPL - Copyright 2009-2018 - nibble, pancake */
#include <assert.h>
#include <stdio.h>
#include <r_types.h>
#include <r_util.h>
#include <r_lib.h>
#include <r_bin.h>
#include <r_io.h>
#include <r_cons.h>
#include "elf/elf.h"
static RBinInfo* info(RBinFile *bf);
//TODO: implement r_bin_symbol_dup() and r_bin_symbol_free ?
static int get_file_type(RBinFile *bf) {
struct Elf_(r_bin_elf_obj_t) *obj = bf->o->bin_obj;
char *type = Elf_(r_bin_elf_get_file_type (obj));
return type? ((!strncmp (type, "CORE", 4)) ? R_BIN_TYPE_CORE : R_BIN_TYPE_DEFAULT) : -1;
}
static RList *maps(RBinFile *bf) {
if (bf && bf->o) {
return Elf_(r_bin_elf_get_maps)(bf->o->bin_obj);
}
return NULL;
}
static char* regstate(RBinFile *bf) {
struct Elf_(r_bin_elf_obj_t) *obj = bf->o->bin_obj;
if (obj->ehdr.e_machine != EM_AARCH64 &&
obj->ehdr.e_machine != EM_ARM &&
obj->ehdr.e_machine != EM_386 &&
obj->ehdr.e_machine != EM_X86_64) {
eprintf ("Cannot retrieve regstate on: %s (not yet supported)\n",
Elf_(r_bin_elf_get_machine_name)(obj));
return NULL;
}
int len = 0;
ut8 *regs = Elf_(r_bin_elf_grab_regstate) (obj, &len);
char *hexregs = (regs && len > 0) ? r_hex_bin2strdup (regs, len) : NULL;
free (regs);
return hexregs;
}
static void setsymord(ELFOBJ* eobj, ut32 ord, RBinSymbol *ptr) {
if (!eobj->symbols_by_ord || ord >= eobj->symbols_by_ord_size) {
return;
}
free (eobj->symbols_by_ord[ord]);
eobj->symbols_by_ord[ord] = r_mem_dup (ptr, sizeof (RBinSymbol));
}
static inline bool setimpord(ELFOBJ* eobj, ut32 ord, RBinImport *ptr) {
if (!eobj->imports_by_ord || ord >= eobj->imports_by_ord_size) {
return false;
}
if (eobj->imports_by_ord[ord]) {
free (eobj->imports_by_ord[ord]->name);
free (eobj->imports_by_ord[ord]);
}
eobj->imports_by_ord[ord] = r_mem_dup (ptr, sizeof (RBinImport));
eobj->imports_by_ord[ord]->name = strdup (ptr->name);
return true;
}
static Sdb* get_sdb(RBinFile *bf) {
RBinObject *o = bf->o;
if (o && o->bin_obj) {
struct Elf_(r_bin_elf_obj_t) *bin = (struct Elf_(r_bin_elf_obj_t) *) o->bin_obj;
return bin->kv;
}
return NULL;
}
static void * load_buffer(RBinFile *bf, RBuffer *buf, ut64 loadaddr, Sdb *sdb) {
struct Elf_(r_bin_elf_obj_t) *res;
if (!buf) {
return NULL;
}
res = Elf_(r_bin_elf_new_buf) (buf, bf->rbin->verbose);
if (res) {
sdb_ns_set (sdb, "info", res->kv);
}
return res;
}
static void * load_bytes(RBinFile *bf, const ut8 *buf, ut64 sz, ut64 loadaddr, Sdb *sdb) {
struct Elf_(r_bin_elf_obj_t) *res;
if (!buf || !sz || sz == UT64_MAX) {
return NULL;
}
RBuffer *tbuf = r_buf_new ();
// NOOOEES must use io!
r_buf_set_bytes (tbuf, buf, sz);
res = Elf_(r_bin_elf_new_buf) (tbuf, bf->rbin->verbose);
if (res) {
sdb_ns_set (sdb, "info", res->kv);
}
r_buf_free (tbuf);
return res;
}
static bool load(RBinFile *bf) {
const ut8 *bytes = bf ? r_buf_buffer (bf->buf) : NULL;
ut64 sz = bf ? r_buf_size (bf->buf): 0;
if (!bf || !bf->o) {
return false;
}
bf->o->bin_obj = load_bytes (bf, bytes, sz, bf->o->loadaddr, bf->sdb);
return bf->o->bin_obj != NULL;
}
static int destroy(RBinFile *bf) {
int i;
ELFOBJ* eobj = bf->o->bin_obj;
if (eobj && eobj->imports_by_ord) {
for (i = 0; i < eobj->imports_by_ord_size; i++) {
RBinImport *imp = eobj->imports_by_ord[i];
if (imp) {
free (imp->name);
free (imp);
eobj->imports_by_ord[i] = NULL;
}
}
R_FREE (eobj->imports_by_ord);
}
Elf_(r_bin_elf_free) ((struct Elf_(r_bin_elf_obj_t)*)bf->o->bin_obj);
return true;
}
static ut64 baddr(RBinFile *bf) {
return Elf_(r_bin_elf_get_baddr) (bf->o->bin_obj);
}
static ut64 boffset(RBinFile *bf) {
return Elf_(r_bin_elf_get_boffset) (bf->o->bin_obj);
}
static RBinAddr* binsym(RBinFile *bf, int sym) {
struct Elf_(r_bin_elf_obj_t)* obj = bf->o->bin_obj;
RBinAddr *ret = NULL;
ut64 addr = 0LL;
switch (sym) {
case R_BIN_SYM_ENTRY:
addr = Elf_(r_bin_elf_get_entry_offset) (bf->o->bin_obj);
break;
case R_BIN_SYM_MAIN:
addr = Elf_(r_bin_elf_get_main_offset) (bf->o->bin_obj);
break;
case R_BIN_SYM_INIT:
addr = Elf_(r_bin_elf_get_init_offset) (bf->o->bin_obj);
break;
case R_BIN_SYM_FINI:
addr = Elf_(r_bin_elf_get_fini_offset) (bf->o->bin_obj);
break;
}
if (addr && addr != UT64_MAX && (ret = R_NEW0 (RBinAddr))) {
struct Elf_(r_bin_elf_obj_t) *bin = bf->o->bin_obj;
bool is_arm = bin->ehdr.e_machine == EM_ARM;
ret->paddr = addr;
ret->vaddr = Elf_(r_bin_elf_p2v) (obj, addr);
if (is_arm && addr & 1) {
ret->bits = 16;
ret->vaddr--;
ret->paddr--;
}
}
return ret;
}
static RList* sections(RBinFile *bf) {
struct Elf_(r_bin_elf_obj_t)* obj = (bf && bf->o)? bf->o->bin_obj : NULL;
struct r_bin_elf_section_t *section = NULL;
int i, num, found_load = 0;
Elf_(Phdr)* phdr = NULL;
RBinSection *ptr = NULL;
RList *ret = NULL;
if (!obj || !(ret = r_list_newf (free))) {
return NULL;
}
//there is not leak in section since they are cached by elf.c
//and freed within Elf_(r_bin_elf_free)
if ((section = Elf_(r_bin_elf_get_sections) (obj))) {
for (i = 0; !section[i].last; i++) {
if (!(ptr = R_NEW0 (RBinSection))) {
break;
}
strncpy (ptr->name, (char*)section[i].name, R_BIN_SIZEOF_STRINGS);
if (strstr (ptr->name, "data") && !strstr (ptr->name, "rel")) {
ptr->is_data = true;
}
ptr->size = section[i].type != SHT_NOBITS ? section[i].size : 0;
ptr->vsize = section[i].size;
ptr->paddr = section[i].offset;
ptr->vaddr = section[i].rva;
ptr->add = !obj->phdr; // Load sections if there is no PHDR
ptr->srwx = 0;
if (R_BIN_ELF_SCN_IS_EXECUTABLE (section[i].flags)) {
ptr->srwx |= R_BIN_SCN_EXECUTABLE;
}
if (R_BIN_ELF_SCN_IS_WRITABLE (section[i].flags)) {
ptr->srwx |= R_BIN_SCN_WRITABLE;
}
if (R_BIN_ELF_SCN_IS_READABLE (section[i].flags)) {
ptr->srwx |= R_BIN_SCN_READABLE;
}
r_list_append (ret, ptr);
}
}
// program headers is another section
num = obj->ehdr.e_phnum;
phdr = obj->phdr;
if (phdr) {
int n = 0;
for (i = 0; i < num; i++) {
if (!(ptr = R_NEW0 (RBinSection))) {
return ret;
}
ptr->add = false;
ptr->size = phdr[i].p_filesz;
ptr->vsize = phdr[i].p_memsz;
ptr->paddr = phdr[i].p_offset;
ptr->vaddr = phdr[i].p_vaddr;
ptr->srwx = phdr[i].p_flags;
switch (phdr[i].p_type) {
case PT_DYNAMIC:
strncpy (ptr->name, "DYNAMIC", R_BIN_SIZEOF_STRINGS);
break;
case PT_LOAD:
snprintf (ptr->name, R_BIN_SIZEOF_STRINGS, "LOAD%d", n++);
found_load = 1;
ptr->add = true;
break;
case PT_INTERP:
strncpy (ptr->name, "INTERP", R_BIN_SIZEOF_STRINGS);
break;
case PT_GNU_STACK:
strncpy (ptr->name, "GNU_STACK", R_BIN_SIZEOF_STRINGS);
break;
case PT_GNU_RELRO:
strncpy (ptr->name, "GNU_RELRO", R_BIN_SIZEOF_STRINGS);
break;
case PT_GNU_EH_FRAME:
strncpy (ptr->name, "GNU_EH_FRAME", R_BIN_SIZEOF_STRINGS);
break;
case PT_PHDR:
strncpy (ptr->name, "PHDR", R_BIN_SIZEOF_STRINGS);
break;
case PT_TLS:
strncpy (ptr->name, "TLS", R_BIN_SIZEOF_STRINGS);
break;
case PT_NOTE:
strncpy (ptr->name, "NOTE", R_BIN_SIZEOF_STRINGS);
break;
default:
strncpy (ptr->name, "UNKNOWN", R_BIN_SIZEOF_STRINGS);
break;
}
ptr->name[R_BIN_SIZEOF_STRINGS - 1] = '\0';
r_list_append (ret, ptr);
}
}
if (r_list_empty (ret)) {
if (!bf->size) {
struct Elf_(r_bin_elf_obj_t) *bin = bf->o->bin_obj;
bf->size = bin? bin->size: 0x9999;
}
if (found_load == 0) {
if (!(ptr = R_NEW0 (RBinSection))) {
return ret;
}
sprintf (ptr->name, "uphdr");
ptr->size = bf->size;
ptr->vsize = bf->size;
ptr->paddr = 0;
ptr->vaddr = 0x10000;
ptr->add = true;
ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_WRITABLE |
R_BIN_SCN_EXECUTABLE;
r_list_append (ret, ptr);
}
}
// add entry for ehdr
ptr = R_NEW0 (RBinSection);
if (ptr) {
ut64 ehdr_size = sizeof (obj->ehdr);
if (bf->size < ehdr_size) {
ehdr_size = bf->size;
}
sprintf (ptr->name, "ehdr");
ptr->paddr = 0;
ptr->vaddr = obj->baddr;
ptr->size = ehdr_size;
ptr->vsize = ehdr_size;
ptr->add = false;
if (obj->ehdr.e_type == ET_REL) {
ptr->add = true;
}
ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_WRITABLE;
r_list_append (ret, ptr);
}
return ret;
}
static RBinAddr* newEntry(ut64 haddr, ut64 paddr, int type, int bits) {
RBinAddr *ptr = R_NEW0 (RBinAddr);
if (ptr) {
ptr->paddr = paddr;
ptr->vaddr = paddr;
ptr->haddr = haddr;
ptr->bits = bits;
ptr->type = type;
//realign due to thumb
if (bits == 16 && ptr->vaddr & 1) {
ptr->paddr--;
ptr->vaddr--;
}
}
return ptr;
}
static void process_constructors (RBinFile *bf, RList *ret, int bits) {
RList *secs = sections (bf);
RListIter *iter;
RBinSection *sec;
int i, type;
r_list_foreach (secs, iter, sec) {
type = -1;
if (!strcmp (sec->name, ".fini_array")) {
type = R_BIN_ENTRY_TYPE_FINI;
} else if (!strcmp (sec->name, ".init_array")) {
type = R_BIN_ENTRY_TYPE_INIT;
} else if (!strcmp (sec->name, ".preinit_array")) {
type = R_BIN_ENTRY_TYPE_PREINIT;
}
if (type != -1) {
ut8 *buf = calloc (sec->size, 1);
if (!buf) {
continue;
}
(void)r_buf_read_at (bf->buf, sec->paddr, buf, sec->size);
if (bits == 32) {
for (i = 0; (i + 3) < sec->size; i += 4) {
ut32 addr32 = r_read_le32 (buf + i);
if (addr32) {
RBinAddr *ba = newEntry (sec->paddr + i, (ut64)addr32, type, bits);
r_list_append (ret, ba);
}
}
} else {
for (i = 0; (i + 7) < sec->size; i += 8) {
ut64 addr64 = r_read_le64 (buf + i);
if (addr64) {
RBinAddr *ba = newEntry (sec->paddr + i, addr64, type, bits);
r_list_append (ret, ba);
}
}
}
free (buf);
}
}
r_list_free (secs);
}
static RList* entries(RBinFile *bf) {
struct Elf_(r_bin_elf_obj_t)* obj;
RBinAddr *ptr = NULL;
struct r_bin_elf_symbol_t *symbol;
RList *ret;
int i;
if (!bf || !bf->o || !bf->o->bin_obj) {
return NULL;
}
obj = bf->o->bin_obj;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
if (!(ptr = R_NEW0 (RBinAddr))) {
return ret;
}
ptr->paddr = Elf_(r_bin_elf_get_entry_offset) (obj);
ptr->vaddr = Elf_(r_bin_elf_p2v) (obj, ptr->paddr);
ptr->haddr = 0x18;
if (obj->ehdr.e_machine == EM_ARM) {
int bin_bits = Elf_(r_bin_elf_get_bits) (obj);
if (bin_bits != 64) {
ptr->bits = 32;
if (ptr->vaddr & 1) {
ptr->vaddr--;
ptr->bits = 16;
}
if (ptr->paddr & 1) {
ptr->paddr--;
ptr->bits = 16;
}
}
}
r_list_append (ret, ptr);
// add entrypoint for jni libraries
// NOTE: this is slow, we shouldnt find for java constructors here
if (!(symbol = Elf_(r_bin_elf_get_symbols) (obj))) {
return ret;
}
for (i = 0; !symbol[i].last; i++) {
if (!strncmp (symbol[i].name, "Java", 4)) {
if (r_str_endswith (symbol[i].name, "_init")) {
if (!(ptr = R_NEW0 (RBinAddr))) {
return ret;
}
ptr->paddr = symbol[i].offset;
ptr->vaddr = Elf_(r_bin_elf_p2v) (obj, ptr->paddr);
ptr->haddr = UT64_MAX;
ptr->type = R_BIN_ENTRY_TYPE_INIT;
r_list_append (ret, ptr);
break;
}
}
}
int bin_bits = Elf_(r_bin_elf_get_bits) (bf->o->bin_obj);
process_constructors (bf, ret, bin_bits < 32 ? 32: bin_bits);
return ret;
}
static void _set_arm_thumb_bits(struct Elf_(r_bin_elf_obj_t) *bin, RBinSymbol **sym) {
int bin_bits = Elf_(r_bin_elf_get_bits) (bin);
RBinSymbol *ptr = *sym;
int len = strlen (ptr->name);
if (ptr->name[0] == '$' && (len >= 2 && !ptr->name[2])) {
switch (ptr->name[1]) {
case 'a' : //arm
ptr->bits = 32;
break;
case 't': //thumb
ptr->bits = 16;
if (ptr->vaddr & 1) {
ptr->vaddr--;
}
if (ptr->paddr & 1) {
ptr->paddr--;
}
break;
case 'd': //data
break;
default:
goto arm_symbol;
}
} else {
arm_symbol:
ptr->bits = bin_bits;
if (bin_bits != 64) {
ptr->bits = 32;
if (ptr->vaddr & 1) {
ptr->vaddr--;
ptr->bits = 16;
}
if (ptr->paddr & 1) {
ptr->paddr--;
ptr->bits = 16;
}
}
}
}
static RList* symbols(RBinFile *bf) {
struct Elf_(r_bin_elf_obj_t) *bin;
struct r_bin_elf_symbol_t *symbol = NULL;
RBinSymbol *ptr = NULL;
RList *ret = NULL;
int i;
if (!bf|| !bf->o || !bf->o->bin_obj) {
return NULL;
}
bin = bf->o->bin_obj;
ret = r_list_newf (free);
if (!ret) {
return NULL;
}
if (!(symbol = Elf_(r_bin_elf_get_symbols) (bin))) {
return ret;
}
for (i = 0; !symbol[i].last; i++) {
ut64 paddr = symbol[i].offset;
ut64 vaddr = Elf_(r_bin_elf_p2v) (bin, paddr);
if (!(ptr = R_NEW0 (RBinSymbol))) {
break;
}
ptr->name = strdup (symbol[i].name);
ptr->forwarder = r_str_const ("NONE");
ptr->bind = r_str_const (symbol[i].bind);
ptr->type = r_str_const (symbol[i].type);
ptr->paddr = paddr;
ptr->vaddr = vaddr;
ptr->size = symbol[i].size;
ptr->ordinal = symbol[i].ordinal;
setsymord (bin, ptr->ordinal, ptr);
if (bin->ehdr.e_machine == EM_ARM && *ptr->name) {
_set_arm_thumb_bits (bin, &ptr);
}
r_list_append (ret, ptr);
}
if (!(symbol = Elf_(r_bin_elf_get_imports) (bin))) {
return ret;
}
for (i = 0; !symbol[i].last; i++) {
ut64 paddr = symbol[i].offset;
ut64 vaddr = Elf_(r_bin_elf_p2v) (bin, paddr);
if (!symbol[i].size) {
continue;
}
if (!(ptr = R_NEW0 (RBinSymbol))) {
break;
}
// TODO(eddyb) make a better distinction between imports and other symbols.
//snprintf (ptr->name, R_BIN_SIZEOF_STRINGS-1, "imp.%s", symbol[i].name);
ptr->name = r_str_newf ("imp.%s", symbol[i].name);
ptr->forwarder = r_str_const ("NONE");
//strncpy (ptr->forwarder, "NONE", R_BIN_SIZEOF_STRINGS);
ptr->bind = r_str_const (symbol[i].bind);
ptr->type = r_str_const (symbol[i].type);
ptr->paddr = paddr;
ptr->vaddr = vaddr;
//special case where there is not entry in the plt for the import
if (ptr->vaddr == UT32_MAX) {
ptr->paddr = 0;
ptr->vaddr = 0;
}
ptr->size = symbol[i].size;
ptr->ordinal = symbol[i].ordinal;
setsymord (bin, ptr->ordinal, ptr);
/* detect thumb */
if (bin->ehdr.e_machine == EM_ARM) {
_set_arm_thumb_bits (bin, &ptr);
}
r_list_append (ret, ptr);
}
return ret;
}
static RList* imports(RBinFile *bf) {
struct Elf_(r_bin_elf_obj_t) *bin = NULL;
RBinElfSymbol *import = NULL;
RBinImport *ptr = NULL;
RList *ret = NULL;
int i;
if (!bf || !bf->o || !bf->o->bin_obj) {
return NULL;
}
bin = bf->o->bin_obj;
if (!(ret = r_list_newf (r_bin_import_free))) {
return NULL;
}
if (!(import = Elf_(r_bin_elf_get_imports) (bin))) {
r_list_free (ret);
return NULL;
}
for (i = 0; !import[i].last; i++) {
if (!(ptr = R_NEW0 (RBinImport))) {
break;
}
ptr->name = strdup (import[i].name);
ptr->bind = r_str_const (import[i].bind);
ptr->type = r_str_const (import[i].type);
ptr->ordinal = import[i].ordinal;
(void)setimpord (bin, ptr->ordinal, ptr);
r_list_append (ret, ptr);
}
return ret;
}
static RList* libs(RBinFile *bf) {
struct r_bin_elf_lib_t *libs = NULL;
RList *ret = NULL;
char *ptr = NULL;
int i;
if (!bf || !bf->o || !bf->o->bin_obj) {
return NULL;
}
if (!(ret = r_list_newf (free))) {
return NULL;
}
if (!(libs = Elf_(r_bin_elf_get_libs) (bf->o->bin_obj))) {
return ret;
}
for (i = 0; !libs[i].last; i++) {
ptr = strdup (libs[i].name);
r_list_append (ret, ptr);
}
free (libs);
return ret;
}
static RBinReloc *reloc_convert(struct Elf_(r_bin_elf_obj_t) *bin, RBinElfReloc *rel, ut64 GOT) {
RBinReloc *r = NULL;
ut64 B, P;
if (!bin || !rel) {
return NULL;
}
B = bin->baddr;
P = rel->rva; // rva has taken baddr into account
if (!(r = R_NEW0 (RBinReloc))) {
return r;
}
r->import = NULL;
r->symbol = NULL;
r->is_ifunc = false;
r->addend = rel->addend;
if (rel->sym) {
if (rel->sym < bin->imports_by_ord_size && bin->imports_by_ord[rel->sym]) {
r->import = bin->imports_by_ord[rel->sym];
} else if (rel->sym < bin->symbols_by_ord_size && bin->symbols_by_ord[rel->sym]) {
r->symbol = bin->symbols_by_ord[rel->sym];
}
}
r->vaddr = rel->rva;
r->paddr = rel->offset;
#define SET(T) r->type = R_BIN_RELOC_ ## T; r->additive = 0; return r
#define ADD(T, A) r->type = R_BIN_RELOC_ ## T; r->addend += A; r->additive = !rel->is_rela; return r
switch (bin->ehdr.e_machine) {
case EM_386: switch (rel->type) {
case R_386_NONE: break; // malloc then free. meh. then again, there's no real world use for _NONE.
case R_386_32: ADD(32, 0);
case R_386_PC32: ADD(32,-P);
case R_386_GLOB_DAT: SET(32);
case R_386_JMP_SLOT: SET(32);
case R_386_RELATIVE: ADD(32, B);
case R_386_GOTOFF: ADD(32,-GOT);
case R_386_GOTPC: ADD(32, GOT-P);
case R_386_16: ADD(16, 0);
case R_386_PC16: ADD(16,-P);
case R_386_8: ADD(8, 0);
case R_386_PC8: ADD(8, -P);
case R_386_COPY: ADD(64, 0); // XXX: copy symbol at runtime
case R_386_IRELATIVE: r->is_ifunc = true; SET(32);
default: break; //eprintf("TODO(eddyb): uninmplemented ELF/x86 reloc type %i\n", rel->type);
}
break;
case EM_X86_64: switch (rel->type) {
case R_X86_64_NONE: break; // malloc then free. meh. then again, there's no real world use for _NONE.
case R_X86_64_64: ADD(64, 0);
case R_X86_64_PLT32: ADD(32,-P /* +L */);
case R_X86_64_GOT32: ADD(32, GOT);
case R_X86_64_PC32: ADD(32,-P);
case R_X86_64_GLOB_DAT: r->vaddr -= rel->sto; SET(64);
case R_X86_64_JUMP_SLOT: r->vaddr -= rel->sto; SET(64);
case R_X86_64_RELATIVE: ADD(64, B);
case R_X86_64_32: ADD(32, 0);
case R_X86_64_32S: ADD(32, 0);
case R_X86_64_16: ADD(16, 0);
case R_X86_64_PC16: ADD(16,-P);
case R_X86_64_8: ADD(8, 0);
case R_X86_64_PC8: ADD(8, -P);
case R_X86_64_GOTPCREL: ADD(64, GOT-P);
case R_X86_64_COPY: ADD(64, 0); // XXX: copy symbol at runtime
case R_X86_64_IRELATIVE: r->is_ifunc = true; SET(64);
default: break; ////eprintf("TODO(eddyb): uninmplemented ELF/x64 reloc type %i\n", rel->type);
}
break;
case EM_ARM: switch (rel->type) {
case R_ARM_NONE: break; // malloc then free. meh. then again, there's no real world use for _NONE.
case R_ARM_ABS32: ADD(32, 0);
case R_ARM_REL32: ADD(32,-P);
case R_ARM_ABS16: ADD(16, 0);
case R_ARM_ABS8: ADD(8, 0);
case R_ARM_SBREL32: ADD(32, -B);
case R_ARM_GLOB_DAT: ADD(32, 0);
case R_ARM_JUMP_SLOT: ADD(32, 0);
case R_ARM_RELATIVE: ADD(32, B);
case R_ARM_GOTOFF: ADD(32,-GOT);
default: ADD(32,GOT); break; // reg relocations
////eprintf("TODO(eddyb): uninmplemented ELF/ARM reloc type %i\n", rel->type);
}
break;
default: break;
}
#undef SET
#undef ADD
free(r);
return 0;
}
static RList* relocs(RBinFile *bf) {
RList *ret = NULL;
RBinReloc *ptr = NULL;
RBinElfReloc *relocs = NULL;
struct Elf_(r_bin_elf_obj_t) *bin = NULL;
ut64 got_addr;
int i;
if (!bf || !bf->o || !bf->o->bin_obj) {
return NULL;
}
bin = bf->o->bin_obj;
if (!(ret = r_list_newf (free))) {
return NULL;
}
/* FIXME: This is a _temporary_ fix/workaround to prevent a use-after-
* free detected by ASan that would corrupt the relocation names */
r_list_free (imports (bf));
if ((got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got")) == -1) {
got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got.plt");
if (got_addr == -1) {
got_addr = 0;
}
}
if (got_addr < 1 && bin->ehdr.e_type == ET_REL) {
got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got.r2");
if (got_addr == -1) {
got_addr = 0;
}
}
if (bf->o) {
if (!(relocs = Elf_(r_bin_elf_get_relocs) (bin))) {
return ret;
}
for (i = 0; !relocs[i].last; i++) {
if (!(ptr = reloc_convert (bin, &relocs[i], got_addr))) {
continue;
}
r_list_append (ret, ptr);
}
free (relocs);
}
return ret;
}
static void _patch_reloc (ut16 e_machine, RIOBind *iob, RBinElfReloc *rel, ut64 S, ut64 B, ut64 L) {
ut64 val;
ut64 A = rel->addend, P = rel->rva;
ut8 buf[8];
switch (e_machine) {
case EM_PPC64: {
int low = 0, word = 0;
switch (rel->type) {
case R_PPC64_REL16_HA:
word = 2;
val = (S + A - P + 0x8000) >> 16;
break;
case R_PPC64_REL16_LO:
word = 2;
val = (S + A - P) & 0xffff;
break;
case R_PPC64_REL14:
low = 14;
val = (st64)(S + A - P) >> 2;
break;
case R_PPC64_REL24:
low = 24;
val = (st64)(S + A - P) >> 2;
break;
case R_PPC64_REL32:
word = 4;
val = S + A - P;
break;
default:
break;
}
if (low) {
// TODO big-endian
switch (low) {
case 14:
val &= (1 << 14) - 1;
iob->read_at (iob->io, rel->rva, buf, 2);
r_write_le32 (buf, (r_read_le32 (buf) & ~((1<<16) - (1<<2))) | val << 2);
iob->write_at (iob->io, rel->rva, buf, 2);
break;
case 24:
val &= (1 << 24) - 1;
iob->read_at (iob->io, rel->rva, buf, 4);
r_write_le32 (buf, (r_read_le32 (buf) & ~((1<<26) - (1<<2))) | val << 2);
iob->write_at (iob->io, rel->rva, buf, 4);
break;
}
} else if (word) {
// TODO big-endian
switch (word) {
case 2:
r_write_le16 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 2);
break;
case 4:
r_write_le32 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 4);
break;
}
}
break;
}
case EM_X86_64: {
int word = 0;
switch (rel->type) {
case R_X86_64_8:
word = 1;
val = S + A;
break;
case R_X86_64_16:
word = 2;
val = S + A;
break;
case R_X86_64_32:
case R_X86_64_32S:
word = 4;
val = S + A;
break;
case R_X86_64_64:
word = 8;
val = S + A;
break;
case R_X86_64_GLOB_DAT:
case R_X86_64_JUMP_SLOT:
word = 4;
val = S;
break;
case R_X86_64_PC8:
word = 1;
val = S + A - P;
break;
case R_X86_64_PC16:
word = 2;
val = S + A - P;
break;
case R_X86_64_PC32:
word = 4;
val = S + A - P;
break;
case R_X86_64_PC64:
word = 8;
val = S + A - P;
break;
case R_X86_64_PLT32:
word = 4;
val = L + A - P;
break;
case R_X86_64_RELATIVE:
word = 8;
val = B + A;
break;
default:
//eprintf ("relocation %d not handle at this time\n", rel->type);
break;
}
switch (word) {
case 0:
break;
case 1:
buf[0] = val;
iob->write_at (iob->io, rel->rva, buf, 1);
break;
case 2:
r_write_le16 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 2);
break;
case 4:
r_write_le32 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 4);
break;
case 8:
r_write_le64 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 8);
break;
}
break;
}
}
}
static bool ht_insert_intu64(SdbHash* ht, int key, ut64 value) {
ut64 *mvalue = malloc (sizeof (ut64));
if (!mvalue) {
return false;
}
*mvalue = value;
return ht_insert (ht, sdb_fmt ("%d", key), (void *)mvalue);
}
static ut64 ht_find_intu64(SdbHash* ht, int key, bool* found) {
ut64 *mvalue = (ut64 *)ht_find (ht, sdb_fmt ("%d", key), found);
return *mvalue;
}
static void relocs_by_sym_free(HtKv *kv) {
free (kv->key);
free (kv->value);
}
static RList* patch_relocs(RBin *b) {
RList *ret = NULL;
RBinReloc *ptr = NULL;
RIO *io = NULL;
RBinObject *obj = NULL;
struct Elf_(r_bin_elf_obj_t) *bin = NULL;
RIOSection *g = NULL, *s = NULL;
SdbHash *relocs_by_sym;
SdbListIter *iter;
RBinElfReloc *relcs = NULL;
RBinInfo *info;
int cdsz;
int i;
ut64 n_off, n_vaddr, vaddr, size, offset = 0;
if (!b)
return NULL;
io = b->iob.io;
if (!io || !io->desc)
return NULL;
obj = r_bin_cur_object (b);
if (!obj) {
return NULL;
}
bin = obj->bin_obj;
if (bin->ehdr.e_type != ET_REL) {
return NULL;
}
if (!io->cached) {
eprintf ("Warning: run r2 with -e io.cache=true to fix relocations in disassembly\n");
return relocs (r_bin_cur (b));
}
info = obj ? obj->info: NULL;
cdsz = info? (info->bits == 64? 8: info->bits == 32? 4: info->bits == 16 ? 4: 0): 0;
ls_foreach (io->sections, iter, s) {
if (s->paddr > offset) {
offset = s->paddr;
g = s;
}
}
if (!g) {
return NULL;
}
n_off = g->paddr + g->size;
n_vaddr = g->vaddr + g->vsize;
//reserve at least that space
size = bin->reloc_num * 4;
if (!b->iob.section_add (io, n_off, n_vaddr, size, size, R_BIN_SCN_READABLE, ".got.r2", 0, io->desc->fd)) {
return NULL;
}
if (!(relcs = Elf_(r_bin_elf_get_relocs) (bin))) {
return NULL;
}
if (!(ret = r_list_newf ((RListFree)free))) {
free (relcs);
return NULL;
}
if (!(relocs_by_sym = ht_new (NULL, relocs_by_sym_free, NULL))) {
r_list_free (ret);
free (relcs);
return NULL;
}
vaddr = n_vaddr;
for (i = 0; !relcs[i].last; i++) {
ut64 sym_addr = 0;
if (relcs[i].sym) {
if (relcs[i].sym < bin->imports_by_ord_size && bin->imports_by_ord[relcs[i].sym]) {
bool found;
sym_addr = ht_find_intu64 (relocs_by_sym, relcs[i].sym, &found);
if (!found) {
sym_addr = 0;
}
} else if (relcs[i].sym < bin->symbols_by_ord_size && bin->symbols_by_ord[relcs[i].sym]) {
sym_addr = bin->symbols_by_ord[relcs[i].sym]->vaddr;
}
}
// TODO relocation types B, L
_patch_reloc (bin->ehdr.e_machine, &b->iob, &relcs[i], sym_addr ? sym_addr : vaddr, 0, n_vaddr + size);
if (!(ptr = reloc_convert (bin, &relcs[i], n_vaddr))) {
continue;
}
if (sym_addr) {
ptr->vaddr = sym_addr;
} else {
ptr->vaddr = vaddr;
ht_insert_intu64 (relocs_by_sym, relcs[i].sym, vaddr);
vaddr += cdsz;
}
r_list_append (ret, ptr);
}
ht_free (relocs_by_sym);
free (relcs);
return ret;
}
static bool has_canary(RBinFile *bf) {
bool ret = false;
RList* imports_list = imports (bf);
RListIter *iter;
RBinImport *import;
if (imports_list) {
r_list_foreach (imports_list, iter, import) {
if (!strcmp (import->name, "__stack_chk_fail") || !strcmp (import->name, "__stack_smash_handler")) {
ret = true;
break;
}
}
imports_list->free = r_bin_import_free;
r_list_free (imports_list);
}
return ret;
}
static RBinInfo* info(RBinFile *bf) {
RBinInfo *ret = NULL;
char *str;
if (!(ret = R_NEW0 (RBinInfo))) {
return NULL;
}
ret->lang = "c";
ret->file = bf->file
? strdup (bf->file)
: NULL;
void *obj = bf->o->bin_obj;
if ((str = Elf_(r_bin_elf_get_rpath)(obj))) {
ret->rpath = strdup (str);
free (str);
} else {
ret->rpath = strdup ("NONE");
}
if (!(str = Elf_(r_bin_elf_get_file_type) (obj))) {
free (ret);
return NULL;
}
ret->type = str;
ret->has_pi = (strstr (str, "DYN"))? 1: 0;
ret->has_lit = true;
ret->has_canary = has_canary (bf);
if (!(str = Elf_(r_bin_elf_get_elf_class) (obj))) {
free (ret);
return NULL;
}
ret->bclass = str;
if (!(str = Elf_(r_bin_elf_get_osabi_name) (obj))) {
free (ret);
return NULL;
}
ret->os = str;
if (!(str = Elf_(r_bin_elf_get_osabi_name) (obj))) {
free (ret);
return NULL;
}
ret->subsystem = str;
if (!(str = Elf_(r_bin_elf_get_machine_name) (obj))) {
free (ret);
return NULL;
}
ret->machine = str;
if (!(str = Elf_(r_bin_elf_get_arch) (obj))) {
free (ret);
return NULL;
}
ret->arch = str;
ret->rclass = strdup ("elf");
ret->bits = Elf_(r_bin_elf_get_bits) (obj);
if (!strcmp (ret->arch, "avr")) {
ret->bits = 16;
}
ret->big_endian = Elf_(r_bin_elf_is_big_endian) (obj);
ret->has_va = Elf_(r_bin_elf_has_va) (obj);
ret->has_nx = Elf_(r_bin_elf_has_nx) (obj);
ret->intrp = Elf_(r_bin_elf_intrp) (obj);
ret->dbg_info = 0;
if (!Elf_(r_bin_elf_get_stripped) (obj)) {
ret->dbg_info |= R_BIN_DBG_LINENUMS | R_BIN_DBG_SYMS | R_BIN_DBG_RELOCS;
} else {
ret->dbg_info |= R_BIN_DBG_STRIPPED;
}
if (Elf_(r_bin_elf_get_static) (obj)) {
ret->dbg_info |= R_BIN_DBG_STATIC;
}
RBinElfSymbol *symbol;
if (!(symbol = Elf_(r_bin_elf_get_symbols) (obj))) {
return ret;
}
int i;
for (i = 0; !symbol[i].last; i++) {
if (!strncmp (symbol[i].name, "type.", 5)) {
ret->lang = "go";
break;
}
}
return ret;
}
static RList* fields(RBinFile *bf) {
RList *ret = NULL;
RBinField *ptr = NULL;
struct r_bin_elf_field_t *field = NULL;
int i;
if (!(ret = r_list_new ())) {
return NULL;
}
ret->free = free;
if (!(field = Elf_(r_bin_elf_get_fields) (bf->o->bin_obj))) {
return ret;
}
for (i = 0; !field[i].last; i++) {
if (!(ptr = R_NEW0 (RBinField))) {
break;
}
ptr->name = strdup (field[i].name);
ptr->comment = NULL;
ptr->vaddr = field[i].offset;
ptr->paddr = field[i].offset;
r_list_append (ret, ptr);
}
free (field);
return ret;
}
static ut64 size(RBinFile *bf) {
ut64 off = 0;
ut64 len = 0;
if (!bf->o->sections) {
RListIter *iter;
RBinSection *section;
bf->o->sections = sections (bf);
r_list_foreach (bf->o->sections, iter, section) {
if (section->paddr > off) {
off = section->paddr;
len = section->size;
}
}
}
return off + len;
}
#if !R_BIN_ELF64 && !R_BIN_CGC
static void headers32(RBinFile *bf) {
#define p bf->rbin->cb_printf
const ut8 *buf = r_buf_get_at (bf->buf, 0, NULL);
p ("0x00000000 ELF MAGIC 0x%08x\n", r_read_le32 (buf));
p ("0x00000004 Type 0x%04x\n", r_read_le16 (buf + 4));
p ("0x00000006 Machine 0x%04x\n", r_read_le16 (buf + 6));
p ("0x00000008 Version 0x%08x\n", r_read_le32 (buf + 8));
p ("0x0000000c Entrypoint 0x%08x\n", r_read_le32 (buf + 12));
p ("0x00000010 PhOff 0x%08x\n", r_read_le32 (buf + 16));
p ("0x00000014 ShOff 0x%08x\n", r_read_le32 (buf + 20));
}
static bool check_bytes(const ut8 *buf, ut64 length) {
return buf && length > 4 && memcmp (buf, ELFMAG, SELFMAG) == 0
&& buf[4] != 2;
}
extern struct r_bin_dbginfo_t r_bin_dbginfo_elf;
extern struct r_bin_write_t r_bin_write_elf;
static RBuffer* create(RBin* bin, const ut8 *code, int codelen, const ut8 *data, int datalen) {
ut32 filesize, code_va, code_pa, phoff;
ut32 p_start, p_phoff, p_phdr;
ut32 p_ehdrsz, p_phdrsz;
ut16 ehdrsz, phdrsz;
ut32 p_vaddr, p_paddr, p_fs, p_fs2;
ut32 baddr;
int is_arm = 0;
RBuffer *buf = r_buf_new ();
if (bin && bin->cur && bin->cur->o && bin->cur->o->info) {
is_arm = !strcmp (bin->cur->o->info->arch, "arm");
}
// XXX: hardcoded
if (is_arm) {
baddr = 0x40000;
} else {
baddr = 0x8048000;
}
#define B(x,y) r_buf_append_bytes(buf,(const ut8*)x,y)
#define D(x) r_buf_append_ut32(buf,x)
#define H(x) r_buf_append_ut16(buf,x)
#define Z(x) r_buf_append_nbytes(buf,x)
#define W(x,y,z) r_buf_write_at(buf,x,(const ut8*)y,z)
#define WZ(x,y) p_tmp=buf->length;Z(x);W(p_tmp,y,strlen(y))
B ("\x7F" "ELF" "\x01\x01\x01\x00", 8);
Z (8);
H (2); // ET_EXEC
if (is_arm) {
H (40); // e_machne = EM_ARM
} else {
H (3); // e_machne = EM_I386
}
D (1);
p_start = buf->length;
D (-1); // _start
p_phoff = buf->length;
D (-1); // phoff -- program headers offset
D (0); // shoff -- section headers offset
D (0); // flags
p_ehdrsz = buf->length;
H (-1); // ehdrsz
p_phdrsz = buf->length;
H (-1); // phdrsz
H (1);
H (0);
H (0);
H (0);
// phdr:
p_phdr = buf->length;
D (1);
D (0);
p_vaddr = buf->length;
D (-1); // vaddr = $$
p_paddr = buf->length;
D (-1); // paddr = $$
p_fs = buf->length;
D (-1); // filesize
p_fs2 = buf->length;
D (-1); // filesize
D (5); // flags
D (0x1000); // align
ehdrsz = p_phdr;
phdrsz = buf->length - p_phdr;
code_pa = buf->length;
code_va = code_pa + baddr;
phoff = 0x34;//p_phdr ;
filesize = code_pa + codelen + datalen;
W (p_start, &code_va, 4);
W (p_phoff, &phoff, 4);
W (p_ehdrsz, &ehdrsz, 2);
W (p_phdrsz, &phdrsz, 2);
code_va = baddr; // hack
W (p_vaddr, &code_va, 4);
code_pa = baddr; // hack
W (p_paddr, &code_pa, 4);
W (p_fs, &filesize, 4);
W (p_fs2, &filesize, 4);
B (code, codelen);
if (data && datalen > 0) {
//ut32 data_section = buf->length;
eprintf ("Warning: DATA section not support for ELF yet\n");
B (data, datalen);
}
return buf;
}
RBinPlugin r_bin_plugin_elf = {
.name = "elf",
.desc = "ELF format r2 plugin",
.license = "LGPL3",
.get_sdb = &get_sdb,
.load = &load,
.load_bytes = &load_bytes,
.load_buffer = &load_buffer,
.destroy = &destroy,
.check_bytes = &check_bytes,
.baddr = &baddr,
.boffset = &boffset,
.binsym = &binsym,
.entries = &entries,
.sections = §ions,
.symbols = &symbols,
.minstrlen = 4,
.imports = &imports,
.info = &info,
.fields = &fields,
.header = &headers32,
.size = &size,
.libs = &libs,
.relocs = &relocs,
.patch_relocs = &patch_relocs,
.dbginfo = &r_bin_dbginfo_elf,
.create = &create,
.write = &r_bin_write_elf,
.file_type = &get_file_type,
.regstate = ®state,
.maps = &maps,
};
#ifndef CORELIB
RLibStruct radare_plugin = {
.type = R_LIB_TYPE_BIN,
.data = &r_bin_plugin_elf,
.version = R2_VERSION
};
#endif
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_140_0 |
crossvul-cpp_data_bad_502_0 | /* radare - LGPL - Copyright 2010-2016 - nibble, pancake */
#include <stdio.h>
#include <r_types.h>
#include <r_util.h>
#include "dyldcache.h"
static int r_bin_dyldcache_init(struct r_bin_dyldcache_obj_t* bin) {
int len = r_buf_fread_at (bin->b, 0, (ut8*)&bin->hdr, "16c4i7l", 1);
if (len == -1) {
perror ("read (cache_header)");
return false;
}
bin->nlibs = bin->hdr.numlibs;
return true;
}
static int r_bin_dyldcache_apply_patch (struct r_buf_t* buf, ut32 data, ut64 offset) {
return r_buf_write_at (buf, offset, (ut8*)&data, sizeof (data));
}
#define NZ_OFFSET(x) if((x) > 0) r_bin_dyldcache_apply_patch (dbuf, (x) - linkedit_offset, (ut64)((size_t)&(x) - (size_t)data))
/* TODO: Needs more testing and ERROR HANDLING */
struct r_bin_dyldcache_lib_t *r_bin_dyldcache_extract(struct r_bin_dyldcache_obj_t* bin, int idx, int *nlib) {
ut64 liboff, linkedit_offset;
ut64 dyld_vmbase;
ut32 addend = 0;
struct r_bin_dyldcache_lib_t *ret = NULL;
struct dyld_cache_image_info* image_infos = NULL;
struct mach_header *mh;
ut8 *data, *cmdptr;
int cmd, libsz = 0;
RBuffer* dbuf;
char *libname;
if (!bin) {
return NULL;
}
if (bin->size < 1) {
eprintf ("Empty file? (%s)\n", bin->file? bin->file: "(null)");
return NULL;
}
if (bin->nlibs < 0 || idx < 0 || idx >= bin->nlibs) {
return NULL;
}
*nlib = bin->nlibs;
ret = R_NEW0 (struct r_bin_dyldcache_lib_t);
if (!ret) {
perror ("malloc (ret)");
return NULL;
}
if (bin->hdr.startaddr > bin->size) {
eprintf ("corrupted dyldcache");
free (ret);
return NULL;
}
if (bin->hdr.startaddr > bin->size || bin->hdr.baseaddroff > bin->size) {
eprintf ("corrupted dyldcache");
free (ret);
return NULL;
}
image_infos = (struct dyld_cache_image_info*) (bin->b->buf + bin->hdr.startaddr);
dyld_vmbase = *(ut64 *)(bin->b->buf + bin->hdr.baseaddroff);
liboff = image_infos[idx].address - dyld_vmbase;
if (liboff > bin->size) {
eprintf ("Corrupted file\n");
free (ret);
return NULL;
}
ret->offset = liboff;
if (image_infos[idx].pathFileOffset > bin->size) {
eprintf ("corrupted file\n");
free (ret);
return NULL;
}
libname = (char *)(bin->b->buf + image_infos[idx].pathFileOffset);
/* Locate lib hdr in cache */
data = bin->b->buf + liboff;
mh = (struct mach_header *)data;
/* Check it is mach-o */
if (mh->magic != MH_MAGIC && mh->magic != MH_MAGIC_64) {
if (mh->magic == 0xbebafeca) { //FAT binary
eprintf ("FAT Binary\n");
}
eprintf ("Not mach-o\n");
free (ret);
return NULL;
}
/* Write mach-o hdr */
if (!(dbuf = r_buf_new ())) {
eprintf ("new (dbuf)\n");
free (ret);
return NULL;
}
addend = mh->magic == MH_MAGIC? sizeof (struct mach_header) : sizeof (struct mach_header_64);
r_buf_set_bytes (dbuf, data, addend);
cmdptr = data + addend;
/* Write load commands */
for (cmd = 0; cmd < mh->ncmds; cmd++) {
struct load_command *lc = (struct load_command *)cmdptr;
r_buf_append_bytes (dbuf, (ut8*)lc, lc->cmdsize);
cmdptr += lc->cmdsize;
}
cmdptr = data + addend;
/* Write segments */
for (cmd = linkedit_offset = 0; cmd < mh->ncmds; cmd++) {
struct load_command *lc = (struct load_command *)cmdptr;
cmdptr += lc->cmdsize;
switch (lc->cmd) {
case LC_SEGMENT:
{
/* Write segment and patch offset */
struct segment_command *seg = (struct segment_command *)lc;
int t = seg->filesize;
if (seg->fileoff + seg->filesize > bin->size || seg->fileoff > bin->size) {
eprintf ("malformed dyldcache\n");
free (ret);
r_buf_free (dbuf);
return NULL;
}
r_buf_append_bytes (dbuf, bin->b->buf+seg->fileoff, t);
r_bin_dyldcache_apply_patch (dbuf, dbuf->length, (ut64)((size_t)&seg->fileoff - (size_t)data));
/* Patch section offsets */
int sect_offset = seg->fileoff - libsz;
libsz = dbuf->length;
if (!strcmp (seg->segname, "__LINKEDIT")) {
linkedit_offset = sect_offset;
}
if (seg->nsects > 0) {
struct section *sects = (struct section *)((ut8 *)seg + sizeof(struct segment_command));
int nsect;
for (nsect = 0; nsect < seg->nsects; nsect++) {
if (sects[nsect].offset > libsz) {
r_bin_dyldcache_apply_patch (dbuf, sects[nsect].offset - sect_offset,
(ut64)((size_t)§s[nsect].offset - (size_t)data));
}
}
}
}
break;
case LC_SYMTAB:
{
struct symtab_command *st = (struct symtab_command *)lc;
NZ_OFFSET (st->symoff);
NZ_OFFSET (st->stroff);
}
break;
case LC_DYSYMTAB:
{
struct dysymtab_command *st = (struct dysymtab_command *)lc;
NZ_OFFSET (st->tocoff);
NZ_OFFSET (st->modtaboff);
NZ_OFFSET (st->extrefsymoff);
NZ_OFFSET (st->indirectsymoff);
NZ_OFFSET (st->extreloff);
NZ_OFFSET (st->locreloff);
}
break;
case LC_DYLD_INFO:
case LC_DYLD_INFO_ONLY:
{
struct dyld_info_command *st = (struct dyld_info_command *)lc;
NZ_OFFSET (st->rebase_off);
NZ_OFFSET (st->bind_off);
NZ_OFFSET (st->weak_bind_off);
NZ_OFFSET (st->lazy_bind_off);
NZ_OFFSET (st->export_off);
}
break;
}
}
/* Fill r_bin_dyldcache_lib_t ret */
ret->b = dbuf;
strncpy (ret->path, libname, sizeof (ret->path) - 1);
ret->size = libsz;
return ret;
}
void* r_bin_dyldcache_free(struct r_bin_dyldcache_obj_t* bin) {
if (!bin) {
return NULL;
}
r_buf_free (bin->b);
free (bin);
return NULL;
}
void r_bin_dydlcache_get_libname(struct r_bin_dyldcache_lib_t *lib, char **libname) {
char *cur = lib->path;
char *res = lib->path;
int path_length = strlen (lib->path);
while (cur < cur + path_length - 1) {
cur = strchr (cur, '/');
if (!cur) {
break;
}
cur++;
res = cur;
}
*libname = res;
}
struct r_bin_dyldcache_obj_t* r_bin_dyldcache_new(const char* file) {
struct r_bin_dyldcache_obj_t *bin;
ut8 *buf;
if (!(bin = R_NEW0 (struct r_bin_dyldcache_obj_t))) {
return NULL;
}
bin->file = file;
if (!(buf = (ut8*)r_file_slurp (file, &bin->size))) {
return r_bin_dyldcache_free (bin);
}
bin->b = r_buf_new ();
if (!r_buf_set_bytes (bin->b, buf, bin->size)) {
free (buf);
return r_bin_dyldcache_free (bin);
}
free (buf);
if (!r_bin_dyldcache_init (bin)) {
return r_bin_dyldcache_free (bin);
}
return bin;
}
struct r_bin_dyldcache_obj_t* r_bin_dyldcache_from_bytes_new(const ut8* buf, ut64 size) {
struct r_bin_dyldcache_obj_t *bin;
if (!(bin = malloc (sizeof (struct r_bin_dyldcache_obj_t)))) {
return NULL;
}
memset (bin, 0, sizeof (struct r_bin_dyldcache_obj_t));
if (!buf) {
return r_bin_dyldcache_free (bin);
}
bin->b = r_buf_new();
if (!r_buf_set_bytes (bin->b, buf, size)) {
return r_bin_dyldcache_free (bin);
}
if (!r_bin_dyldcache_init (bin)) {
return r_bin_dyldcache_free (bin);
}
bin->size = size;
return bin;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_502_0 |
crossvul-cpp_data_good_177_0 | #include <mruby.h>
#include <mruby/array.h>
#include <mruby/class.h>
#include <mruby/proc.h>
#define fiber_ptr(o) ((struct RFiber*)mrb_ptr(o))
#define FIBER_STACK_INIT_SIZE 64
#define FIBER_CI_INIT_SIZE 8
#define CI_ACC_RESUMED -3
/*
* call-seq:
* Fiber.new{...} -> obj
*
* Creates a fiber, whose execution is suspend until it is explicitly
* resumed using <code>Fiber#resume</code> method.
* The code running inside the fiber can give up control by calling
* <code>Fiber.yield</code> in which case it yields control back to caller
* (the caller of the <code>Fiber#resume</code>).
*
* Upon yielding or termination the Fiber returns the value of the last
* executed expression
*
* For instance:
*
* fiber = Fiber.new do
* Fiber.yield 1
* 2
* end
*
* puts fiber.resume
* puts fiber.resume
* puts fiber.resume
*
* <em>produces</em>
*
* 1
* 2
* resuming dead fiber (FiberError)
*
* The <code>Fiber#resume</code> method accepts an arbitrary number of
* parameters, if it is the first call to <code>resume</code> then they
* will be passed as block arguments. Otherwise they will be the return
* value of the call to <code>Fiber.yield</code>
*
* Example:
*
* fiber = Fiber.new do |first|
* second = Fiber.yield first + 2
* end
*
* puts fiber.resume 10
* puts fiber.resume 14
* puts fiber.resume 18
*
* <em>produces</em>
*
* 12
* 14
* resuming dead fiber (FiberError)
*
*/
static mrb_value
fiber_init(mrb_state *mrb, mrb_value self)
{
static const struct mrb_context mrb_context_zero = { 0 };
struct RFiber *f = fiber_ptr(self);
struct mrb_context *c;
struct RProc *p;
mrb_callinfo *ci;
mrb_value blk;
size_t slen;
mrb_get_args(mrb, "&", &blk);
if (f->cxt) {
mrb_raise(mrb, E_RUNTIME_ERROR, "cannot initialize twice");
}
if (mrb_nil_p(blk)) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "tried to create Fiber object without a block");
}
p = mrb_proc_ptr(blk);
if (MRB_PROC_CFUNC_P(p)) {
mrb_raise(mrb, E_FIBER_ERROR, "tried to create Fiber from C defined method");
}
c = (struct mrb_context*)mrb_malloc(mrb, sizeof(struct mrb_context));
*c = mrb_context_zero;
f->cxt = c;
/* initialize VM stack */
slen = FIBER_STACK_INIT_SIZE;
if (p->body.irep->nregs > slen) {
slen += p->body.irep->nregs;
}
c->stbase = (mrb_value *)mrb_malloc(mrb, slen*sizeof(mrb_value));
c->stend = c->stbase + slen;
c->stack = c->stbase;
#ifdef MRB_NAN_BOXING
{
mrb_value *p = c->stbase;
mrb_value *pend = c->stend;
while (p < pend) {
SET_NIL_VALUE(*p);
p++;
}
}
#else
memset(c->stbase, 0, slen * sizeof(mrb_value));
#endif
/* copy receiver from a block */
c->stack[0] = mrb->c->stack[0];
/* initialize callinfo stack */
c->cibase = (mrb_callinfo *)mrb_calloc(mrb, FIBER_CI_INIT_SIZE, sizeof(mrb_callinfo));
c->ciend = c->cibase + FIBER_CI_INIT_SIZE;
c->ci = c->cibase;
c->ci->stackent = c->stack;
/* adjust return callinfo */
ci = c->ci;
ci->target_class = MRB_PROC_TARGET_CLASS(p);
ci->proc = p;
mrb_field_write_barrier(mrb, (struct RBasic*)mrb_obj_ptr(self), (struct RBasic*)p);
ci->pc = p->body.irep->iseq;
ci->nregs = p->body.irep->nregs;
ci[1] = ci[0];
c->ci++; /* push dummy callinfo */
c->fib = f;
c->status = MRB_FIBER_CREATED;
return self;
}
static struct mrb_context*
fiber_check(mrb_state *mrb, mrb_value fib)
{
struct RFiber *f = fiber_ptr(fib);
mrb_assert(f->tt == MRB_TT_FIBER);
if (!f->cxt) {
mrb_raise(mrb, E_FIBER_ERROR, "uninitialized Fiber");
}
return f->cxt;
}
static mrb_value
fiber_result(mrb_state *mrb, const mrb_value *a, mrb_int len)
{
if (len == 0) return mrb_nil_value();
if (len == 1) return a[0];
return mrb_ary_new_from_values(mrb, len, a);
}
/* mark return from context modifying method */
#define MARK_CONTEXT_MODIFY(c) (c)->ci->target_class = NULL
static void
fiber_check_cfunc(mrb_state *mrb, struct mrb_context *c)
{
mrb_callinfo *ci;
for (ci = c->ci; ci >= c->cibase; ci--) {
if (ci->acc < 0) {
mrb_raise(mrb, E_FIBER_ERROR, "can't cross C function boundary");
}
}
}
static void
fiber_switch_context(mrb_state *mrb, struct mrb_context *c)
{
c->status = MRB_FIBER_RUNNING;
mrb->c = c;
}
static mrb_value
fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec)
{
struct mrb_context *c = fiber_check(mrb, self);
struct mrb_context *old_c = mrb->c;
enum mrb_fiber_state status;
mrb_value value;
fiber_check_cfunc(mrb, c);
status = c->status;
if (resume && status == MRB_FIBER_TRANSFERRED) {
mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber");
}
if (status == MRB_FIBER_RUNNING || status == MRB_FIBER_RESUMED) {
mrb_raise(mrb, E_FIBER_ERROR, "double resume (fib)");
}
if (status == MRB_FIBER_TERMINATED) {
mrb_raise(mrb, E_FIBER_ERROR, "resuming dead fiber");
}
old_c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;
c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c);
fiber_switch_context(mrb, c);
if (status == MRB_FIBER_CREATED) {
mrb_value *b, *e;
mrb_stack_extend(mrb, len+2); /* for receiver and (optional) block */
b = c->stack+1;
e = b + len;
while (b<e) {
*b++ = *a++;
}
c->cibase->argc = (int)len;
value = c->stack[0] = MRB_PROC_ENV(c->ci->proc)->stack[0];
}
else {
value = fiber_result(mrb, a, len);
}
if (vmexec) {
c->vmexec = TRUE;
value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc);
mrb->c = old_c;
}
else {
MARK_CONTEXT_MODIFY(c);
}
return value;
}
/*
* call-seq:
* fiber.resume(args, ...) -> obj
*
* Resumes the fiber from the point at which the last <code>Fiber.yield</code>
* was called, or starts running it if it is the first call to
* <code>resume</code>. Arguments passed to resume will be the value of
* the <code>Fiber.yield</code> expression or will be passed as block
* parameters to the fiber's block if this is the first <code>resume</code>.
*
* Alternatively, when resume is called it evaluates to the arguments passed
* to the next <code>Fiber.yield</code> statement inside the fiber's block
* or to the block value if it runs to completion without any
* <code>Fiber.yield</code>
*/
static mrb_value
fiber_resume(mrb_state *mrb, mrb_value self)
{
mrb_value *a;
mrb_int len;
mrb_bool vmexec = FALSE;
mrb_get_args(mrb, "*!", &a, &len);
if (mrb->c->ci->acc < 0) {
vmexec = TRUE;
}
return fiber_switch(mrb, self, len, a, TRUE, vmexec);
}
/* resume thread with given arguments */
MRB_API mrb_value
mrb_fiber_resume(mrb_state *mrb, mrb_value fib, mrb_int len, const mrb_value *a)
{
return fiber_switch(mrb, fib, len, a, TRUE, TRUE);
}
/*
* call-seq:
* fiber.alive? -> true or false
*
* Returns true if the fiber can still be resumed. After finishing
* execution of the fiber block this method will always return false.
*/
MRB_API mrb_value
mrb_fiber_alive_p(mrb_state *mrb, mrb_value self)
{
struct mrb_context *c = fiber_check(mrb, self);
return mrb_bool_value(c->status != MRB_FIBER_TERMINATED);
}
#define fiber_alive_p mrb_fiber_alive_p
static mrb_value
fiber_eq(mrb_state *mrb, mrb_value self)
{
mrb_value other;
mrb_get_args(mrb, "o", &other);
if (mrb_type(other) != MRB_TT_FIBER) {
return mrb_false_value();
}
return mrb_bool_value(fiber_ptr(self) == fiber_ptr(other));
}
/*
* call-seq:
* fiber.transfer(args, ...) -> obj
*
* Transfers control to receiver fiber of the method call.
* Unlike <code>resume</code> the receiver wouldn't be pushed to call
* stack of fibers. Instead it will switch to the call stack of
* transferring fiber.
* When resuming a fiber that was transferred to another fiber it would
* cause double resume error. Though when the fiber is re-transferred
* and <code>Fiber.yield</code> is called, the fiber would be resumable.
*/
static mrb_value
fiber_transfer(mrb_state *mrb, mrb_value self)
{
struct mrb_context *c = fiber_check(mrb, self);
mrb_value* a;
mrb_int len;
fiber_check_cfunc(mrb, mrb->c);
mrb_get_args(mrb, "*!", &a, &len);
if (c == mrb->root_c) {
mrb->c->status = MRB_FIBER_TRANSFERRED;
fiber_switch_context(mrb, c);
MARK_CONTEXT_MODIFY(c);
return fiber_result(mrb, a, len);
}
if (c == mrb->c) {
return fiber_result(mrb, a, len);
}
return fiber_switch(mrb, self, len, a, FALSE, FALSE);
}
/* yield values to the caller fiber */
/* mrb_fiber_yield() must be called as `return mrb_fiber_yield(...)` */
MRB_API mrb_value
mrb_fiber_yield(mrb_state *mrb, mrb_int len, const mrb_value *a)
{
struct mrb_context *c = mrb->c;
if (!c->prev) {
mrb_raise(mrb, E_FIBER_ERROR, "can't yield from root fiber");
}
fiber_check_cfunc(mrb, c);
c->prev->status = MRB_FIBER_RUNNING;
c->status = MRB_FIBER_SUSPENDED;
fiber_switch_context(mrb, c->prev);
c->prev = NULL;
if (c->vmexec) {
c->vmexec = FALSE;
mrb->c->ci->acc = CI_ACC_RESUMED;
}
MARK_CONTEXT_MODIFY(mrb->c);
return fiber_result(mrb, a, len);
}
/*
* call-seq:
* Fiber.yield(args, ...) -> obj
*
* Yields control back to the context that resumed the fiber, passing
* along any arguments that were passed to it. The fiber will resume
* processing at this point when <code>resume</code> is called next.
* Any arguments passed to the next <code>resume</code> will be the
*
* mruby limitation: Fiber resume/yield cannot cross C function boundary.
* thus you cannot yield from #initialize which is called by mrb_funcall().
*/
static mrb_value
fiber_yield(mrb_state *mrb, mrb_value self)
{
mrb_value *a;
mrb_int len;
mrb_get_args(mrb, "*!", &a, &len);
return mrb_fiber_yield(mrb, len, a);
}
/*
* call-seq:
* Fiber.current() -> fiber
*
* Returns the current fiber. If you are not running in the context of
* a fiber this method will return the root fiber.
*/
static mrb_value
fiber_current(mrb_state *mrb, mrb_value self)
{
if (!mrb->c->fib) {
struct RFiber *f = (struct RFiber*)mrb_obj_alloc(mrb, MRB_TT_FIBER, mrb_class_ptr(self));
f->cxt = mrb->c;
mrb->c->fib = f;
}
return mrb_obj_value(mrb->c->fib);
}
void
mrb_mruby_fiber_gem_init(mrb_state* mrb)
{
struct RClass *c;
c = mrb_define_class(mrb, "Fiber", mrb->object_class);
MRB_SET_INSTANCE_TT(c, MRB_TT_FIBER);
mrb_define_method(mrb, c, "initialize", fiber_init, MRB_ARGS_NONE());
mrb_define_method(mrb, c, "resume", fiber_resume, MRB_ARGS_ANY());
mrb_define_method(mrb, c, "transfer", fiber_transfer, MRB_ARGS_ANY());
mrb_define_method(mrb, c, "alive?", fiber_alive_p, MRB_ARGS_NONE());
mrb_define_method(mrb, c, "==", fiber_eq, MRB_ARGS_REQ(1));
mrb_define_class_method(mrb, c, "yield", fiber_yield, MRB_ARGS_ANY());
mrb_define_class_method(mrb, c, "current", fiber_current, MRB_ARGS_NONE());
mrb_define_class(mrb, "FiberError", mrb->eStandardError_class);
}
void
mrb_mruby_fiber_gem_final(mrb_state* mrb)
{
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_177_0 |
crossvul-cpp_data_bad_5341_0 | /*
* Copyright (C) 2006 Evgeniy Stepanov <eugeni.stepanov@gmail.com>
*
* This file is part of libass.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "config.h"
#include "ass_compat.h"
#include <assert.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
#include "ass_render.h"
#include "ass_parse.h"
#include "ass_shaper.h"
#define MAX_GLYPHS_INITIAL 1024
#define MAX_LINES_INITIAL 64
#define MAX_BITMAPS_INITIAL 16
#define MAX_SUB_BITMAPS_INITIAL 64
#define SUBPIXEL_MASK 63
#define SUBPIXEL_ACCURACY 7
ASS_Renderer *ass_renderer_init(ASS_Library *library)
{
int error;
FT_Library ft;
ASS_Renderer *priv = 0;
int vmajor, vminor, vpatch;
error = FT_Init_FreeType(&ft);
if (error) {
ass_msg(library, MSGL_FATAL, "%s failed", "FT_Init_FreeType");
goto ass_init_exit;
}
FT_Library_Version(ft, &vmajor, &vminor, &vpatch);
ass_msg(library, MSGL_V, "Raster: FreeType %d.%d.%d",
vmajor, vminor, vpatch);
priv = calloc(1, sizeof(ASS_Renderer));
if (!priv) {
FT_Done_FreeType(ft);
goto ass_init_exit;
}
priv->library = library;
priv->ftlibrary = ft;
// images_root and related stuff is zero-filled in calloc
#if (defined(__i386__) || defined(__x86_64__)) && CONFIG_ASM
if (has_avx2())
priv->engine = &ass_bitmap_engine_avx2;
else if (has_sse2())
priv->engine = &ass_bitmap_engine_sse2;
else
priv->engine = &ass_bitmap_engine_c;
#else
priv->engine = &ass_bitmap_engine_c;
#endif
#if CONFIG_RASTERIZER
rasterizer_init(&priv->rasterizer, 16);
#endif
priv->cache.font_cache = ass_font_cache_create();
priv->cache.bitmap_cache = ass_bitmap_cache_create();
priv->cache.composite_cache = ass_composite_cache_create();
priv->cache.outline_cache = ass_outline_cache_create();
priv->cache.glyph_max = GLYPH_CACHE_MAX;
priv->cache.bitmap_max_size = BITMAP_CACHE_MAX_SIZE;
priv->cache.composite_max_size = COMPOSITE_CACHE_MAX_SIZE;
priv->text_info.max_bitmaps = MAX_BITMAPS_INITIAL;
priv->text_info.max_glyphs = MAX_GLYPHS_INITIAL;
priv->text_info.max_lines = MAX_LINES_INITIAL;
priv->text_info.n_bitmaps = 0;
priv->text_info.combined_bitmaps = calloc(MAX_BITMAPS_INITIAL, sizeof(CombinedBitmapInfo));
priv->text_info.glyphs = calloc(MAX_GLYPHS_INITIAL, sizeof(GlyphInfo));
priv->text_info.lines = calloc(MAX_LINES_INITIAL, sizeof(LineInfo));
priv->settings.font_size_coeff = 1.;
priv->settings.selective_style_overrides = ASS_OVERRIDE_BIT_SELECTIVE_FONT_SCALE;
priv->shaper = ass_shaper_new(0);
ass_shaper_info(library);
#ifdef CONFIG_HARFBUZZ
priv->settings.shaper = ASS_SHAPING_COMPLEX;
#else
priv->settings.shaper = ASS_SHAPING_SIMPLE;
#endif
ass_init_exit:
if (priv)
ass_msg(library, MSGL_V, "Initialized");
else
ass_msg(library, MSGL_ERR, "Initialization failed");
return priv;
}
void ass_renderer_done(ASS_Renderer *render_priv)
{
ass_frame_unref(render_priv->images_root);
ass_frame_unref(render_priv->prev_images_root);
ass_cache_done(render_priv->cache.composite_cache);
ass_cache_done(render_priv->cache.bitmap_cache);
ass_cache_done(render_priv->cache.outline_cache);
ass_shaper_free(render_priv->shaper);
ass_cache_done(render_priv->cache.font_cache);
#if CONFIG_RASTERIZER
rasterizer_done(&render_priv->rasterizer);
#endif
if (render_priv->state.stroker) {
FT_Stroker_Done(render_priv->state.stroker);
render_priv->state.stroker = 0;
}
if (render_priv->fontselect)
ass_fontselect_free(render_priv->fontselect);
if (render_priv->ftlibrary)
FT_Done_FreeType(render_priv->ftlibrary);
free(render_priv->eimg);
free(render_priv->text_info.glyphs);
free(render_priv->text_info.lines);
free(render_priv->text_info.combined_bitmaps);
free(render_priv->settings.default_font);
free(render_priv->settings.default_family);
free(render_priv->user_override_style.FontName);
free(render_priv);
}
/**
* \brief Create a new ASS_Image
* Parameters are the same as ASS_Image fields.
*/
static ASS_Image *my_draw_bitmap(unsigned char *bitmap, int bitmap_w,
int bitmap_h, int stride, int dst_x,
int dst_y, uint32_t color,
CompositeHashValue *source)
{
ASS_ImagePriv *img = malloc(sizeof(ASS_ImagePriv));
if (!img) {
if (!source)
ass_aligned_free(bitmap);
return NULL;
}
img->result.w = bitmap_w;
img->result.h = bitmap_h;
img->result.stride = stride;
img->result.bitmap = bitmap;
img->result.color = color;
img->result.dst_x = dst_x;
img->result.dst_y = dst_y;
img->source = source;
ass_cache_inc_ref(source);
img->ref_count = 0;
return &img->result;
}
/**
* \brief Mapping between script and screen coordinates
*/
static double x2scr_pos(ASS_Renderer *render_priv, double x)
{
return x * render_priv->orig_width / render_priv->font_scale_x / render_priv->track->PlayResX +
render_priv->settings.left_margin;
}
static double x2scr(ASS_Renderer *render_priv, double x)
{
if (render_priv->state.explicit)
return x2scr_pos(render_priv, x);
return x * render_priv->orig_width_nocrop / render_priv->font_scale_x /
render_priv->track->PlayResX +
FFMAX(render_priv->settings.left_margin, 0);
}
static double x2scr_pos_scaled(ASS_Renderer *render_priv, double x)
{
return x * render_priv->orig_width / render_priv->track->PlayResX +
render_priv->settings.left_margin;
}
static double x2scr_scaled(ASS_Renderer *render_priv, double x)
{
if (render_priv->state.explicit)
return x2scr_pos_scaled(render_priv, x);
return x * render_priv->orig_width_nocrop /
render_priv->track->PlayResX +
FFMAX(render_priv->settings.left_margin, 0);
}
/**
* \brief Mapping between script and screen coordinates
*/
static double y2scr_pos(ASS_Renderer *render_priv, double y)
{
return y * render_priv->orig_height / render_priv->track->PlayResY +
render_priv->settings.top_margin;
}
static double y2scr(ASS_Renderer *render_priv, double y)
{
if (render_priv->state.explicit)
return y2scr_pos(render_priv, y);
return y * render_priv->orig_height_nocrop /
render_priv->track->PlayResY +
FFMAX(render_priv->settings.top_margin, 0);
}
// the same for toptitles
static double y2scr_top(ASS_Renderer *render_priv, double y)
{
if (render_priv->state.explicit)
return y2scr_pos(render_priv, y);
if (render_priv->settings.use_margins)
return y * render_priv->orig_height_nocrop /
render_priv->track->PlayResY;
else
return y * render_priv->orig_height_nocrop /
render_priv->track->PlayResY +
FFMAX(render_priv->settings.top_margin, 0);
}
// the same for subtitles
static double y2scr_sub(ASS_Renderer *render_priv, double y)
{
if (render_priv->state.explicit)
return y2scr_pos(render_priv, y);
if (render_priv->settings.use_margins)
return y * render_priv->orig_height_nocrop /
render_priv->track->PlayResY +
FFMAX(render_priv->settings.top_margin, 0)
+ FFMAX(render_priv->settings.bottom_margin, 0);
else
return y * render_priv->orig_height_nocrop /
render_priv->track->PlayResY +
FFMAX(render_priv->settings.top_margin, 0);
}
/*
* \brief Convert bitmap glyphs into ASS_Image list with inverse clipping
*
* Inverse clipping with the following strategy:
* - find rectangle from (x0, y0) to (cx0, y1)
* - find rectangle from (cx0, y0) to (cx1, cy0)
* - find rectangle from (cx0, cy1) to (cx1, y1)
* - find rectangle from (cx1, y0) to (x1, y1)
* These rectangles can be invalid and in this case are discarded.
* Afterwards, they are clipped against the screen coordinates.
* In an additional pass, the rectangles need to be split up left/right for
* karaoke effects. This can result in a lot of bitmaps (6 to be exact).
*/
static ASS_Image **render_glyph_i(ASS_Renderer *render_priv,
Bitmap *bm, int dst_x, int dst_y,
uint32_t color, uint32_t color2, int brk,
ASS_Image **tail, unsigned type,
CompositeHashValue *source)
{
int i, j, x0, y0, x1, y1, cx0, cy0, cx1, cy1, sx, sy, zx, zy;
Rect r[4];
ASS_Image *img;
dst_x += bm->left;
dst_y += bm->top;
// we still need to clip against screen boundaries
zx = x2scr_pos_scaled(render_priv, 0);
zy = y2scr_pos(render_priv, 0);
sx = x2scr_pos_scaled(render_priv, render_priv->track->PlayResX);
sy = y2scr_pos(render_priv, render_priv->track->PlayResY);
x0 = 0;
y0 = 0;
x1 = bm->w;
y1 = bm->h;
cx0 = render_priv->state.clip_x0 - dst_x;
cy0 = render_priv->state.clip_y0 - dst_y;
cx1 = render_priv->state.clip_x1 - dst_x;
cy1 = render_priv->state.clip_y1 - dst_y;
// calculate rectangles and discard invalid ones while we're at it.
i = 0;
r[i].x0 = x0;
r[i].y0 = y0;
r[i].x1 = (cx0 > x1) ? x1 : cx0;
r[i].y1 = y1;
if (r[i].x1 > r[i].x0 && r[i].y1 > r[i].y0) i++;
r[i].x0 = (cx0 < 0) ? x0 : cx0;
r[i].y0 = y0;
r[i].x1 = (cx1 > x1) ? x1 : cx1;
r[i].y1 = (cy0 > y1) ? y1 : cy0;
if (r[i].x1 > r[i].x0 && r[i].y1 > r[i].y0) i++;
r[i].x0 = (cx0 < 0) ? x0 : cx0;
r[i].y0 = (cy1 < 0) ? y0 : cy1;
r[i].x1 = (cx1 > x1) ? x1 : cx1;
r[i].y1 = y1;
if (r[i].x1 > r[i].x0 && r[i].y1 > r[i].y0) i++;
r[i].x0 = (cx1 < 0) ? x0 : cx1;
r[i].y0 = y0;
r[i].x1 = x1;
r[i].y1 = y1;
if (r[i].x1 > r[i].x0 && r[i].y1 > r[i].y0) i++;
// clip each rectangle to screen coordinates
for (j = 0; j < i; j++) {
r[j].x0 = (r[j].x0 + dst_x < zx) ? zx - dst_x : r[j].x0;
r[j].y0 = (r[j].y0 + dst_y < zy) ? zy - dst_y : r[j].y0;
r[j].x1 = (r[j].x1 + dst_x > sx) ? sx - dst_x : r[j].x1;
r[j].y1 = (r[j].y1 + dst_y > sy) ? sy - dst_y : r[j].y1;
}
// draw the rectangles
for (j = 0; j < i; j++) {
int lbrk = brk;
// kick out rectangles that are invalid now
if (r[j].x1 <= r[j].x0 || r[j].y1 <= r[j].y0)
continue;
// split up into left and right for karaoke, if needed
if (lbrk > r[j].x0) {
if (lbrk > r[j].x1) lbrk = r[j].x1;
img = my_draw_bitmap(bm->buffer + r[j].y0 * bm->stride + r[j].x0,
lbrk - r[j].x0, r[j].y1 - r[j].y0, bm->stride,
dst_x + r[j].x0, dst_y + r[j].y0, color, source);
if (!img) break;
img->type = type;
*tail = img;
tail = &img->next;
}
if (lbrk < r[j].x1) {
if (lbrk < r[j].x0) lbrk = r[j].x0;
img = my_draw_bitmap(bm->buffer + r[j].y0 * bm->stride + lbrk,
r[j].x1 - lbrk, r[j].y1 - r[j].y0, bm->stride,
dst_x + lbrk, dst_y + r[j].y0, color2, source);
if (!img) break;
img->type = type;
*tail = img;
tail = &img->next;
}
}
return tail;
}
/**
* \brief convert bitmap glyph into ASS_Image struct(s)
* \param bit freetype bitmap glyph, FT_PIXEL_MODE_GRAY
* \param dst_x bitmap x coordinate in video frame
* \param dst_y bitmap y coordinate in video frame
* \param color first color, RGBA
* \param color2 second color, RGBA
* \param brk x coordinate relative to glyph origin, color is used to the left of brk, color2 - to the right
* \param tail pointer to the last image's next field, head of the generated list should be stored here
* \return pointer to the new list tail
* Performs clipping. Uses my_draw_bitmap for actual bitmap convertion.
*/
static ASS_Image **
render_glyph(ASS_Renderer *render_priv, Bitmap *bm, int dst_x, int dst_y,
uint32_t color, uint32_t color2, int brk, ASS_Image **tail,
unsigned type, CompositeHashValue *source)
{
// Inverse clipping in use?
if (render_priv->state.clip_mode)
return render_glyph_i(render_priv, bm, dst_x, dst_y, color, color2,
brk, tail, type, source);
// brk is relative to dst_x
// color = color left of brk
// color2 = color right of brk
int b_x0, b_y0, b_x1, b_y1; // visible part of the bitmap
int clip_x0, clip_y0, clip_x1, clip_y1;
int tmp;
ASS_Image *img;
dst_x += bm->left;
dst_y += bm->top;
brk -= bm->left;
// clipping
clip_x0 = FFMINMAX(render_priv->state.clip_x0, 0, render_priv->width);
clip_y0 = FFMINMAX(render_priv->state.clip_y0, 0, render_priv->height);
clip_x1 = FFMINMAX(render_priv->state.clip_x1, 0, render_priv->width);
clip_y1 = FFMINMAX(render_priv->state.clip_y1, 0, render_priv->height);
b_x0 = 0;
b_y0 = 0;
b_x1 = bm->w;
b_y1 = bm->h;
tmp = dst_x - clip_x0;
if (tmp < 0) {
b_x0 = -tmp;
render_priv->state.has_clips = 1;
}
tmp = dst_y - clip_y0;
if (tmp < 0) {
b_y0 = -tmp;
render_priv->state.has_clips = 1;
}
tmp = clip_x1 - dst_x - bm->w;
if (tmp < 0) {
b_x1 = bm->w + tmp;
render_priv->state.has_clips = 1;
}
tmp = clip_y1 - dst_y - bm->h;
if (tmp < 0) {
b_y1 = bm->h + tmp;
render_priv->state.has_clips = 1;
}
if ((b_y0 >= b_y1) || (b_x0 >= b_x1))
return tail;
if (brk > b_x0) { // draw left part
if (brk > b_x1)
brk = b_x1;
img = my_draw_bitmap(bm->buffer + bm->stride * b_y0 + b_x0,
brk - b_x0, b_y1 - b_y0, bm->stride,
dst_x + b_x0, dst_y + b_y0, color, source);
if (!img) return tail;
img->type = type;
*tail = img;
tail = &img->next;
}
if (brk < b_x1) { // draw right part
if (brk < b_x0)
brk = b_x0;
img = my_draw_bitmap(bm->buffer + bm->stride * b_y0 + brk,
b_x1 - brk, b_y1 - b_y0, bm->stride,
dst_x + brk, dst_y + b_y0, color2, source);
if (!img) return tail;
img->type = type;
*tail = img;
tail = &img->next;
}
return tail;
}
// Calculate bitmap memory footprint
static inline size_t bitmap_size(Bitmap *bm)
{
return bm ? sizeof(Bitmap) + bm->stride * bm->h : 0;
}
/**
* Iterate through a list of bitmaps and blend with clip vector, if
* applicable. The blended bitmaps are added to a free list which is freed
* at the start of a new frame.
*/
static void blend_vector_clip(ASS_Renderer *render_priv,
ASS_Image *head)
{
ASS_Drawing *drawing = render_priv->state.clip_drawing;
if (!drawing)
return;
// Try to get mask from cache
BitmapHashKey key;
memset(&key, 0, sizeof(key));
key.type = BITMAP_CLIP;
key.u.clip.text = drawing->text;
BitmapHashValue *val;
if (!ass_cache_get(render_priv->cache.bitmap_cache, &key, &val)) {
if (!val)
return;
val->bm = val->bm_o = NULL;
// Not found in cache, parse and rasterize it
ASS_Outline *outline = ass_drawing_parse(drawing, 1);
if (!outline) {
ass_msg(render_priv->library, MSGL_WARN,
"Clip vector parsing failed. Skipping.");
ass_cache_commit(val, sizeof(BitmapHashKey) + sizeof(BitmapHashValue));
ass_cache_dec_ref(val);
return;
}
// We need to translate the clip according to screen borders
if (render_priv->settings.left_margin != 0 ||
render_priv->settings.top_margin != 0) {
FT_Vector trans = {
.x = int_to_d6(render_priv->settings.left_margin),
.y = -int_to_d6(render_priv->settings.top_margin),
};
outline_translate(outline, trans.x, trans.y);
}
val->bm = outline_to_bitmap(render_priv, outline, 0);
ass_cache_commit(val, bitmap_size(val->bm) +
sizeof(BitmapHashKey) + sizeof(BitmapHashValue));
}
Bitmap *clip_bm = val->bm;
if (!clip_bm) {
ass_cache_dec_ref(val);
return;
}
// Iterate through bitmaps and blend/clip them
for (ASS_Image *cur = head; cur; cur = cur->next) {
int left, top, right, bottom, w, h;
int ax, ay, aw, ah, as;
int bx, by, bw, bh, bs;
int aleft, atop, bleft, btop;
unsigned char *abuffer, *bbuffer, *nbuffer;
render_priv->state.has_clips = 1;
abuffer = cur->bitmap;
bbuffer = clip_bm->buffer;
ax = cur->dst_x;
ay = cur->dst_y;
aw = cur->w;
ah = cur->h;
as = cur->stride;
bx = clip_bm->left;
by = clip_bm->top;
bw = clip_bm->w;
bh = clip_bm->h;
bs = clip_bm->stride;
// Calculate overlap coordinates
left = (ax > bx) ? ax : bx;
top = (ay > by) ? ay : by;
right = ((ax + aw) < (bx + bw)) ? (ax + aw) : (bx + bw);
bottom = ((ay + ah) < (by + bh)) ? (ay + ah) : (by + bh);
aleft = left - ax;
atop = top - ay;
w = right - left;
h = bottom - top;
bleft = left - bx;
btop = top - by;
if (render_priv->state.clip_drawing_mode) {
// Inverse clip
if (ax + aw < bx || ay + ah < by || ax > bx + bw ||
ay > by + bh || !h || !w) {
continue;
}
// Allocate new buffer and add to free list
nbuffer = ass_aligned_alloc(32, as * ah, false);
if (!nbuffer)
break;
// Blend together
memcpy(nbuffer, abuffer, ((ah - 1) * as) + aw);
render_priv->engine->sub_bitmaps(nbuffer + atop * as + aleft, as,
bbuffer + btop * bs + bleft, bs,
h, w);
} else {
// Regular clip
if (ax + aw < bx || ay + ah < by || ax > bx + bw ||
ay > by + bh || !h || !w) {
cur->w = cur->h = cur->stride = 0;
continue;
}
// Allocate new buffer and add to free list
unsigned align = (w >= 16) ? 16 : ((w >= 8) ? 8 : 1);
unsigned ns = ass_align(align, w);
nbuffer = ass_aligned_alloc(align, ns * h, false);
if (!nbuffer)
break;
// Blend together
render_priv->engine->mul_bitmaps(nbuffer, ns,
abuffer + atop * as + aleft, as,
bbuffer + btop * bs + bleft, bs,
w, h);
cur->dst_x += aleft;
cur->dst_y += atop;
cur->w = w;
cur->h = h;
cur->stride = ns;
}
cur->bitmap = nbuffer;
ASS_ImagePriv *priv = (ASS_ImagePriv *) cur;
ass_cache_dec_ref(priv->source);
priv->source = NULL;
}
ass_cache_dec_ref(val);
}
/**
* \brief Convert TextInfo struct to ASS_Image list
* Splits glyphs in halves when needed (for \kf karaoke).
*/
static ASS_Image *render_text(ASS_Renderer *render_priv)
{
ASS_Image *head;
ASS_Image **tail = &head;
unsigned n_bitmaps = render_priv->text_info.n_bitmaps;
CombinedBitmapInfo *bitmaps = render_priv->text_info.combined_bitmaps;
for (unsigned i = 0; i < n_bitmaps; i++) {
CombinedBitmapInfo *info = &bitmaps[i];
if (!info->bm_s || render_priv->state.border_style == 4)
continue;
tail =
render_glyph(render_priv, info->bm_s, info->x, info->y, info->c[3], 0,
1000000, tail, IMAGE_TYPE_SHADOW, info->image);
}
for (unsigned i = 0; i < n_bitmaps; i++) {
CombinedBitmapInfo *info = &bitmaps[i];
if (!info->bm_o)
continue;
if ((info->effect_type == EF_KARAOKE_KO)
&& (info->effect_timing <= info->first_pos_x)) {
// do nothing
} else {
tail =
render_glyph(render_priv, info->bm_o, info->x, info->y, info->c[2],
0, 1000000, tail, IMAGE_TYPE_OUTLINE, info->image);
}
}
for (unsigned i = 0; i < n_bitmaps; i++) {
CombinedBitmapInfo *info = &bitmaps[i];
if (!info->bm)
continue;
if ((info->effect_type == EF_KARAOKE)
|| (info->effect_type == EF_KARAOKE_KO)) {
if (info->effect_timing > info->first_pos_x)
tail =
render_glyph(render_priv, info->bm, info->x, info->y,
info->c[0], 0, 1000000, tail,
IMAGE_TYPE_CHARACTER, info->image);
else
tail =
render_glyph(render_priv, info->bm, info->x, info->y,
info->c[1], 0, 1000000, tail,
IMAGE_TYPE_CHARACTER, info->image);
} else if (info->effect_type == EF_KARAOKE_KF) {
tail =
render_glyph(render_priv, info->bm, info->x, info->y, info->c[0],
info->c[1], info->effect_timing, tail,
IMAGE_TYPE_CHARACTER, info->image);
} else
tail =
render_glyph(render_priv, info->bm, info->x, info->y, info->c[0],
0, 1000000, tail, IMAGE_TYPE_CHARACTER, info->image);
}
for (unsigned i = 0; i < n_bitmaps; i++)
ass_cache_dec_ref(bitmaps[i].image);
*tail = 0;
blend_vector_clip(render_priv, head);
return head;
}
static void compute_string_bbox(TextInfo *text, DBBox *bbox)
{
int i;
if (text->length > 0) {
bbox->xMin = 32000;
bbox->xMax = -32000;
bbox->yMin = -1 * text->lines[0].asc + d6_to_double(text->glyphs[0].pos.y);
bbox->yMax = text->height - text->lines[0].asc +
d6_to_double(text->glyphs[0].pos.y);
for (i = 0; i < text->length; ++i) {
GlyphInfo *info = text->glyphs + i;
if (info->skip) continue;
double s = d6_to_double(info->pos.x);
double e = s + d6_to_double(info->cluster_advance.x);
bbox->xMin = FFMIN(bbox->xMin, s);
bbox->xMax = FFMAX(bbox->xMax, e);
}
} else
bbox->xMin = bbox->xMax = bbox->yMin = bbox->yMax = 0.;
}
static ASS_Style *handle_selective_style_overrides(ASS_Renderer *render_priv,
ASS_Style *rstyle)
{
// The script style is the one the event was declared with.
ASS_Style *script = render_priv->track->styles +
render_priv->state.event->Style;
// The user style was set with ass_set_selective_style_override().
ASS_Style *user = &render_priv->user_override_style;
ASS_Style *new = &render_priv->state.override_style_temp_storage;
int explicit = event_has_hard_overrides(render_priv->state.event->Text) ||
render_priv->state.evt_type != EVENT_NORMAL;
int requested = render_priv->settings.selective_style_overrides;
double scale;
user->Name = "OverrideStyle"; // name insignificant
// Either the event's style, or the style forced with a \r tag.
if (!rstyle)
rstyle = script;
// Create a new style that contains a mix of the original style and
// user_style (the user's override style). Copy only fields from the
// script's style that are deemed necessary.
*new = *rstyle;
render_priv->state.explicit = explicit;
render_priv->state.apply_font_scale =
!explicit || !(requested & ASS_OVERRIDE_BIT_SELECTIVE_FONT_SCALE);
// On positioned events, do not apply most overrides.
if (explicit)
requested = 0;
if (requested & ASS_OVERRIDE_BIT_STYLE)
requested |= ASS_OVERRIDE_BIT_FONT_NAME |
ASS_OVERRIDE_BIT_FONT_SIZE_FIELDS |
ASS_OVERRIDE_BIT_COLORS |
ASS_OVERRIDE_BIT_BORDER |
ASS_OVERRIDE_BIT_ATTRIBUTES;
// Copies fields even not covered by any of the other bits.
if (requested & ASS_OVERRIDE_FULL_STYLE)
*new = *user;
// The user style is supposed to be independent of the script resolution.
// Treat the user style's values as if they were specified for a script with
// PlayResY=288, and rescale the values to the current script.
scale = render_priv->track->PlayResY / 288.0;
if (requested & ASS_OVERRIDE_BIT_FONT_SIZE_FIELDS) {
new->FontSize = user->FontSize * scale;
new->Spacing = user->Spacing * scale;
new->ScaleX = user->ScaleX;
new->ScaleY = user->ScaleY;
}
if (requested & ASS_OVERRIDE_BIT_FONT_NAME) {
new->FontName = user->FontName;
new->treat_fontname_as_pattern = user->treat_fontname_as_pattern;
}
if (requested & ASS_OVERRIDE_BIT_COLORS) {
new->PrimaryColour = user->PrimaryColour;
new->SecondaryColour = user->SecondaryColour;
new->OutlineColour = user->OutlineColour;
new->BackColour = user->BackColour;
}
if (requested & ASS_OVERRIDE_BIT_ATTRIBUTES) {
new->Bold = user->Bold;
new->Italic = user->Italic;
new->Underline = user->Underline;
new->StrikeOut = user->StrikeOut;
}
if (requested & ASS_OVERRIDE_BIT_BORDER) {
new->BorderStyle = user->BorderStyle;
new->Outline = user->Outline * scale;
new->Shadow = user->Shadow * scale;
}
if (requested & ASS_OVERRIDE_BIT_ALIGNMENT)
new->Alignment = user->Alignment;
if (requested & ASS_OVERRIDE_BIT_MARGINS) {
new->MarginL = user->MarginL;
new->MarginR = user->MarginR;
new->MarginV = user->MarginV;
}
if (!new->FontName)
new->FontName = rstyle->FontName;
render_priv->state.style = new;
render_priv->state.overrides = requested;
return new;
}
static void init_font_scale(ASS_Renderer *render_priv)
{
ASS_Settings *settings_priv = &render_priv->settings;
render_priv->font_scale = ((double) render_priv->orig_height) /
render_priv->track->PlayResY;
if (settings_priv->storage_height)
render_priv->blur_scale = ((double) render_priv->orig_height) /
settings_priv->storage_height;
else
render_priv->blur_scale = 1.;
if (render_priv->track->ScaledBorderAndShadow)
render_priv->border_scale =
((double) render_priv->orig_height) /
render_priv->track->PlayResY;
else
render_priv->border_scale = render_priv->blur_scale;
if (!settings_priv->storage_height)
render_priv->blur_scale = render_priv->border_scale;
if (render_priv->state.apply_font_scale) {
render_priv->font_scale *= settings_priv->font_size_coeff;
render_priv->border_scale *= settings_priv->font_size_coeff;
render_priv->blur_scale *= settings_priv->font_size_coeff;
}
}
/**
* \brief partially reset render_context to style values
* Works like {\r}: resets some style overrides
*/
void reset_render_context(ASS_Renderer *render_priv, ASS_Style *style)
{
style = handle_selective_style_overrides(render_priv, style);
init_font_scale(render_priv);
render_priv->state.c[0] = style->PrimaryColour;
render_priv->state.c[1] = style->SecondaryColour;
render_priv->state.c[2] = style->OutlineColour;
render_priv->state.c[3] = style->BackColour;
render_priv->state.flags =
(style->Underline ? DECO_UNDERLINE : 0) |
(style->StrikeOut ? DECO_STRIKETHROUGH : 0);
render_priv->state.font_size = style->FontSize;
free(render_priv->state.family);
render_priv->state.family = NULL;
render_priv->state.family = strdup(style->FontName);
render_priv->state.treat_family_as_pattern =
style->treat_fontname_as_pattern;
render_priv->state.bold = style->Bold;
render_priv->state.italic = style->Italic;
update_font(render_priv);
render_priv->state.border_style = style->BorderStyle;
render_priv->state.border_x = style->Outline;
render_priv->state.border_y = style->Outline;
change_border(render_priv, render_priv->state.border_x, render_priv->state.border_y);
render_priv->state.scale_x = style->ScaleX;
render_priv->state.scale_y = style->ScaleY;
render_priv->state.hspacing = style->Spacing;
render_priv->state.be = 0;
render_priv->state.blur = style->Blur;
render_priv->state.shadow_x = style->Shadow;
render_priv->state.shadow_y = style->Shadow;
render_priv->state.frx = render_priv->state.fry = 0.;
render_priv->state.frz = M_PI * style->Angle / 180.;
render_priv->state.fax = render_priv->state.fay = 0.;
render_priv->state.font_encoding = style->Encoding;
}
/**
* \brief Start new event. Reset render_priv->state.
*/
static void
init_render_context(ASS_Renderer *render_priv, ASS_Event *event)
{
render_priv->state.event = event;
render_priv->state.parsed_tags = 0;
render_priv->state.has_clips = 0;
render_priv->state.evt_type = EVENT_NORMAL;
reset_render_context(render_priv, NULL);
render_priv->state.wrap_style = render_priv->track->WrapStyle;
render_priv->state.alignment = render_priv->state.style->Alignment;
render_priv->state.pos_x = 0;
render_priv->state.pos_y = 0;
render_priv->state.org_x = 0;
render_priv->state.org_y = 0;
render_priv->state.have_origin = 0;
render_priv->state.clip_x0 = 0;
render_priv->state.clip_y0 = 0;
render_priv->state.clip_x1 = render_priv->track->PlayResX;
render_priv->state.clip_y1 = render_priv->track->PlayResY;
render_priv->state.clip_mode = 0;
render_priv->state.detect_collisions = 1;
render_priv->state.fade = 0;
render_priv->state.drawing_scale = 0;
render_priv->state.pbo = 0;
render_priv->state.effect_type = EF_NONE;
render_priv->state.effect_timing = 0;
render_priv->state.effect_skip_timing = 0;
apply_transition_effects(render_priv, event);
}
static void free_render_context(ASS_Renderer *render_priv)
{
ass_cache_dec_ref(render_priv->state.font);
free(render_priv->state.family);
ass_drawing_free(render_priv->state.clip_drawing);
render_priv->state.font = NULL;
render_priv->state.family = NULL;
render_priv->state.clip_drawing = NULL;
TextInfo *text_info = &render_priv->text_info;
for (int n = 0; n < text_info->length; n++)
ass_drawing_free(text_info->glyphs[n].drawing);
text_info->length = 0;
}
/*
* Replace the outline of a glyph by a contour which makes up a simple
* opaque rectangle.
*/
static void draw_opaque_box(ASS_Renderer *render_priv, GlyphInfo *info,
int asc, int desc, ASS_Outline *ol,
FT_Vector advance, int sx, int sy)
{
int adv = advance.x;
double scale_y = info->orig_scale_y;
double scale_x = info->orig_scale_x;
// to avoid gaps
sx = FFMAX(64, sx);
sy = FFMAX(64, sy);
// Emulate the WTFish behavior of VSFilter, i.e. double-scale
// the sizes of the opaque box.
adv += double_to_d6(info->hspacing * render_priv->font_scale * scale_x);
adv *= scale_x;
sx *= scale_x;
sy *= scale_y;
desc *= scale_y;
desc += asc * (scale_y - 1.0);
FT_Vector points[4] = {
{ .x = -sx, .y = asc + sy },
{ .x = adv + sx, .y = asc + sy },
{ .x = adv + sx, .y = -desc - sy },
{ .x = -sx, .y = -desc - sy },
};
ol->n_points = ol->n_contours = 0;
if (!outline_alloc(ol, 4, 1))
return;
for (int i = 0; i < 4; ++i) {
ol->points[ol->n_points] = points[i];
ol->tags[ol->n_points++] = 1;
}
ol->contours[ol->n_contours++] = ol->n_points - 1;
}
/*
* Stroke an outline glyph in x/y direction. Applies various fixups to get
* around limitations of the FreeType stroker.
*/
static void stroke_outline(ASS_Renderer *render_priv, ASS_Outline *outline,
int sx, int sy)
{
if (sx <= 0 && sy <= 0)
return;
fix_freetype_stroker(outline, sx, sy);
size_t n_points = outline->n_points;
if (n_points > SHRT_MAX) {
ass_msg(render_priv->library, MSGL_WARN, "Too many outline points: %d",
outline->n_points);
n_points = SHRT_MAX;
}
size_t n_contours = FFMIN(outline->n_contours, SHRT_MAX);
short contours_small[EFFICIENT_CONTOUR_COUNT];
short *contours = contours_small;
short *contours_large = NULL;
if (n_contours > EFFICIENT_CONTOUR_COUNT) {
contours_large = malloc(n_contours * sizeof(short));
if (!contours_large)
return;
contours = contours_large;
}
for (size_t i = 0; i < n_contours; ++i)
contours[i] = FFMIN(outline->contours[i], n_points - 1);
FT_Outline ftol;
ftol.n_points = n_points;
ftol.n_contours = n_contours;
ftol.points = outline->points;
ftol.tags = outline->tags;
ftol.contours = contours;
ftol.flags = 0;
// Borders are equal; use the regular stroker
if (sx == sy && render_priv->state.stroker) {
int error;
FT_StrokerBorder border = FT_Outline_GetOutsideBorder(&ftol);
error = FT_Stroker_ParseOutline(render_priv->state.stroker, &ftol, 0);
if (error) {
ass_msg(render_priv->library, MSGL_WARN,
"FT_Stroker_ParseOutline failed, error: %d", error);
}
unsigned new_points, new_contours;
error = FT_Stroker_GetBorderCounts(render_priv->state.stroker, border,
&new_points, &new_contours);
if (error) {
ass_msg(render_priv->library, MSGL_WARN,
"FT_Stroker_GetBorderCounts failed, error: %d", error);
}
outline_free(outline);
outline->n_points = outline->n_contours = 0;
if (new_contours > FFMAX(EFFICIENT_CONTOUR_COUNT, n_contours)) {
if (!ASS_REALLOC_ARRAY(contours_large, new_contours)) {
free(contours_large);
return;
}
}
n_points = new_points;
n_contours = new_contours;
if (!outline_alloc(outline, n_points, n_contours)) {
ass_msg(render_priv->library, MSGL_WARN,
"Not enough memory for border outline");
free(contours_large);
return;
}
ftol.n_points = ftol.n_contours = 0;
ftol.points = outline->points;
ftol.tags = outline->tags;
FT_Stroker_ExportBorder(render_priv->state.stroker, border, &ftol);
outline->n_points = n_points;
outline->n_contours = n_contours;
for (size_t i = 0; i < n_contours; ++i)
outline->contours[i] = (unsigned short) contours[i];
// "Stroke" with the outline emboldener (in two passes if needed).
// The outlines look uglier, but the emboldening never adds any points
} else {
#if (FREETYPE_MAJOR > 2) || \
((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR > 4)) || \
((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR == 4) && (FREETYPE_PATCH >= 10))
FT_Outline_EmboldenXY(&ftol, sx * 2, sy * 2);
FT_Outline_Translate(&ftol, -sx, -sy);
#else
int i;
FT_Outline nol;
FT_Outline_New(render_priv->ftlibrary, ftol.n_points,
ftol.n_contours, &nol);
FT_Outline_Copy(&ftol, &nol);
FT_Outline_Embolden(&ftol, sx * 2);
FT_Outline_Translate(&ftol, -sx, -sx);
FT_Outline_Embolden(&nol, sy * 2);
FT_Outline_Translate(&nol, -sy, -sy);
for (i = 0; i < ftol.n_points; i++)
ftol.points[i].y = nol.points[i].y;
FT_Outline_Done(render_priv->ftlibrary, &nol);
#endif
}
free(contours_large);
}
/**
* \brief Prepare glyph hash
*/
static void
fill_glyph_hash(ASS_Renderer *priv, OutlineHashKey *outline_key,
GlyphInfo *info)
{
if (info->drawing) {
DrawingHashKey *key = &outline_key->u.drawing;
outline_key->type = OUTLINE_DRAWING;
key->scale_x = double_to_d16(info->scale_x);
key->scale_y = double_to_d16(info->scale_y);
key->outline.x = double_to_d16(info->border_x);
key->outline.y = double_to_d16(info->border_y);
key->border_style = info->border_style;
// hpacing only matters for opaque box borders (see draw_opaque_box),
// so for normal borders, maximize cache utility by ignoring it
key->hspacing =
info->border_style == 3 ? double_to_d16(info->hspacing) : 0;
key->hash = info->drawing->hash;
key->text = info->drawing->text;
key->pbo = info->drawing->pbo;
key->scale = info->drawing->scale;
} else {
GlyphHashKey *key = &outline_key->u.glyph;
outline_key->type = OUTLINE_GLYPH;
key->font = info->font;
key->size = info->font_size;
key->face_index = info->face_index;
key->glyph_index = info->glyph_index;
key->bold = info->bold;
key->italic = info->italic;
key->scale_x = double_to_d16(info->scale_x);
key->scale_y = double_to_d16(info->scale_y);
key->outline.x = double_to_d16(info->border_x);
key->outline.y = double_to_d16(info->border_y);
key->flags = info->flags;
key->border_style = info->border_style;
key->hspacing =
info->border_style == 3 ? double_to_d16(info->hspacing) : 0;
}
}
/**
* \brief Prepare combined-bitmap hash
*/
static void fill_composite_hash(CompositeHashKey *hk, CombinedBitmapInfo *info)
{
hk->filter = info->filter;
hk->bitmap_count = info->bitmap_count;
hk->bitmaps = info->bitmaps;
}
/**
* \brief Get normal and outline (border) glyphs
* \param info out: struct filled with extracted data
* Tries to get both glyphs from cache.
* If they can't be found, gets a glyph from font face, generates outline with FT_Stroker,
* and add them to cache.
* The glyphs are returned in info->glyph and info->outline_glyph
*/
static void
get_outline_glyph(ASS_Renderer *priv, GlyphInfo *info)
{
memset(&info->hash_key, 0, sizeof(info->hash_key));
OutlineHashKey key;
OutlineHashValue *val;
fill_glyph_hash(priv, &key, info);
if (!ass_cache_get(priv->cache.outline_cache, &key, &val)) {
if (!val)
return;
memset(val, 0, sizeof(*val));
if (info->drawing) {
ASS_Drawing *drawing = info->drawing;
ass_drawing_hash(drawing);
if(!ass_drawing_parse(drawing, 0)) {
ass_cache_commit(val, 1);
ass_cache_dec_ref(val);
return;
}
val->outline = outline_copy(&drawing->outline);
val->advance.x = drawing->advance.x;
val->advance.y = drawing->advance.y;
val->asc = drawing->asc;
val->desc = drawing->desc;
} else {
ass_face_set_size(info->font->faces[info->face_index],
info->font_size);
ass_font_set_transform(info->font, info->scale_x,
info->scale_y, NULL);
FT_Glyph glyph =
ass_font_get_glyph(info->font,
info->symbol, info->face_index, info->glyph_index,
priv->settings.hinting, info->flags);
if (glyph != NULL) {
val->outline = outline_convert(&((FT_OutlineGlyph) glyph)->outline);
if (priv->settings.shaper == ASS_SHAPING_SIMPLE) {
val->advance.x = d16_to_d6(glyph->advance.x);
val->advance.y = d16_to_d6(glyph->advance.y);
}
FT_Done_Glyph(glyph);
ass_font_get_asc_desc(info->font, info->symbol,
&val->asc, &val->desc);
val->asc *= info->scale_y;
val->desc *= info->scale_y;
}
}
if (!val->outline) {
ass_cache_commit(val, 1);
ass_cache_dec_ref(val);
return;
}
outline_get_cbox(val->outline, &val->bbox_scaled);
if (info->border_style == 3) {
val->border = calloc(1, sizeof(ASS_Outline));
if (!val->border) {
outline_free(val->outline);
free(val->outline);
val->outline = NULL;
ass_cache_commit(val, 1);
ass_cache_dec_ref(val);
return;
}
FT_Vector advance;
if (priv->settings.shaper == ASS_SHAPING_SIMPLE || info->drawing)
advance = val->advance;
else
advance = info->advance;
draw_opaque_box(priv, info, val->asc, val->desc, val->border, advance,
double_to_d6(info->border_x * priv->border_scale),
double_to_d6(info->border_y * priv->border_scale));
} else if ((info->border_x > 0 || info->border_y > 0)
&& double_to_d6(info->scale_x) && double_to_d6(info->scale_y)) {
change_border(priv, info->border_x, info->border_y);
val->border = outline_copy(val->outline);
stroke_outline(priv, val->border,
double_to_d6(info->border_x * priv->border_scale),
double_to_d6(info->border_y * priv->border_scale));
}
ass_cache_commit(val, 1);
}
if (!val->outline) {
ass_cache_dec_ref(val);
return;
}
info->hash_key.u.outline.outline = val;
info->outline = val->outline;
info->border = val->border;
info->bbox = val->bbox_scaled;
if (info->drawing || priv->settings.shaper == ASS_SHAPING_SIMPLE) {
info->cluster_advance.x = info->advance.x = val->advance.x;
info->cluster_advance.y = info->advance.y = val->advance.y;
}
info->asc = val->asc;
info->desc = val->desc;
}
/**
* \brief Apply transformation to outline points of a glyph
* Applies rotations given by frx, fry and frz and projects the points back
* onto the screen plane.
*/
static void
transform_3d_points(FT_Vector shift, ASS_Outline *outline, double frx, double fry,
double frz, double fax, double fay, double scale,
int yshift)
{
double sx = sin(frx);
double sy = sin(fry);
double sz = sin(frz);
double cx = cos(frx);
double cy = cos(fry);
double cz = cos(frz);
FT_Vector *p = outline->points;
double x, y, z, xx, yy, zz;
int dist;
dist = 20000 * scale;
for (size_t i = 0; i < outline->n_points; ++i) {
x = (double) p[i].x + shift.x + (fax * (yshift - p[i].y));
y = (double) p[i].y + shift.y + (-fay * p[i].x);
z = 0.;
xx = x * cz + y * sz;
yy = -(x * sz - y * cz);
zz = z;
x = xx;
y = yy * cx + zz * sx;
z = yy * sx - zz * cx;
xx = x * cy + z * sy;
yy = y;
zz = x * sy - z * cy;
zz = FFMAX(zz, 1000 - dist);
x = (xx * dist) / (zz + dist);
y = (yy * dist) / (zz + dist);
p[i].x = x - shift.x + 0.5;
p[i].y = y - shift.y + 0.5;
}
}
/**
* \brief Apply 3d transformation to several objects
* \param shift FreeType vector
* \param glyph FreeType glyph
* \param glyph2 FreeType glyph
* \param frx x-axis rotation angle
* \param fry y-axis rotation angle
* \param frz z-axis rotation angle
* Rotates both glyphs by frx, fry and frz. Shift vector is added before rotation and subtracted after it.
*/
static void
transform_3d(FT_Vector shift, ASS_Outline *outline, ASS_Outline *border,
double frx, double fry, double frz, double fax, double fay,
double scale, int yshift)
{
frx = -frx;
frz = -frz;
if (frx != 0. || fry != 0. || frz != 0. || fax != 0. || fay != 0.) {
if (outline)
transform_3d_points(shift, outline, frx, fry, frz,
fax, fay, scale, yshift);
if (border)
transform_3d_points(shift, border, frx, fry, frz,
fax, fay, scale, yshift);
}
}
/**
* \brief Get bitmaps for a glyph
* \param info glyph info
* Tries to get glyph bitmaps from bitmap cache.
* If they can't be found, they are generated by rotating and rendering the glyph.
* After that, bitmaps are added to the cache.
* They are returned in info->bm (glyph), info->bm_o (outline) and info->bm_s (shadow).
*/
static void
get_bitmap_glyph(ASS_Renderer *render_priv, GlyphInfo *info)
{
if (!info->outline || info->symbol == '\n' || info->symbol == 0 || info->skip)
return;
BitmapHashValue *val;
OutlineBitmapHashKey *key = &info->hash_key.u.outline;
if (ass_cache_get(render_priv->cache.bitmap_cache, &info->hash_key, &val)) {
info->image = val;
return;
}
if (!val)
return;
ASS_Outline *outline = outline_copy(info->outline);
ASS_Outline *border = outline_copy(info->border);
// calculating rotation shift vector (from rotation origin to the glyph basepoint)
FT_Vector shift = { key->shift_x, key->shift_y };
double scale_x = render_priv->font_scale_x;
double fax_scaled = info->fax / info->scale_y * info->scale_x;
double fay_scaled = info->fay / info->scale_x * info->scale_y;
// apply rotation
// use blur_scale because, like blurs, VSFilter forgets to scale this
transform_3d(shift, outline, border,
info->frx, info->fry, info->frz, fax_scaled,
fay_scaled, render_priv->blur_scale, info->asc);
// PAR correction scaling
FT_Matrix m = { double_to_d16(scale_x), 0,
0, double_to_d16(1.0) };
// subpixel shift
if (outline) {
if (scale_x != 1.0)
outline_transform(outline, &m);
outline_translate(outline, key->advance.x, -key->advance.y);
}
if (border) {
if (scale_x != 1.0)
outline_transform(border, &m);
outline_translate(border, key->advance.x, -key->advance.y);
}
// render glyph
int error = outline_to_bitmap2(render_priv, outline, border,
&val->bm, &val->bm_o);
if (error)
info->symbol = 0;
ass_cache_commit(val, bitmap_size(val->bm) + bitmap_size(val->bm_o) +
sizeof(BitmapHashKey) + sizeof(BitmapHashValue));
info->image = val;
outline_free(outline);
free(outline);
outline_free(border);
free(border);
}
/**
* This function goes through text_info and calculates text parameters.
* The following text_info fields are filled:
* height
* lines[].height
* lines[].asc
* lines[].desc
*/
static void measure_text(ASS_Renderer *render_priv)
{
TextInfo *text_info = &render_priv->text_info;
int cur_line = 0;
double max_asc = 0., max_desc = 0.;
GlyphInfo *last = NULL;
int i;
int empty_line = 1;
text_info->height = 0.;
for (i = 0; i < text_info->length + 1; ++i) {
if ((i == text_info->length) || text_info->glyphs[i].linebreak) {
if (empty_line && cur_line > 0 && last) {
max_asc = d6_to_double(last->asc) / 2.0;
max_desc = d6_to_double(last->desc) / 2.0;
}
text_info->lines[cur_line].asc = max_asc;
text_info->lines[cur_line].desc = max_desc;
text_info->height += max_asc + max_desc;
cur_line++;
max_asc = max_desc = 0.;
empty_line = 1;
}
if (i < text_info->length) {
GlyphInfo *cur = text_info->glyphs + i;
if (d6_to_double(cur->asc) > max_asc)
max_asc = d6_to_double(cur->asc);
if (d6_to_double(cur->desc) > max_desc)
max_desc = d6_to_double(cur->desc);
if (cur->symbol != '\n' && cur->symbol != 0) {
empty_line = 0;
last = cur;
}
}
}
text_info->height +=
(text_info->n_lines -
1) * render_priv->settings.line_spacing;
}
/**
* Mark extra whitespace for later removal.
*/
#define IS_WHITESPACE(x) ((x->symbol == ' ' || x->symbol == '\n') \
&& !x->linebreak)
static void trim_whitespace(ASS_Renderer *render_priv)
{
int i, j;
GlyphInfo *cur;
TextInfo *ti = &render_priv->text_info;
// Mark trailing spaces
i = ti->length - 1;
cur = ti->glyphs + i;
while (i && IS_WHITESPACE(cur)) {
cur->skip++;
cur = ti->glyphs + --i;
}
// Mark leading whitespace
i = 0;
cur = ti->glyphs;
while (i < ti->length && IS_WHITESPACE(cur)) {
cur->skip++;
cur = ti->glyphs + ++i;
}
// Mark all extraneous whitespace inbetween
for (i = 0; i < ti->length; ++i) {
cur = ti->glyphs + i;
if (cur->linebreak) {
// Mark whitespace before
j = i - 1;
cur = ti->glyphs + j;
while (j && IS_WHITESPACE(cur)) {
cur->skip++;
cur = ti->glyphs + --j;
}
// A break itself can contain a whitespace, too
cur = ti->glyphs + i;
if (cur->symbol == ' ' || cur->symbol == '\n') {
cur->skip++;
// Mark whitespace after
j = i + 1;
cur = ti->glyphs + j;
while (j < ti->length && IS_WHITESPACE(cur)) {
cur->skip++;
cur = ti->glyphs + ++j;
}
i = j - 1;
}
}
}
}
#undef IS_WHITESPACE
/**
* \brief rearrange text between lines
* \param max_text_width maximal text line width in pixels
* The algo is similar to the one in libvo/sub.c:
* 1. Place text, wrapping it when current line is full
* 2. Try moving words from the end of a line to the beginning of the next one while it reduces
* the difference in lengths between this two lines.
* The result may not be optimal, but usually is good enough.
*
* FIXME: implement style 0 and 3 correctly
*/
static void
wrap_lines_smart(ASS_Renderer *render_priv, double max_text_width)
{
int i;
GlyphInfo *cur, *s1, *e1, *s2, *s3;
int last_space;
int break_type;
int exit;
double pen_shift_x;
double pen_shift_y;
int cur_line;
int run_offset;
TextInfo *text_info = &render_priv->text_info;
last_space = -1;
text_info->n_lines = 1;
break_type = 0;
s1 = text_info->glyphs; // current line start
for (i = 0; i < text_info->length; ++i) {
int break_at = -1;
double s_offset, len;
cur = text_info->glyphs + i;
s_offset = d6_to_double(s1->bbox.xMin + s1->pos.x);
len = d6_to_double(cur->bbox.xMax + cur->pos.x) - s_offset;
if (cur->symbol == '\n') {
break_type = 2;
break_at = i;
ass_msg(render_priv->library, MSGL_DBG2,
"forced line break at %d", break_at);
} else if (cur->symbol == ' ') {
last_space = i;
} else if (len >= max_text_width
&& (render_priv->state.wrap_style != 2)) {
break_type = 1;
break_at = last_space;
if (break_at >= 0)
ass_msg(render_priv->library, MSGL_DBG2, "line break at %d",
break_at);
}
if (break_at != -1) {
// need to use one more line
// marking break_at+1 as start of a new line
int lead = break_at + 1; // the first symbol of the new line
if (text_info->n_lines >= text_info->max_lines) {
// Raise maximum number of lines
text_info->max_lines *= 2;
text_info->lines = realloc(text_info->lines,
sizeof(LineInfo) *
text_info->max_lines);
}
if (lead < text_info->length) {
text_info->glyphs[lead].linebreak = break_type;
last_space = -1;
s1 = text_info->glyphs + lead;
text_info->n_lines++;
}
}
}
#define DIFF(x,y) (((x) < (y)) ? (y - x) : (x - y))
exit = 0;
while (!exit && render_priv->state.wrap_style != 1) {
exit = 1;
s3 = text_info->glyphs;
s1 = s2 = 0;
for (i = 0; i <= text_info->length; ++i) {
cur = text_info->glyphs + i;
if ((i == text_info->length) || cur->linebreak) {
s1 = s2;
s2 = s3;
s3 = cur;
if (s1 && (s2->linebreak == 1)) { // have at least 2 lines, and linebreak is 'soft'
double l1, l2, l1_new, l2_new;
GlyphInfo *w = s2;
do {
--w;
} while ((w > s1) && (w->symbol == ' '));
while ((w > s1) && (w->symbol != ' ')) {
--w;
}
e1 = w;
while ((e1 > s1) && (e1->symbol == ' ')) {
--e1;
}
if (w->symbol == ' ')
++w;
l1 = d6_to_double(((s2 - 1)->bbox.xMax + (s2 - 1)->pos.x) -
(s1->bbox.xMin + s1->pos.x));
l2 = d6_to_double(((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -
(s2->bbox.xMin + s2->pos.x));
l1_new = d6_to_double(
(e1->bbox.xMax + e1->pos.x) -
(s1->bbox.xMin + s1->pos.x));
l2_new = d6_to_double(
((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -
(w->bbox.xMin + w->pos.x));
if (DIFF(l1_new, l2_new) < DIFF(l1, l2)) {
w->linebreak = 1;
s2->linebreak = 0;
exit = 0;
}
}
}
if (i == text_info->length)
break;
}
}
assert(text_info->n_lines >= 1);
#undef DIFF
measure_text(render_priv);
trim_whitespace(render_priv);
cur_line = 1;
run_offset = 0;
i = 0;
cur = text_info->glyphs + i;
while (i < text_info->length && cur->skip)
cur = text_info->glyphs + ++i;
pen_shift_x = d6_to_double(-cur->pos.x);
pen_shift_y = 0.;
for (i = 0; i < text_info->length; ++i) {
cur = text_info->glyphs + i;
if (cur->linebreak) {
while (i < text_info->length && cur->skip && cur->symbol != '\n')
cur = text_info->glyphs + ++i;
double height =
text_info->lines[cur_line - 1].desc +
text_info->lines[cur_line].asc;
text_info->lines[cur_line - 1].len = i -
text_info->lines[cur_line - 1].offset;
text_info->lines[cur_line].offset = i;
cur_line++;
run_offset++;
pen_shift_x = d6_to_double(-cur->pos.x);
pen_shift_y += height + render_priv->settings.line_spacing;
}
cur->pos.x += double_to_d6(pen_shift_x);
cur->pos.y += double_to_d6(pen_shift_y);
}
text_info->lines[cur_line - 1].len =
text_info->length - text_info->lines[cur_line - 1].offset;
#if 0
// print line info
for (i = 0; i < text_info->n_lines; i++) {
printf("line %d offset %d length %d\n", i, text_info->lines[i].offset,
text_info->lines[i].len);
}
#endif
}
/**
* \brief Calculate base point for positioning and rotation
* \param bbox text bbox
* \param alignment alignment
* \param bx, by out: base point coordinates
*/
static void get_base_point(DBBox *bbox, int alignment, double *bx, double *by)
{
const int halign = alignment & 3;
const int valign = alignment & 12;
if (bx)
switch (halign) {
case HALIGN_LEFT:
*bx = bbox->xMin;
break;
case HALIGN_CENTER:
*bx = (bbox->xMax + bbox->xMin) / 2.0;
break;
case HALIGN_RIGHT:
*bx = bbox->xMax;
break;
}
if (by)
switch (valign) {
case VALIGN_TOP:
*by = bbox->yMin;
break;
case VALIGN_CENTER:
*by = (bbox->yMax + bbox->yMin) / 2.0;
break;
case VALIGN_SUB:
*by = bbox->yMax;
break;
}
}
/**
* Prepare bitmap hash key of a glyph
*/
static void
fill_bitmap_hash(ASS_Renderer *priv, GlyphInfo *info,
OutlineBitmapHashKey *hash_key)
{
hash_key->frx = rot_key(info->frx);
hash_key->fry = rot_key(info->fry);
hash_key->frz = rot_key(info->frz);
hash_key->fax = double_to_d16(info->fax);
hash_key->fay = double_to_d16(info->fay);
}
/**
* \brief Adjust the glyph's font size and scale factors to ensure smooth
* scaling and handle pathological font sizes. The main problem here is
* freetype's grid fitting, which destroys animations by font size, or will
* result in incorrect final text size if font sizes are very small and
* scale factors very large. See Google Code issue #46.
* \param priv guess what
* \param glyph the glyph to be modified
*/
static void
fix_glyph_scaling(ASS_Renderer *priv, GlyphInfo *glyph)
{
double ft_size;
if (priv->settings.hinting == ASS_HINTING_NONE) {
// arbitrary, not too small to prevent grid fitting rounding effects
// XXX: this is a rather crude hack
ft_size = 256.0;
} else {
// If hinting is enabled, we want to pass the real font size
// to freetype. Normalize scale_y to 1.0.
ft_size = glyph->scale_y * glyph->font_size;
}
glyph->scale_x = glyph->scale_x * glyph->font_size / ft_size;
glyph->scale_y = glyph->scale_y * glyph->font_size / ft_size;
glyph->font_size = ft_size;
}
/**
* \brief Checks whether a glyph should start a new bitmap run
* \param info Pointer to new GlyphInfo to check
* \param current_info Pointer to CombinedBitmapInfo for current run (may be NULL)
* \return 1 if a new run should be started
*/
static int is_new_bm_run(GlyphInfo *info, GlyphInfo *last)
{
// FIXME: Don't break on glyph substitutions
return !last || info->effect || info->drawing || last->drawing ||
strcmp(last->font->desc.family, info->font->desc.family) ||
last->font->desc.vertical != info->font->desc.vertical ||
last->face_index != info->face_index ||
last->font_size != info->font_size ||
last->c[0] != info->c[0] ||
last->c[1] != info->c[1] ||
last->c[2] != info->c[2] ||
last->c[3] != info->c[3] ||
last->be != info->be ||
last->blur != info->blur ||
last->shadow_x != info->shadow_x ||
last->shadow_y != info->shadow_y ||
last->frx != info->frx ||
last->fry != info->fry ||
last->frz != info->frz ||
last->fax != info->fax ||
last->fay != info->fay ||
last->scale_x != info->scale_x ||
last->scale_y != info->scale_y ||
last->border_style != info->border_style ||
last->border_x != info->border_x ||
last->border_y != info->border_y ||
last->hspacing != info->hspacing ||
last->italic != info->italic ||
last->bold != info->bold ||
last->flags != info->flags;
}
static void make_shadow_bitmap(CombinedBitmapInfo *info, ASS_Renderer *render_priv)
{
if (!(info->filter.flags & FILTER_NONZERO_SHADOW)) {
if (info->bm && info->bm_o && !(info->filter.flags & FILTER_BORDER_STYLE_3)) {
fix_outline(info->bm, info->bm_o);
} else if (info->bm_o && !(info->filter.flags & FILTER_NONZERO_BORDER)) {
ass_free_bitmap(info->bm_o);
info->bm_o = 0;
}
return;
}
// Create shadow and fix outline as needed
if (info->bm && info->bm_o && !(info->filter.flags & FILTER_BORDER_STYLE_3)) {
info->bm_s = copy_bitmap(render_priv->engine, info->bm_o);
fix_outline(info->bm, info->bm_o);
} else if (info->bm_o && (info->filter.flags & FILTER_NONZERO_BORDER)) {
info->bm_s = copy_bitmap(render_priv->engine, info->bm_o);
} else if (info->bm_o) {
info->bm_s = info->bm_o;
info->bm_o = 0;
} else if (info->bm)
info->bm_s = copy_bitmap(render_priv->engine, info->bm);
if (!info->bm_s)
return;
// Works right even for negative offsets
// '>>' rounds toward negative infinity, '&' returns correct remainder
info->bm_s->left += info->filter.shadow.x >> 6;
info->bm_s->top += info->filter.shadow.y >> 6;
shift_bitmap(info->bm_s, info->filter.shadow.x & SUBPIXEL_MASK, info->filter.shadow.y & SUBPIXEL_MASK);
}
// Parse event text.
// Fill render_priv->text_info.
static int parse_events(ASS_Renderer *render_priv, ASS_Event *event)
{
TextInfo *text_info = &render_priv->text_info;
ASS_Drawing *drawing = NULL;
unsigned code;
char *p, *q;
int i;
p = event->Text;
// Event parsing.
while (1) {
// get next char, executing style override
// this affects render_context
code = 0;
while (*p) {
if ((*p == '{') && (q = strchr(p, '}'))) {
while (p < q)
p = parse_tag(render_priv, p, q, 1.);
assert(*p == '}');
p++;
} else if (render_priv->state.drawing_scale) {
q = p;
if (*p == '{')
q++;
while ((*q != '{') && (*q != 0))
q++;
if (!drawing) {
drawing = ass_drawing_new(render_priv->library,
render_priv->ftlibrary);
if (!drawing)
return 1;
}
ass_drawing_set_text(drawing, p, q - p);
code = 0xfffc; // object replacement character
p = q;
break;
} else {
code = get_next_char(render_priv, &p);
break;
}
}
if (code == 0)
break;
// face could have been changed in get_next_char
if (!render_priv->state.font) {
free_render_context(render_priv);
ass_drawing_free(drawing);
return 1;
}
if (text_info->length >= text_info->max_glyphs) {
// Raise maximum number of glyphs
text_info->max_glyphs *= 2;
text_info->glyphs =
realloc(text_info->glyphs,
sizeof(GlyphInfo) * text_info->max_glyphs);
}
GlyphInfo *info = &text_info->glyphs[text_info->length];
// Clear current GlyphInfo
memset(info, 0, sizeof(GlyphInfo));
// Parse drawing
if (drawing && drawing->text) {
drawing->scale_x = render_priv->state.scale_x *
render_priv->font_scale;
drawing->scale_y = render_priv->state.scale_y *
render_priv->font_scale;
drawing->scale = render_priv->state.drawing_scale;
drawing->pbo = render_priv->state.pbo;
info->drawing = drawing;
drawing = NULL;
}
// Fill glyph information
info->symbol = code;
info->font = render_priv->state.font;
if (!info->drawing)
ass_cache_inc_ref(info->font);
for (i = 0; i < 4; ++i) {
uint32_t clr = render_priv->state.c[i];
// VSFilter compatibility: apply fade only when it's positive
if (render_priv->state.fade > 0)
change_alpha(&clr,
mult_alpha(_a(clr), render_priv->state.fade), 1.);
info->c[i] = clr;
}
info->effect_type = render_priv->state.effect_type;
info->effect_timing = render_priv->state.effect_timing;
info->effect_skip_timing = render_priv->state.effect_skip_timing;
info->font_size =
render_priv->state.font_size * render_priv->font_scale;
info->be = render_priv->state.be;
info->blur = render_priv->state.blur;
info->shadow_x = render_priv->state.shadow_x;
info->shadow_y = render_priv->state.shadow_y;
info->scale_x = info->orig_scale_x = render_priv->state.scale_x;
info->scale_y = info->orig_scale_y = render_priv->state.scale_y;
info->border_style = render_priv->state.border_style;
info->border_x= render_priv->state.border_x;
info->border_y = render_priv->state.border_y;
info->hspacing = render_priv->state.hspacing;
info->bold = render_priv->state.bold;
info->italic = render_priv->state.italic;
info->flags = render_priv->state.flags;
info->frx = render_priv->state.frx;
info->fry = render_priv->state.fry;
info->frz = render_priv->state.frz;
info->fax = render_priv->state.fax;
info->fay = render_priv->state.fay;
if (!info->drawing)
fix_glyph_scaling(render_priv, info);
text_info->length++;
render_priv->state.effect_type = EF_NONE;
render_priv->state.effect_timing = 0;
render_priv->state.effect_skip_timing = 0;
}
ass_drawing_free(drawing);
return 0;
}
// Process render_priv->text_info and load glyph outlines.
static void retrieve_glyphs(ASS_Renderer *render_priv)
{
GlyphInfo *glyphs = render_priv->text_info.glyphs;
int i;
for (i = 0; i < render_priv->text_info.length; i++) {
GlyphInfo *info = glyphs + i;
while (info) {
get_outline_glyph(render_priv, info);
info = info->next;
}
info = glyphs + i;
// Add additional space after italic to non-italic style changes
if (i && glyphs[i - 1].italic && !info->italic) {
int back = i - 1;
GlyphInfo *og = &glyphs[back];
while (back && og->bbox.xMax - og->bbox.xMin == 0
&& og->italic)
og = &glyphs[--back];
if (og->bbox.xMax > og->cluster_advance.x)
og->cluster_advance.x = og->bbox.xMax;
}
// add horizontal letter spacing
info->cluster_advance.x += double_to_d6(info->hspacing *
render_priv->font_scale * info->orig_scale_x);
// add displacement for vertical shearing
info->cluster_advance.y += (info->fay / info->scale_x * info->scale_y) * info->cluster_advance.x;
}
}
// Preliminary layout (for line wrapping)
static void preliminary_layout(ASS_Renderer *render_priv)
{
FT_Vector pen;
int i;
pen.x = 0;
pen.y = 0;
for (i = 0; i < render_priv->text_info.length; i++) {
GlyphInfo *info = render_priv->text_info.glyphs + i;
FT_Vector cluster_pen = pen;
while (info) {
info->pos.x = cluster_pen.x;
info->pos.y = cluster_pen.y;
cluster_pen.x += info->advance.x;
cluster_pen.y += info->advance.y;
// fill bitmap hash
info->hash_key.type = BITMAP_OUTLINE;
fill_bitmap_hash(render_priv, info, &info->hash_key.u.outline);
info = info->next;
}
info = render_priv->text_info.glyphs + i;
pen.x += info->cluster_advance.x;
pen.y += info->cluster_advance.y;
}
}
// Reorder text into visual order
static void reorder_text(ASS_Renderer *render_priv)
{
TextInfo *text_info = &render_priv->text_info;
FT_Vector pen;
int i;
FriBidiStrIndex *cmap = ass_shaper_reorder(render_priv->shaper, text_info);
if (!cmap) {
ass_msg(render_priv->library, MSGL_ERR, "Failed to reorder text");
ass_shaper_cleanup(render_priv->shaper, text_info);
free_render_context(render_priv);
return;
}
// Reposition according to the map
pen.x = 0;
pen.y = 0;
int lineno = 1;
double last_pen_x = 0;
double last_fay = 0;
for (i = 0; i < text_info->length; i++) {
GlyphInfo *info = text_info->glyphs + cmap[i];
if (text_info->glyphs[i].linebreak) {
pen.y -= (last_fay / info->scale_x * info->scale_y) * (pen.x - last_pen_x);
last_pen_x = pen.x = 0;
pen.y += double_to_d6(text_info->lines[lineno-1].desc);
pen.y += double_to_d6(text_info->lines[lineno].asc);
pen.y += double_to_d6(render_priv->settings.line_spacing);
lineno++;
}
else if (last_fay != info->fay) {
pen.y -= (last_fay / info->scale_x * info->scale_y) * (pen.x - last_pen_x);
last_pen_x = pen.x;
}
last_fay = info->fay;
if (info->skip) continue;
FT_Vector cluster_pen = pen;
while (info) {
info->pos.x = info->offset.x + cluster_pen.x;
info->pos.y = info->offset.y + cluster_pen.y;
cluster_pen.x += info->advance.x;
cluster_pen.y += info->advance.y;
info = info->next;
}
info = text_info->glyphs + cmap[i];
pen.x += info->cluster_advance.x;
pen.y += info->cluster_advance.y;
}
}
static void align_lines(ASS_Renderer *render_priv, double max_text_width)
{
TextInfo *text_info = &render_priv->text_info;
GlyphInfo *glyphs = text_info->glyphs;
int i, j;
double width = 0;
int last_break = -1;
int halign = render_priv->state.alignment & 3;
if (render_priv->state.evt_type == EVENT_HSCROLL)
return;
for (i = 0; i <= text_info->length; ++i) { // (text_info->length + 1) is the end of the last line
if ((i == text_info->length) || glyphs[i].linebreak) {
double shift = 0;
if (halign == HALIGN_LEFT) { // left aligned, no action
shift = 0;
} else if (halign == HALIGN_RIGHT) { // right aligned
shift = max_text_width - width;
} else if (halign == HALIGN_CENTER) { // centered
shift = (max_text_width - width) / 2.0;
}
for (j = last_break + 1; j < i; ++j) {
GlyphInfo *info = glyphs + j;
while (info) {
info->pos.x += double_to_d6(shift);
info = info->next;
}
}
last_break = i - 1;
width = 0;
}
if (i < text_info->length && !glyphs[i].skip &&
glyphs[i].symbol != '\n' && glyphs[i].symbol != 0) {
width += d6_to_double(glyphs[i].cluster_advance.x);
}
}
}
static void calculate_rotation_params(ASS_Renderer *render_priv, DBBox *bbox,
double device_x, double device_y)
{
TextInfo *text_info = &render_priv->text_info;
DVector center;
int i;
if (render_priv->state.have_origin) {
center.x = x2scr(render_priv, render_priv->state.org_x);
center.y = y2scr(render_priv, render_priv->state.org_y);
} else {
double bx = 0., by = 0.;
get_base_point(bbox, render_priv->state.alignment, &bx, &by);
center.x = device_x + bx;
center.y = device_y + by;
}
for (i = 0; i < text_info->length; ++i) {
GlyphInfo *info = text_info->glyphs + i;
while (info) {
OutlineBitmapHashKey *key = &info->hash_key.u.outline;
if (key->frx || key->fry || key->frz || key->fax || key->fay) {
key->shift_x = info->pos.x + double_to_d6(device_x - center.x);
key->shift_y = -(info->pos.y + double_to_d6(device_y - center.y));
} else {
key->shift_x = 0;
key->shift_y = 0;
}
info = info->next;
}
}
}
static inline void rectangle_reset(Rectangle *rect)
{
rect->x_min = rect->y_min = INT_MAX;
rect->x_max = rect->y_max = INT_MIN;
}
static inline void rectangle_combine(Rectangle *rect, const Bitmap *bm, int x, int y)
{
rect->x_min = FFMIN(rect->x_min, x + bm->left);
rect->y_min = FFMIN(rect->y_min, y + bm->top);
rect->x_max = FFMAX(rect->x_max, x + bm->left + bm->w);
rect->y_max = FFMAX(rect->y_max, y + bm->top + bm->h);
}
// Convert glyphs to bitmaps, combine them, apply blur, generate shadows.
static void render_and_combine_glyphs(ASS_Renderer *render_priv,
double device_x, double device_y)
{
TextInfo *text_info = &render_priv->text_info;
int left = render_priv->settings.left_margin;
device_x = (device_x - left) * render_priv->font_scale_x + left;
unsigned nb_bitmaps = 0;
char linebreak = 0;
CombinedBitmapInfo *combined_info = text_info->combined_bitmaps;
CombinedBitmapInfo *current_info = NULL;
GlyphInfo *last_info = NULL;
for (int i = 0; i < text_info->length; i++) {
GlyphInfo *info = text_info->glyphs + i;
if (info->linebreak) linebreak = 1;
if (info->skip) {
for (; info; info = info->next)
ass_cache_dec_ref(info->hash_key.u.outline.outline);
continue;
}
for (; info; info = info->next) {
OutlineBitmapHashKey *key = &info->hash_key.u.outline;
info->pos.x = double_to_d6(device_x + d6_to_double(info->pos.x) * render_priv->font_scale_x);
info->pos.y = double_to_d6(device_y) + info->pos.y;
key->advance.x = info->pos.x & (SUBPIXEL_MASK & ~SUBPIXEL_ACCURACY);
key->advance.y = info->pos.y & (SUBPIXEL_MASK & ~SUBPIXEL_ACCURACY);
int x = info->pos.x >> 6, y = info->pos.y >> 6;
get_bitmap_glyph(render_priv, info);
if(linebreak || is_new_bm_run(info, last_info)) {
linebreak = 0;
last_info = NULL;
if (nb_bitmaps >= text_info->max_bitmaps) {
size_t new_size = 2 * text_info->max_bitmaps;
if (!ASS_REALLOC_ARRAY(text_info->combined_bitmaps, new_size)) {
ass_cache_dec_ref(info->image);
continue;
}
text_info->max_bitmaps = new_size;
combined_info = text_info->combined_bitmaps;
}
current_info = &combined_info[nb_bitmaps];
memcpy(¤t_info->c, &info->c, sizeof(info->c));
current_info->effect_type = info->effect_type;
current_info->effect_timing = info->effect_timing;
current_info->first_pos_x = info->bbox.xMax >> 6;
current_info->filter.flags = 0;
if (info->border_style == 3)
current_info->filter.flags |= FILTER_BORDER_STYLE_3;
if (info->border_x || info->border_y)
current_info->filter.flags |= FILTER_NONZERO_BORDER;
if (info->shadow_x || info->shadow_y)
current_info->filter.flags |= FILTER_NONZERO_SHADOW;
// VSFilter compatibility: invisible fill and no border?
// In this case no shadow is supposed to be rendered.
if (info->border || (info->c[0] & 0xFF) != 0xFF)
current_info->filter.flags |= FILTER_DRAW_SHADOW;
current_info->filter.be = info->be;
current_info->filter.blur = 2 * info->blur * render_priv->blur_scale;
current_info->filter.shadow.x = double_to_d6(info->shadow_x * render_priv->border_scale);
current_info->filter.shadow.y = double_to_d6(info->shadow_y * render_priv->border_scale);
current_info->x = current_info->y = INT_MAX;
rectangle_reset(¤t_info->rect);
rectangle_reset(¤t_info->rect_o);
current_info->n_bm = current_info->n_bm_o = 0;
current_info->bm = current_info->bm_o = current_info->bm_s = NULL;
current_info->image = NULL;
current_info->bitmap_count = current_info->max_bitmap_count = 0;
current_info->bitmaps = malloc(MAX_SUB_BITMAPS_INITIAL * sizeof(BitmapRef));
if (!current_info->bitmaps) {
ass_cache_dec_ref(info->image);
continue;
}
current_info->max_bitmap_count = MAX_SUB_BITMAPS_INITIAL;
nb_bitmaps++;
}
last_info = info;
if (!info->image || !current_info) {
ass_cache_dec_ref(info->image);
continue;
}
if (current_info->bitmap_count >= current_info->max_bitmap_count) {
size_t new_size = 2 * current_info->max_bitmap_count;
if (!ASS_REALLOC_ARRAY(current_info->bitmaps, new_size)) {
ass_cache_dec_ref(info->image);
continue;
}
current_info->max_bitmap_count = new_size;
}
current_info->bitmaps[current_info->bitmap_count].image = info->image;
current_info->bitmaps[current_info->bitmap_count].x = x;
current_info->bitmaps[current_info->bitmap_count].y = y;
current_info->bitmap_count++;
current_info->x = FFMIN(current_info->x, x);
current_info->y = FFMIN(current_info->y, y);
if (info->image->bm) {
rectangle_combine(¤t_info->rect, info->image->bm, x, y);
current_info->n_bm++;
}
if (info->image->bm_o) {
rectangle_combine(¤t_info->rect_o, info->image->bm_o, x, y);
current_info->n_bm_o++;
}
}
}
for (int i = 0; i < nb_bitmaps; i++) {
CombinedBitmapInfo *info = &combined_info[i];
for (int j = 0; j < info->bitmap_count; j++) {
info->bitmaps[j].x -= info->x;
info->bitmaps[j].y -= info->y;
}
CompositeHashKey hk;
CompositeHashValue *hv;
fill_composite_hash(&hk, info);
if (ass_cache_get(render_priv->cache.composite_cache, &hk, &hv)) {
info->bm = hv->bm;
info->bm_o = hv->bm_o;
info->bm_s = hv->bm_s;
info->image = hv;
continue;
}
if (!hv)
continue;
int bord = be_padding(info->filter.be);
if (!bord && info->n_bm == 1) {
for (int j = 0; j < info->bitmap_count; j++) {
if (!info->bitmaps[j].image->bm)
continue;
info->bm = copy_bitmap(render_priv->engine, info->bitmaps[j].image->bm);
if (info->bm) {
info->bm->left += info->bitmaps[j].x;
info->bm->top += info->bitmaps[j].y;
}
break;
}
} else if (info->n_bm) {
info->bm = alloc_bitmap(render_priv->engine,
info->rect.x_max - info->rect.x_min + 2 * bord,
info->rect.y_max - info->rect.y_min + 2 * bord, true);
Bitmap *dst = info->bm;
if (dst) {
dst->left = info->rect.x_min - info->x - bord;
dst->top = info->rect.y_min - info->y - bord;
for (int j = 0; j < info->bitmap_count; j++) {
Bitmap *src = info->bitmaps[j].image->bm;
if (!src)
continue;
int x = info->bitmaps[j].x + src->left - dst->left;
int y = info->bitmaps[j].y + src->top - dst->top;
assert(x >= 0 && x + src->w <= dst->w);
assert(y >= 0 && y + src->h <= dst->h);
unsigned char *buf = dst->buffer + y * dst->stride + x;
render_priv->engine->add_bitmaps(buf, dst->stride,
src->buffer, src->stride,
src->h, src->w);
}
}
}
if (!bord && info->n_bm_o == 1) {
for (int j = 0; j < info->bitmap_count; j++) {
if (!info->bitmaps[j].image->bm_o)
continue;
info->bm_o = copy_bitmap(render_priv->engine, info->bitmaps[j].image->bm_o);
if (info->bm_o) {
info->bm_o->left += info->bitmaps[j].x;
info->bm_o->top += info->bitmaps[j].y;
}
break;
}
} else if (info->n_bm_o) {
info->bm_o = alloc_bitmap(render_priv->engine,
info->rect_o.x_max - info->rect_o.x_min + 2 * bord,
info->rect_o.y_max - info->rect_o.y_min + 2 * bord,
true);
Bitmap *dst = info->bm_o;
if (dst) {
dst->left = info->rect_o.x_min - info->x - bord;
dst->top = info->rect_o.y_min - info->y - bord;
for (int j = 0; j < info->bitmap_count; j++) {
Bitmap *src = info->bitmaps[j].image->bm_o;
if (!src)
continue;
int x = info->bitmaps[j].x + src->left - dst->left;
int y = info->bitmaps[j].y + src->top - dst->top;
assert(x >= 0 && x + src->w <= dst->w);
assert(y >= 0 && y + src->h <= dst->h);
unsigned char *buf = dst->buffer + y * dst->stride + x;
render_priv->engine->add_bitmaps(buf, dst->stride,
src->buffer, src->stride,
src->h, src->w);
}
}
}
if (info->bm || info->bm_o) {
ass_synth_blur(render_priv->engine, info->filter.flags & FILTER_BORDER_STYLE_3,
info->filter.be, info->filter.blur, info->bm, info->bm_o);
if (info->filter.flags & FILTER_DRAW_SHADOW)
make_shadow_bitmap(info, render_priv);
}
hv->bm = info->bm;
hv->bm_o = info->bm_o;
hv->bm_s = info->bm_s;
ass_cache_commit(hv, bitmap_size(hv->bm) +
bitmap_size(hv->bm_o) + bitmap_size(hv->bm_s) +
sizeof(CompositeHashKey) + sizeof(CompositeHashValue));
info->image = hv;
}
text_info->n_bitmaps = nb_bitmaps;
}
static void add_background(ASS_Renderer *render_priv, EventImages *event_images)
{
void *nbuffer = ass_aligned_alloc(1, event_images->width * event_images->height, false);
if (!nbuffer)
return;
memset(nbuffer, 0xFF, event_images->width * event_images->height);
ASS_Image *img = my_draw_bitmap(nbuffer, event_images->width,
event_images->height,
event_images->width,
event_images->left,
event_images->top,
render_priv->state.c[3], NULL);
if (img) {
img->next = event_images->imgs;
event_images->imgs = img;
}
}
/**
* \brief Main ass rendering function, glues everything together
* \param event event to render
* \param event_images struct containing resulting images, will also be initialized
* Process event, appending resulting ASS_Image's to images_root.
*/
static int
ass_render_event(ASS_Renderer *render_priv, ASS_Event *event,
EventImages *event_images)
{
DBBox bbox;
int MarginL, MarginR, MarginV;
int valign;
double device_x = 0;
double device_y = 0;
TextInfo *text_info = &render_priv->text_info;
if (event->Style >= render_priv->track->n_styles) {
ass_msg(render_priv->library, MSGL_WARN, "No style found");
return 1;
}
if (!event->Text) {
ass_msg(render_priv->library, MSGL_WARN, "Empty event");
return 1;
}
free_render_context(render_priv);
init_render_context(render_priv, event);
if (parse_events(render_priv, event))
return 1;
if (text_info->length == 0) {
// no valid symbols in the event; this can be smth like {comment}
free_render_context(render_priv);
return 1;
}
// Find shape runs and shape text
ass_shaper_set_base_direction(render_priv->shaper,
resolve_base_direction(render_priv->state.font_encoding));
ass_shaper_find_runs(render_priv->shaper, render_priv, text_info->glyphs,
text_info->length);
if (ass_shaper_shape(render_priv->shaper, text_info) < 0) {
ass_msg(render_priv->library, MSGL_ERR, "Failed to shape text");
free_render_context(render_priv);
return 1;
}
retrieve_glyphs(render_priv);
preliminary_layout(render_priv);
// depends on glyph x coordinates being monotonous, so it should be done before line wrap
process_karaoke_effects(render_priv);
valign = render_priv->state.alignment & 12;
MarginL =
(event->MarginL) ? event->MarginL : render_priv->state.style->MarginL;
MarginR =
(event->MarginR) ? event->MarginR : render_priv->state.style->MarginR;
MarginV =
(event->MarginV) ? event->MarginV : render_priv->state.style->MarginV;
// calculate max length of a line
double max_text_width =
x2scr(render_priv, render_priv->track->PlayResX - MarginR) -
x2scr(render_priv, MarginL);
// wrap lines
if (render_priv->state.evt_type != EVENT_HSCROLL) {
// rearrange text in several lines
wrap_lines_smart(render_priv, max_text_width);
} else {
// no breaking or wrapping, everything in a single line
text_info->lines[0].offset = 0;
text_info->lines[0].len = text_info->length;
text_info->n_lines = 1;
measure_text(render_priv);
}
reorder_text(render_priv);
align_lines(render_priv, max_text_width);
// determing text bounding box
compute_string_bbox(text_info, &bbox);
// determine device coordinates for text
// x coordinate for everything except positioned events
if (render_priv->state.evt_type == EVENT_NORMAL ||
render_priv->state.evt_type == EVENT_VSCROLL) {
device_x = x2scr(render_priv, MarginL);
} else if (render_priv->state.evt_type == EVENT_HSCROLL) {
if (render_priv->state.scroll_direction == SCROLL_RL)
device_x =
x2scr(render_priv,
render_priv->track->PlayResX -
render_priv->state.scroll_shift);
else if (render_priv->state.scroll_direction == SCROLL_LR)
device_x =
x2scr(render_priv,
render_priv->state.scroll_shift) - (bbox.xMax -
bbox.xMin);
}
// y coordinate for everything except positioned events
if (render_priv->state.evt_type == EVENT_NORMAL ||
render_priv->state.evt_type == EVENT_HSCROLL) {
if (valign == VALIGN_TOP) { // toptitle
device_y =
y2scr_top(render_priv,
MarginV) + text_info->lines[0].asc;
} else if (valign == VALIGN_CENTER) { // midtitle
double scr_y =
y2scr(render_priv, render_priv->track->PlayResY / 2.0);
device_y = scr_y - (bbox.yMax + bbox.yMin) / 2.0;
} else { // subtitle
double line_pos = render_priv->state.explicit ?
0 : render_priv->settings.line_position;
double scr_top, scr_bottom, scr_y0;
if (valign != VALIGN_SUB)
ass_msg(render_priv->library, MSGL_V,
"Invalid valign, assuming 0 (subtitle)");
scr_bottom =
y2scr_sub(render_priv,
render_priv->track->PlayResY - MarginV);
scr_top = y2scr_top(render_priv, 0); //xxx not always 0?
device_y = scr_bottom + (scr_top - scr_bottom) * line_pos / 100.0;
device_y -= text_info->height;
device_y += text_info->lines[0].asc;
// clip to top to avoid confusion if line_position is very high,
// turning the subtitle into a toptitle
// also, don't change behavior if line_position is not used
scr_y0 = scr_top + text_info->lines[0].asc;
if (device_y < scr_y0 && line_pos > 0) {
device_y = scr_y0;
}
}
} else if (render_priv->state.evt_type == EVENT_VSCROLL) {
if (render_priv->state.scroll_direction == SCROLL_TB)
device_y =
y2scr(render_priv,
render_priv->state.clip_y0 +
render_priv->state.scroll_shift) - (bbox.yMax -
bbox.yMin);
else if (render_priv->state.scroll_direction == SCROLL_BT)
device_y =
y2scr(render_priv,
render_priv->state.clip_y1 -
render_priv->state.scroll_shift);
}
// positioned events are totally different
if (render_priv->state.evt_type == EVENT_POSITIONED) {
double base_x = 0;
double base_y = 0;
get_base_point(&bbox, render_priv->state.alignment, &base_x, &base_y);
device_x =
x2scr_pos(render_priv, render_priv->state.pos_x) - base_x;
device_y =
y2scr_pos(render_priv, render_priv->state.pos_y) - base_y;
}
// fix clip coordinates (they depend on alignment)
if (render_priv->state.evt_type == EVENT_NORMAL ||
render_priv->state.evt_type == EVENT_HSCROLL ||
render_priv->state.evt_type == EVENT_VSCROLL) {
render_priv->state.clip_x0 =
x2scr_scaled(render_priv, render_priv->state.clip_x0);
render_priv->state.clip_x1 =
x2scr_scaled(render_priv, render_priv->state.clip_x1);
if (valign == VALIGN_TOP) {
render_priv->state.clip_y0 =
y2scr_top(render_priv, render_priv->state.clip_y0);
render_priv->state.clip_y1 =
y2scr_top(render_priv, render_priv->state.clip_y1);
} else if (valign == VALIGN_CENTER) {
render_priv->state.clip_y0 =
y2scr(render_priv, render_priv->state.clip_y0);
render_priv->state.clip_y1 =
y2scr(render_priv, render_priv->state.clip_y1);
} else if (valign == VALIGN_SUB) {
render_priv->state.clip_y0 =
y2scr_sub(render_priv, render_priv->state.clip_y0);
render_priv->state.clip_y1 =
y2scr_sub(render_priv, render_priv->state.clip_y1);
}
} else if (render_priv->state.evt_type == EVENT_POSITIONED) {
render_priv->state.clip_x0 =
x2scr_pos_scaled(render_priv, render_priv->state.clip_x0);
render_priv->state.clip_x1 =
x2scr_pos_scaled(render_priv, render_priv->state.clip_x1);
render_priv->state.clip_y0 =
y2scr_pos(render_priv, render_priv->state.clip_y0);
render_priv->state.clip_y1 =
y2scr_pos(render_priv, render_priv->state.clip_y1);
}
if (render_priv->state.explicit) {
// we still need to clip against screen boundaries
double zx = x2scr_pos_scaled(render_priv, 0);
double zy = y2scr_pos(render_priv, 0);
double sx = x2scr_pos_scaled(render_priv, render_priv->track->PlayResX);
double sy = y2scr_pos(render_priv, render_priv->track->PlayResY);
render_priv->state.clip_x0 = render_priv->state.clip_x0 < zx ? zx : render_priv->state.clip_x0;
render_priv->state.clip_y0 = render_priv->state.clip_y0 < zy ? zy : render_priv->state.clip_y0;
render_priv->state.clip_x1 = render_priv->state.clip_x1 > sx ? sx : render_priv->state.clip_x1;
render_priv->state.clip_y1 = render_priv->state.clip_y1 > sy ? sy : render_priv->state.clip_y1;
}
calculate_rotation_params(render_priv, &bbox, device_x, device_y);
render_and_combine_glyphs(render_priv, device_x, device_y);
memset(event_images, 0, sizeof(*event_images));
event_images->top = device_y - text_info->lines[0].asc;
event_images->height = text_info->height;
event_images->left =
(device_x + bbox.xMin * render_priv->font_scale_x) + 0.5;
event_images->width =
(bbox.xMax - bbox.xMin) * render_priv->font_scale_x + 0.5;
event_images->detect_collisions = render_priv->state.detect_collisions;
event_images->shift_direction = (valign == VALIGN_TOP) ? 1 : -1;
event_images->event = event;
event_images->imgs = render_text(render_priv);
if (render_priv->state.border_style == 4)
add_background(render_priv, event_images);
ass_shaper_cleanup(render_priv->shaper, text_info);
free_render_context(render_priv);
return 0;
}
/**
* \brief Check cache limits and reset cache if they are exceeded
*/
static void check_cache_limits(ASS_Renderer *priv, CacheStore *cache)
{
ass_cache_cut(cache->composite_cache, cache->composite_max_size);
ass_cache_cut(cache->bitmap_cache, cache->bitmap_max_size);
ass_cache_cut(cache->outline_cache, cache->glyph_max);
}
/**
* \brief Start a new frame
*/
static int
ass_start_frame(ASS_Renderer *render_priv, ASS_Track *track,
long long now)
{
ASS_Settings *settings_priv = &render_priv->settings;
if (!render_priv->settings.frame_width
&& !render_priv->settings.frame_height)
return 1; // library not initialized
if (!render_priv->fontselect)
return 1;
if (render_priv->library != track->library)
return 1;
if (track->n_events == 0)
return 1; // nothing to do
render_priv->track = track;
render_priv->time = now;
ass_lazy_track_init(render_priv->library, render_priv->track);
ass_shaper_set_kerning(render_priv->shaper, track->Kerning);
ass_shaper_set_language(render_priv->shaper, track->Language);
ass_shaper_set_level(render_priv->shaper, render_priv->settings.shaper);
// PAR correction
double par = render_priv->settings.par;
if (par == 0.) {
if (settings_priv->frame_width && settings_priv->frame_height &&
settings_priv->storage_width && settings_priv->storage_height) {
double dar = ((double) settings_priv->frame_width) /
settings_priv->frame_height;
double sar = ((double) settings_priv->storage_width) /
settings_priv->storage_height;
par = sar / dar;
} else
par = 1.0;
}
render_priv->font_scale_x = par;
render_priv->prev_images_root = render_priv->images_root;
render_priv->images_root = NULL;
check_cache_limits(render_priv, &render_priv->cache);
return 0;
}
static int cmp_event_layer(const void *p1, const void *p2)
{
ASS_Event *e1 = ((EventImages *) p1)->event;
ASS_Event *e2 = ((EventImages *) p2)->event;
if (e1->Layer < e2->Layer)
return -1;
if (e1->Layer > e2->Layer)
return 1;
if (e1->ReadOrder < e2->ReadOrder)
return -1;
if (e1->ReadOrder > e2->ReadOrder)
return 1;
return 0;
}
static ASS_RenderPriv *get_render_priv(ASS_Renderer *render_priv,
ASS_Event *event)
{
if (!event->render_priv) {
event->render_priv = calloc(1, sizeof(ASS_RenderPriv));
if (!event->render_priv)
return NULL;
}
if (render_priv->render_id != event->render_priv->render_id) {
memset(event->render_priv, 0, sizeof(ASS_RenderPriv));
event->render_priv->render_id = render_priv->render_id;
}
return event->render_priv;
}
static int overlap(Segment *s1, Segment *s2)
{
if (s1->a >= s2->b || s2->a >= s1->b ||
s1->ha >= s2->hb || s2->ha >= s1->hb)
return 0;
return 1;
}
static int cmp_segment(const void *p1, const void *p2)
{
return ((Segment *) p1)->a - ((Segment *) p2)->a;
}
static void
shift_event(ASS_Renderer *render_priv, EventImages *ei, int shift)
{
ASS_Image *cur = ei->imgs;
while (cur) {
cur->dst_y += shift;
// clip top and bottom
if (cur->dst_y < 0) {
int clip = -cur->dst_y;
cur->h -= clip;
cur->bitmap += clip * cur->stride;
cur->dst_y = 0;
}
if (cur->dst_y + cur->h >= render_priv->height) {
int clip = cur->dst_y + cur->h - render_priv->height;
cur->h -= clip;
}
if (cur->h <= 0) {
cur->h = 0;
cur->dst_y = 0;
}
cur = cur->next;
}
ei->top += shift;
}
// dir: 1 - move down
// -1 - move up
static int fit_segment(Segment *s, Segment *fixed, int *cnt, int dir)
{
int i;
int shift = 0;
if (dir == 1) // move down
for (i = 0; i < *cnt; ++i) {
if (s->b + shift <= fixed[i].a || s->a + shift >= fixed[i].b ||
s->hb <= fixed[i].ha || s->ha >= fixed[i].hb)
continue;
shift = fixed[i].b - s->a;
} else // dir == -1, move up
for (i = *cnt - 1; i >= 0; --i) {
if (s->b + shift <= fixed[i].a || s->a + shift >= fixed[i].b ||
s->hb <= fixed[i].ha || s->ha >= fixed[i].hb)
continue;
shift = fixed[i].a - s->b;
}
fixed[*cnt].a = s->a + shift;
fixed[*cnt].b = s->b + shift;
fixed[*cnt].ha = s->ha;
fixed[*cnt].hb = s->hb;
(*cnt)++;
qsort(fixed, *cnt, sizeof(Segment), cmp_segment);
return shift;
}
static void
fix_collisions(ASS_Renderer *render_priv, EventImages *imgs, int cnt)
{
Segment *used = ass_realloc_array(NULL, cnt, sizeof(*used));
int cnt_used = 0;
int i, j;
if (!used)
return;
// fill used[] with fixed events
for (i = 0; i < cnt; ++i) {
ASS_RenderPriv *priv;
if (!imgs[i].detect_collisions)
continue;
priv = get_render_priv(render_priv, imgs[i].event);
if (priv && priv->height > 0) { // it's a fixed event
Segment s;
s.a = priv->top;
s.b = priv->top + priv->height;
s.ha = priv->left;
s.hb = priv->left + priv->width;
if (priv->height != imgs[i].height) { // no, it's not
ass_msg(render_priv->library, MSGL_WARN,
"Event height has changed");
priv->top = 0;
priv->height = 0;
priv->left = 0;
priv->width = 0;
}
for (j = 0; j < cnt_used; ++j)
if (overlap(&s, used + j)) { // no, it's not
priv->top = 0;
priv->height = 0;
priv->left = 0;
priv->width = 0;
}
if (priv->height > 0) { // still a fixed event
used[cnt_used].a = priv->top;
used[cnt_used].b = priv->top + priv->height;
used[cnt_used].ha = priv->left;
used[cnt_used].hb = priv->left + priv->width;
cnt_used++;
shift_event(render_priv, imgs + i, priv->top - imgs[i].top);
}
}
}
qsort(used, cnt_used, sizeof(Segment), cmp_segment);
// try to fit other events in free spaces
for (i = 0; i < cnt; ++i) {
ASS_RenderPriv *priv;
if (!imgs[i].detect_collisions)
continue;
priv = get_render_priv(render_priv, imgs[i].event);
if (priv && priv->height == 0) { // not a fixed event
int shift;
Segment s;
s.a = imgs[i].top;
s.b = imgs[i].top + imgs[i].height;
s.ha = imgs[i].left;
s.hb = imgs[i].left + imgs[i].width;
shift = fit_segment(&s, used, &cnt_used, imgs[i].shift_direction);
if (shift)
shift_event(render_priv, imgs + i, shift);
// make it fixed
priv->top = imgs[i].top;
priv->height = imgs[i].height;
priv->left = imgs[i].left;
priv->width = imgs[i].width;
}
}
free(used);
}
/**
* \brief compare two images
* \param i1 first image
* \param i2 second image
* \return 0 if identical, 1 if different positions, 2 if different content
*/
static int ass_image_compare(ASS_Image *i1, ASS_Image *i2)
{
if (i1->w != i2->w)
return 2;
if (i1->h != i2->h)
return 2;
if (i1->stride != i2->stride)
return 2;
if (i1->color != i2->color)
return 2;
if (i1->bitmap != i2->bitmap)
return 2;
if (i1->dst_x != i2->dst_x)
return 1;
if (i1->dst_y != i2->dst_y)
return 1;
return 0;
}
/**
* \brief compare current and previous image list
* \param priv library handle
* \return 0 if identical, 1 if different positions, 2 if different content
*/
static int ass_detect_change(ASS_Renderer *priv)
{
ASS_Image *img, *img2;
int diff;
if (priv->state.has_clips)
return 2;
img = priv->prev_images_root;
img2 = priv->images_root;
diff = 0;
while (img && diff < 2) {
ASS_Image *next, *next2;
next = img->next;
if (img2) {
int d = ass_image_compare(img, img2);
if (d > diff)
diff = d;
next2 = img2->next;
} else {
// previous list is shorter
diff = 2;
break;
}
img = next;
img2 = next2;
}
// is the previous list longer?
if (img2)
diff = 2;
return diff;
}
/**
* \brief render a frame
* \param priv library handle
* \param track track
* \param now current video timestamp (ms)
* \param detect_change a value describing how the new images differ from the previous ones will be written here:
* 0 if identical, 1 if different positions, 2 if different content.
* Can be NULL, in that case no detection is performed.
*/
ASS_Image *ass_render_frame(ASS_Renderer *priv, ASS_Track *track,
long long now, int *detect_change)
{
int i, cnt, rc;
EventImages *last;
ASS_Image **tail;
// init frame
rc = ass_start_frame(priv, track, now);
if (rc != 0) {
if (detect_change) {
*detect_change = 2;
}
return NULL;
}
// render events separately
cnt = 0;
for (i = 0; i < track->n_events; ++i) {
ASS_Event *event = track->events + i;
if ((event->Start <= now)
&& (now < (event->Start + event->Duration))) {
if (cnt >= priv->eimg_size) {
priv->eimg_size += 100;
priv->eimg =
realloc(priv->eimg,
priv->eimg_size * sizeof(EventImages));
}
rc = ass_render_event(priv, event, priv->eimg + cnt);
if (!rc)
++cnt;
}
}
// sort by layer
qsort(priv->eimg, cnt, sizeof(EventImages), cmp_event_layer);
// call fix_collisions for each group of events with the same layer
last = priv->eimg;
for (i = 1; i < cnt; ++i)
if (last->event->Layer != priv->eimg[i].event->Layer) {
fix_collisions(priv, last, priv->eimg + i - last);
last = priv->eimg + i;
}
if (cnt > 0)
fix_collisions(priv, last, priv->eimg + cnt - last);
// concat lists
tail = &priv->images_root;
for (i = 0; i < cnt; ++i) {
ASS_Image *cur = priv->eimg[i].imgs;
while (cur) {
*tail = cur;
tail = &cur->next;
cur = cur->next;
}
}
ass_frame_ref(priv->images_root);
if (detect_change)
*detect_change = ass_detect_change(priv);
// free the previous image list
ass_frame_unref(priv->prev_images_root);
priv->prev_images_root = NULL;
return priv->images_root;
}
/**
* \brief Add reference to a frame image list.
* \param image_list image list returned by ass_render_frame()
*/
void ass_frame_ref(ASS_Image *img)
{
if (!img)
return;
((ASS_ImagePriv *) img)->ref_count++;
}
/**
* \brief Release reference to a frame image list.
* \param image_list image list returned by ass_render_frame()
*/
void ass_frame_unref(ASS_Image *img)
{
if (!img || --((ASS_ImagePriv *) img)->ref_count)
return;
do {
ASS_ImagePriv *priv = (ASS_ImagePriv *) img;
img = img->next;
if (priv->source)
ass_cache_dec_ref(priv->source);
else
ass_aligned_free(priv->result.bitmap);
free(priv);
} while (img);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5341_0 |
crossvul-cpp_data_good_1277_0 | /**********************************************************************
regexec.c - Oniguruma (regular expression library)
**********************************************************************/
/*-
* Copyright (c) 2002-2019 K.Kosako
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "regint.h"
#define IS_MBC_WORD_ASCII_MODE(enc,s,end,mode) \
((mode) == 0 ? ONIGENC_IS_MBC_WORD(enc,s,end) : ONIGENC_IS_MBC_WORD_ASCII(enc,s,end))
#ifdef USE_CRNL_AS_LINE_TERMINATOR
#define ONIGENC_IS_MBC_CRNL(enc,p,end) \
(ONIGENC_MBC_TO_CODE(enc,p,end) == 13 && \
ONIGENC_IS_MBC_NEWLINE(enc,(p+enclen(enc,p)),end))
#endif
#define CHECK_INTERRUPT_IN_MATCH
#ifdef USE_CALLOUT
typedef struct {
int last_match_at_call_counter;
struct {
OnigType type;
OnigValue val;
} slot[ONIG_CALLOUT_DATA_SLOT_NUM];
} CalloutData;
#endif
struct OnigMatchParamStruct {
unsigned int match_stack_limit;
unsigned long retry_limit_in_match;
#ifdef USE_CALLOUT
OnigCalloutFunc progress_callout_of_contents;
OnigCalloutFunc retraction_callout_of_contents;
int match_at_call_counter;
void* callout_user_data;
CalloutData* callout_data;
int callout_data_alloc_num;
#endif
};
extern int
onig_set_match_stack_limit_size_of_match_param(OnigMatchParam* param,
unsigned int limit)
{
param->match_stack_limit = limit;
return ONIG_NORMAL;
}
extern int
onig_set_retry_limit_in_match_of_match_param(OnigMatchParam* param,
unsigned long limit)
{
param->retry_limit_in_match = limit;
return ONIG_NORMAL;
}
extern int
onig_set_progress_callout_of_match_param(OnigMatchParam* param, OnigCalloutFunc f)
{
#ifdef USE_CALLOUT
param->progress_callout_of_contents = f;
return ONIG_NORMAL;
#else
return ONIG_NO_SUPPORT_CONFIG;
#endif
}
extern int
onig_set_retraction_callout_of_match_param(OnigMatchParam* param, OnigCalloutFunc f)
{
#ifdef USE_CALLOUT
param->retraction_callout_of_contents = f;
return ONIG_NORMAL;
#else
return ONIG_NO_SUPPORT_CONFIG;
#endif
}
extern int
onig_set_callout_user_data_of_match_param(OnigMatchParam* param, void* user_data)
{
#ifdef USE_CALLOUT
param->callout_user_data = user_data;
return ONIG_NORMAL;
#else
return ONIG_NO_SUPPORT_CONFIG;
#endif
}
typedef struct {
void* stack_p;
int stack_n;
OnigOptionType options;
OnigRegion* region;
int ptr_num;
const UChar* start; /* search start position (for \G: BEGIN_POSITION) */
unsigned int match_stack_limit;
unsigned long retry_limit_in_match;
OnigMatchParam* mp;
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
int best_len; /* for ONIG_OPTION_FIND_LONGEST */
UChar* best_s;
#endif
} MatchArg;
#ifdef ONIG_DEBUG
/* arguments type */
typedef enum {
ARG_SPECIAL = -1,
ARG_NON = 0,
ARG_RELADDR = 1,
ARG_ABSADDR = 2,
ARG_LENGTH = 3,
ARG_MEMNUM = 4,
ARG_OPTION = 5,
ARG_MODE = 6
} OpArgType;
typedef struct {
short int opcode;
char* name;
} OpInfoType;
static OpInfoType OpInfo[] = {
{ OP_FINISH, "finish" },
{ OP_END, "end" },
{ OP_EXACT1, "exact1" },
{ OP_EXACT2, "exact2" },
{ OP_EXACT3, "exact3" },
{ OP_EXACT4, "exact4" },
{ OP_EXACT5, "exact5" },
{ OP_EXACTN, "exactn" },
{ OP_EXACTMB2N1, "exactmb2-n1" },
{ OP_EXACTMB2N2, "exactmb2-n2" },
{ OP_EXACTMB2N3, "exactmb2-n3" },
{ OP_EXACTMB2N, "exactmb2-n" },
{ OP_EXACTMB3N, "exactmb3n" },
{ OP_EXACTMBN, "exactmbn" },
{ OP_EXACT1_IC, "exact1-ic" },
{ OP_EXACTN_IC, "exactn-ic" },
{ OP_CCLASS, "cclass" },
{ OP_CCLASS_MB, "cclass-mb" },
{ OP_CCLASS_MIX, "cclass-mix" },
{ OP_CCLASS_NOT, "cclass-not" },
{ OP_CCLASS_MB_NOT, "cclass-mb-not" },
{ OP_CCLASS_MIX_NOT, "cclass-mix-not" },
{ OP_ANYCHAR, "anychar" },
{ OP_ANYCHAR_ML, "anychar-ml" },
{ OP_ANYCHAR_STAR, "anychar*" },
{ OP_ANYCHAR_ML_STAR, "anychar-ml*" },
{ OP_ANYCHAR_STAR_PEEK_NEXT, "anychar*-peek-next" },
{ OP_ANYCHAR_ML_STAR_PEEK_NEXT, "anychar-ml*-peek-next" },
{ OP_WORD, "word" },
{ OP_WORD_ASCII, "word-ascii" },
{ OP_NO_WORD, "not-word" },
{ OP_NO_WORD_ASCII, "not-word-ascii" },
{ OP_WORD_BOUNDARY, "word-boundary" },
{ OP_NO_WORD_BOUNDARY, "not-word-boundary" },
{ OP_WORD_BEGIN, "word-begin" },
{ OP_WORD_END, "word-end" },
{ OP_TEXT_SEGMENT_BOUNDARY, "text-segment-boundary" },
{ OP_BEGIN_BUF, "begin-buf" },
{ OP_END_BUF, "end-buf" },
{ OP_BEGIN_LINE, "begin-line" },
{ OP_END_LINE, "end-line" },
{ OP_SEMI_END_BUF, "semi-end-buf" },
{ OP_BEGIN_POSITION, "begin-position" },
{ OP_BACKREF1, "backref1" },
{ OP_BACKREF2, "backref2" },
{ OP_BACKREF_N, "backref-n" },
{ OP_BACKREF_N_IC, "backref-n-ic" },
{ OP_BACKREF_MULTI, "backref_multi" },
{ OP_BACKREF_MULTI_IC, "backref_multi-ic" },
{ OP_BACKREF_WITH_LEVEL, "backref_with_level" },
{ OP_BACKREF_WITH_LEVEL_IC, "backref_with_level-c" },
{ OP_BACKREF_CHECK, "backref_check" },
{ OP_BACKREF_CHECK_WITH_LEVEL, "backref_check_with_level" },
{ OP_MEMORY_START_PUSH, "mem-start-push" },
{ OP_MEMORY_START, "mem-start" },
{ OP_MEMORY_END_PUSH, "mem-end-push" },
{ OP_MEMORY_END_PUSH_REC, "mem-end-push-rec" },
{ OP_MEMORY_END, "mem-end" },
{ OP_MEMORY_END_REC, "mem-end-rec" },
{ OP_FAIL, "fail" },
{ OP_JUMP, "jump" },
{ OP_PUSH, "push" },
{ OP_PUSH_SUPER, "push-super" },
{ OP_POP_OUT, "pop-out" },
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
{ OP_PUSH_OR_JUMP_EXACT1, "push-or-jump-e1" },
#endif
{ OP_PUSH_IF_PEEK_NEXT, "push-if-peek-next" },
{ OP_REPEAT, "repeat" },
{ OP_REPEAT_NG, "repeat-ng" },
{ OP_REPEAT_INC, "repeat-inc" },
{ OP_REPEAT_INC_NG, "repeat-inc-ng" },
{ OP_REPEAT_INC_SG, "repeat-inc-sg" },
{ OP_REPEAT_INC_NG_SG, "repeat-inc-ng-sg" },
{ OP_EMPTY_CHECK_START, "empty-check-start" },
{ OP_EMPTY_CHECK_END, "empty-check-end" },
{ OP_EMPTY_CHECK_END_MEMST, "empty-check-end-memst" },
{ OP_EMPTY_CHECK_END_MEMST_PUSH,"empty-check-end-memst-push" },
{ OP_PREC_READ_START, "push-pos" },
{ OP_PREC_READ_END, "pop-pos" },
{ OP_PREC_READ_NOT_START, "prec-read-not-start" },
{ OP_PREC_READ_NOT_END, "prec-read-not-end" },
{ OP_ATOMIC_START, "atomic-start" },
{ OP_ATOMIC_END, "atomic-end" },
{ OP_LOOK_BEHIND, "look-behind" },
{ OP_LOOK_BEHIND_NOT_START, "look-behind-not-start" },
{ OP_LOOK_BEHIND_NOT_END, "look-behind-not-end" },
{ OP_CALL, "call" },
{ OP_RETURN, "return" },
{ OP_PUSH_SAVE_VAL, "push-save-val" },
{ OP_UPDATE_VAR, "update-var" },
#ifdef USE_CALLOUT
{ OP_CALLOUT_CONTENTS, "callout-contents" },
{ OP_CALLOUT_NAME, "callout-name" },
#endif
{ -1, "" }
};
static char*
op2name(int opcode)
{
int i;
for (i = 0; OpInfo[i].opcode >= 0; i++) {
if (opcode == OpInfo[i].opcode) return OpInfo[i].name;
}
return "";
}
static void
p_string(FILE* f, int len, UChar* s)
{
fputs(":", f);
while (len-- > 0) { fputc(*s++, f); }
}
static void
p_len_string(FILE* f, LengthType len, int mb_len, UChar* s)
{
int x = len * mb_len;
fprintf(f, ":%d:", len);
while (x-- > 0) { fputc(*s++, f); }
}
static void
p_rel_addr(FILE* f, RelAddrType rel_addr, Operation* p, Operation* start)
{
RelAddrType curr = (RelAddrType )(p - start);
fprintf(f, "{%d/%d}", rel_addr, curr + rel_addr);
}
static int
bitset_on_num(BitSetRef bs)
{
int i, n;
n = 0;
for (i = 0; i < SINGLE_BYTE_SIZE; i++) {
if (BITSET_AT(bs, i)) n++;
}
return n;
}
static void
print_compiled_byte_code(FILE* f, regex_t* reg, int index,
Operation* start, OnigEncoding enc)
{
int i, n;
RelAddrType addr;
LengthType len;
MemNumType mem;
OnigCodePoint code;
ModeType mode;
UChar *q;
Operation* p;
enum OpCode opcode;
p = reg->ops + index;
#ifdef USE_DIRECT_THREADED_CODE
opcode = reg->ocs[index];
#else
opcode = p->opcode;
#endif
fprintf(f, "%s", op2name(opcode));
switch (opcode) {
case OP_EXACT1:
p_string(f, 1, p->exact.s); break;
case OP_EXACT2:
p_string(f, 2, p->exact.s); break;
case OP_EXACT3:
p_string(f, 3, p->exact.s); break;
case OP_EXACT4:
p_string(f, 4, p->exact.s); break;
case OP_EXACT5:
p_string(f, 5, p->exact.s); break;
case OP_EXACTN:
len = p->exact_n.n;
p_string(f, len, p->exact_n.s); break;
case OP_EXACTMB2N1:
p_string(f, 2, p->exact.s); break;
case OP_EXACTMB2N2:
p_string(f, 4, p->exact.s); break;
case OP_EXACTMB2N3:
p_string(f, 3, p->exact.s); break;
case OP_EXACTMB2N:
len = p->exact_n.n;
p_len_string(f, len, 2, p->exact_n.s); break;
case OP_EXACTMB3N:
len = p->exact_n.n;
p_len_string(f, len, 3, p->exact_n.s); break;
case OP_EXACTMBN:
{
int mb_len;
mb_len = p->exact_len_n.len;
len = p->exact_len_n.n;
q = p->exact_len_n.s;
fprintf(f, ":%d:%d:", mb_len, len);
n = len * mb_len;
while (n-- > 0) { fputc(*q++, f); }
}
break;
case OP_EXACT1_IC:
len = enclen(enc, p->exact.s);
p_string(f, len, p->exact.s);
break;
case OP_EXACTN_IC:
len = p->exact_n.n;
p_len_string(f, len, 1, p->exact_n.s);
break;
case OP_CCLASS:
case OP_CCLASS_NOT:
n = bitset_on_num(p->cclass.bsp);
fprintf(f, ":%d", n);
break;
case OP_CCLASS_MB:
case OP_CCLASS_MB_NOT:
{
OnigCodePoint ncode;
OnigCodePoint* codes;
codes = (OnigCodePoint* )p->cclass_mb.mb;
GET_CODE_POINT(ncode, codes);
codes++;
GET_CODE_POINT(code, codes);
fprintf(f, ":%u:%u", code, ncode);
}
break;
case OP_CCLASS_MIX:
case OP_CCLASS_MIX_NOT:
{
OnigCodePoint ncode;
OnigCodePoint* codes;
codes = (OnigCodePoint* )p->cclass_mix.mb;
n = bitset_on_num(p->cclass_mix.bsp);
GET_CODE_POINT(ncode, codes);
codes++;
GET_CODE_POINT(code, codes);
fprintf(f, ":%d:%u:%u", n, code, ncode);
}
break;
case OP_ANYCHAR_STAR_PEEK_NEXT:
case OP_ANYCHAR_ML_STAR_PEEK_NEXT:
p_string(f, 1, &(p->anychar_star_peek_next.c));
break;
case OP_WORD_BOUNDARY:
case OP_NO_WORD_BOUNDARY:
case OP_WORD_BEGIN:
case OP_WORD_END:
mode = p->word_boundary.mode;
fprintf(f, ":%d", mode);
break;
case OP_BACKREF_N:
case OP_BACKREF_N_IC:
mem = p->backref_n.n1;
fprintf(f, ":%d", mem);
break;
case OP_BACKREF_MULTI_IC:
case OP_BACKREF_MULTI:
case OP_BACKREF_CHECK:
fputs(" ", f);
n = p->backref_general.num;
for (i = 0; i < n; i++) {
mem = (n == 1) ? p->backref_general.n1 : p->backref_general.ns[i];
if (i > 0) fputs(", ", f);
fprintf(f, "%d", mem);
}
break;
case OP_BACKREF_WITH_LEVEL:
case OP_BACKREF_WITH_LEVEL_IC:
case OP_BACKREF_CHECK_WITH_LEVEL:
{
LengthType level;
level = p->backref_general.nest_level;
fprintf(f, ":%d", level);
fputs(" ", f);
n = p->backref_general.num;
for (i = 0; i < n; i++) {
mem = (n == 1) ? p->backref_general.n1 : p->backref_general.ns[i];
if (i > 0) fputs(", ", f);
fprintf(f, "%d", mem);
}
}
break;
case OP_MEMORY_START:
case OP_MEMORY_START_PUSH:
mem = p->memory_start.num;
fprintf(f, ":%d", mem);
break;
case OP_MEMORY_END_PUSH:
case OP_MEMORY_END_PUSH_REC:
case OP_MEMORY_END:
case OP_MEMORY_END_REC:
mem = p->memory_end.num;
fprintf(f, ":%d", mem);
break;
case OP_JUMP:
addr = p->jump.addr;
fputc(':', f);
p_rel_addr(f, addr, p, start);
break;
case OP_PUSH:
case OP_PUSH_SUPER:
addr = p->push.addr;
fputc(':', f);
p_rel_addr(f, addr, p, start);
break;
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
case OP_PUSH_OR_JUMP_EXACT1:
addr = p->push_or_jump_exact1.addr;
fputc(':', f);
p_rel_addr(f, addr, p, start);
p_string(f, 1, &(p->push_or_jump_exact1.c));
break;
#endif
case OP_PUSH_IF_PEEK_NEXT:
addr = p->push_if_peek_next.addr;
fputc(':', f);
p_rel_addr(f, addr, p, start);
p_string(f, 1, &(p->push_if_peek_next.c));
break;
case OP_REPEAT:
case OP_REPEAT_NG:
mem = p->repeat.id;
addr = p->repeat.addr;
fprintf(f, ":%d:", mem);
p_rel_addr(f, addr, p, start);
break;
case OP_REPEAT_INC:
case OP_REPEAT_INC_NG:
case OP_REPEAT_INC_SG:
case OP_REPEAT_INC_NG_SG:
mem = p->repeat.id;
fprintf(f, ":%d", mem);
break;
case OP_EMPTY_CHECK_START:
mem = p->empty_check_start.mem;
fprintf(f, ":%d", mem);
break;
case OP_EMPTY_CHECK_END:
case OP_EMPTY_CHECK_END_MEMST:
case OP_EMPTY_CHECK_END_MEMST_PUSH:
mem = p->empty_check_end.mem;
fprintf(f, ":%d", mem);
break;
case OP_PREC_READ_NOT_START:
addr = p->prec_read_not_start.addr;
fputc(':', f);
p_rel_addr(f, addr, p, start);
break;
case OP_LOOK_BEHIND:
len = p->look_behind.len;
fprintf(f, ":%d", len);
break;
case OP_LOOK_BEHIND_NOT_START:
addr = p->look_behind_not_start.addr;
len = p->look_behind_not_start.len;
fprintf(f, ":%d:", len);
p_rel_addr(f, addr, p, start);
break;
case OP_CALL:
addr = p->call.addr;
fprintf(f, ":{/%d}", addr);
break;
case OP_PUSH_SAVE_VAL:
{
SaveType type;
type = p->push_save_val.type;
mem = p->push_save_val.id;
fprintf(f, ":%d:%d", type, mem);
}
break;
case OP_UPDATE_VAR:
{
UpdateVarType type;
type = p->update_var.type;
mem = p->update_var.id;
fprintf(f, ":%d:%d", type, mem);
}
break;
#ifdef USE_CALLOUT
case OP_CALLOUT_CONTENTS:
mem = p->callout_contents.num;
fprintf(f, ":%d", mem);
break;
case OP_CALLOUT_NAME:
{
int id;
id = p->callout_name.id;
mem = p->callout_name.num;
fprintf(f, ":%d:%d", id, mem);
}
break;
#endif
case OP_TEXT_SEGMENT_BOUNDARY:
if (p->text_segment_boundary.not != 0)
fprintf(f, ":not");
break;
case OP_FINISH:
case OP_END:
case OP_ANYCHAR:
case OP_ANYCHAR_ML:
case OP_ANYCHAR_STAR:
case OP_ANYCHAR_ML_STAR:
case OP_WORD:
case OP_WORD_ASCII:
case OP_NO_WORD:
case OP_NO_WORD_ASCII:
case OP_BEGIN_BUF:
case OP_END_BUF:
case OP_BEGIN_LINE:
case OP_END_LINE:
case OP_SEMI_END_BUF:
case OP_BEGIN_POSITION:
case OP_BACKREF1:
case OP_BACKREF2:
case OP_FAIL:
case OP_POP_OUT:
case OP_PREC_READ_START:
case OP_PREC_READ_END:
case OP_PREC_READ_NOT_END:
case OP_ATOMIC_START:
case OP_ATOMIC_END:
case OP_LOOK_BEHIND_NOT_END:
case OP_RETURN:
break;
default:
fprintf(stderr, "print_compiled_byte_code: undefined code %d\n", opcode);
break;
}
}
#endif /* ONIG_DEBUG */
#ifdef ONIG_DEBUG_COMPILE
extern void
onig_print_compiled_byte_code_list(FILE* f, regex_t* reg)
{
Operation* bp;
Operation* start = reg->ops;
Operation* end = reg->ops + reg->ops_used;
fprintf(f, "bt_mem_start: 0x%x, bt_mem_end: 0x%x\n",
reg->bt_mem_start, reg->bt_mem_end);
fprintf(f, "code-length: %d\n", reg->ops_used);
bp = start;
while (bp < end) {
int pos = bp - start;
fprintf(f, "%4d: ", pos);
print_compiled_byte_code(f, reg, pos, start, reg->enc);
fprintf(f, "\n");
bp++;
}
fprintf(f, "\n");
}
#endif
#ifdef USE_CAPTURE_HISTORY
static void history_tree_free(OnigCaptureTreeNode* node);
static void
history_tree_clear(OnigCaptureTreeNode* node)
{
int i;
if (IS_NULL(node)) return ;
for (i = 0; i < node->num_childs; i++) {
if (IS_NOT_NULL(node->childs[i])) {
history_tree_free(node->childs[i]);
}
}
for (i = 0; i < node->allocated; i++) {
node->childs[i] = (OnigCaptureTreeNode* )0;
}
node->num_childs = 0;
node->beg = ONIG_REGION_NOTPOS;
node->end = ONIG_REGION_NOTPOS;
node->group = -1;
}
static void
history_tree_free(OnigCaptureTreeNode* node)
{
history_tree_clear(node);
if (IS_NOT_NULL(node->childs)) xfree(node->childs);
xfree(node);
}
static void
history_root_free(OnigRegion* r)
{
if (IS_NULL(r->history_root)) return ;
history_tree_free(r->history_root);
r->history_root = (OnigCaptureTreeNode* )0;
}
static OnigCaptureTreeNode*
history_node_new(void)
{
OnigCaptureTreeNode* node;
node = (OnigCaptureTreeNode* )xmalloc(sizeof(OnigCaptureTreeNode));
CHECK_NULL_RETURN(node);
node->childs = (OnigCaptureTreeNode** )0;
node->allocated = 0;
node->num_childs = 0;
node->group = -1;
node->beg = ONIG_REGION_NOTPOS;
node->end = ONIG_REGION_NOTPOS;
return node;
}
static int
history_tree_add_child(OnigCaptureTreeNode* parent, OnigCaptureTreeNode* child)
{
#define HISTORY_TREE_INIT_ALLOC_SIZE 8
if (parent->num_childs >= parent->allocated) {
int n, i;
if (IS_NULL(parent->childs)) {
n = HISTORY_TREE_INIT_ALLOC_SIZE;
parent->childs =
(OnigCaptureTreeNode** )xmalloc(sizeof(parent->childs[0]) * n);
}
else {
n = parent->allocated * 2;
parent->childs =
(OnigCaptureTreeNode** )xrealloc(parent->childs,
sizeof(parent->childs[0]) * n);
}
CHECK_NULL_RETURN_MEMERR(parent->childs);
for (i = parent->allocated; i < n; i++) {
parent->childs[i] = (OnigCaptureTreeNode* )0;
}
parent->allocated = n;
}
parent->childs[parent->num_childs] = child;
parent->num_childs++;
return 0;
}
static OnigCaptureTreeNode*
history_tree_clone(OnigCaptureTreeNode* node)
{
int i;
OnigCaptureTreeNode *clone, *child;
clone = history_node_new();
CHECK_NULL_RETURN(clone);
clone->beg = node->beg;
clone->end = node->end;
for (i = 0; i < node->num_childs; i++) {
child = history_tree_clone(node->childs[i]);
if (IS_NULL(child)) {
history_tree_free(clone);
return (OnigCaptureTreeNode* )0;
}
history_tree_add_child(clone, child);
}
return clone;
}
extern OnigCaptureTreeNode*
onig_get_capture_tree(OnigRegion* region)
{
return region->history_root;
}
#endif /* USE_CAPTURE_HISTORY */
extern void
onig_region_clear(OnigRegion* region)
{
int i;
for (i = 0; i < region->num_regs; i++) {
region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS;
}
#ifdef USE_CAPTURE_HISTORY
history_root_free(region);
#endif
}
extern int
onig_region_resize(OnigRegion* region, int n)
{
region->num_regs = n;
if (n < ONIG_NREGION)
n = ONIG_NREGION;
if (region->allocated == 0) {
region->beg = (int* )xmalloc(n * sizeof(int));
region->end = (int* )xmalloc(n * sizeof(int));
if (region->beg == 0 || region->end == 0)
return ONIGERR_MEMORY;
region->allocated = n;
}
else if (region->allocated < n) {
region->beg = (int* )xrealloc(region->beg, n * sizeof(int));
region->end = (int* )xrealloc(region->end, n * sizeof(int));
if (region->beg == 0 || region->end == 0)
return ONIGERR_MEMORY;
region->allocated = n;
}
return 0;
}
static int
onig_region_resize_clear(OnigRegion* region, int n)
{
int r;
r = onig_region_resize(region, n);
if (r != 0) return r;
onig_region_clear(region);
return 0;
}
extern int
onig_region_set(OnigRegion* region, int at, int beg, int end)
{
if (at < 0) return ONIGERR_INVALID_ARGUMENT;
if (at >= region->allocated) {
int r = onig_region_resize(region, at + 1);
if (r < 0) return r;
}
region->beg[at] = beg;
region->end[at] = end;
return 0;
}
extern void
onig_region_init(OnigRegion* region)
{
region->num_regs = 0;
region->allocated = 0;
region->beg = (int* )0;
region->end = (int* )0;
region->history_root = (OnigCaptureTreeNode* )0;
}
extern OnigRegion*
onig_region_new(void)
{
OnigRegion* r;
r = (OnigRegion* )xmalloc(sizeof(OnigRegion));
CHECK_NULL_RETURN(r);
onig_region_init(r);
return r;
}
extern void
onig_region_free(OnigRegion* r, int free_self)
{
if (r != 0) {
if (r->allocated > 0) {
if (r->beg) xfree(r->beg);
if (r->end) xfree(r->end);
r->allocated = 0;
}
#ifdef USE_CAPTURE_HISTORY
history_root_free(r);
#endif
if (free_self) xfree(r);
}
}
extern void
onig_region_copy(OnigRegion* to, OnigRegion* from)
{
#define RREGC_SIZE (sizeof(int) * from->num_regs)
int i;
if (to == from) return;
if (to->allocated == 0) {
if (from->num_regs > 0) {
to->beg = (int* )xmalloc(RREGC_SIZE);
if (IS_NULL(to->beg)) return;
to->end = (int* )xmalloc(RREGC_SIZE);
if (IS_NULL(to->end)) return;
to->allocated = from->num_regs;
}
}
else if (to->allocated < from->num_regs) {
to->beg = (int* )xrealloc(to->beg, RREGC_SIZE);
if (IS_NULL(to->beg)) return;
to->end = (int* )xrealloc(to->end, RREGC_SIZE);
if (IS_NULL(to->end)) return;
to->allocated = from->num_regs;
}
for (i = 0; i < from->num_regs; i++) {
to->beg[i] = from->beg[i];
to->end[i] = from->end[i];
}
to->num_regs = from->num_regs;
#ifdef USE_CAPTURE_HISTORY
history_root_free(to);
if (IS_NOT_NULL(from->history_root)) {
to->history_root = history_tree_clone(from->history_root);
}
#endif
}
#ifdef USE_CALLOUT
#define CALLOUT_BODY(func, ain, aname_id, anum, user, args, result) do { \
args.in = (ain);\
args.name_id = (aname_id);\
args.num = anum;\
args.regex = reg;\
args.string = str;\
args.string_end = end;\
args.start = sstart;\
args.right_range = right_range;\
args.current = s;\
args.retry_in_match_counter = retry_in_match_counter;\
args.msa = msa;\
args.stk_base = stk_base;\
args.stk = stk;\
args.mem_start_stk = mem_start_stk;\
args.mem_end_stk = mem_end_stk;\
result = (func)(&args, user);\
} while (0)
#define RETRACTION_CALLOUT(func, aname_id, anum, user) do {\
int result;\
OnigCalloutArgs args;\
CALLOUT_BODY(func, ONIG_CALLOUT_IN_RETRACTION, aname_id, anum, user, args, result);\
switch (result) {\
case ONIG_CALLOUT_FAIL:\
case ONIG_CALLOUT_SUCCESS:\
break;\
default:\
if (result > 0) {\
result = ONIGERR_INVALID_ARGUMENT;\
}\
best_len = result;\
goto finish;\
break;\
}\
} while(0)
#endif
/** stack **/
#define INVALID_STACK_INDEX -1
#define STK_ALT_FLAG 0x0001
/* stack type */
/* used by normal-POP */
#define STK_SUPER_ALT STK_ALT_FLAG
#define STK_ALT (0x0002 | STK_ALT_FLAG)
#define STK_ALT_PREC_READ_NOT (0x0004 | STK_ALT_FLAG)
#define STK_ALT_LOOK_BEHIND_NOT (0x0006 | STK_ALT_FLAG)
/* handled by normal-POP */
#define STK_MEM_START 0x0010
#define STK_MEM_END 0x8030
#define STK_REPEAT_INC 0x0050
#ifdef USE_CALLOUT
#define STK_CALLOUT 0x0070
#endif
/* avoided by normal-POP */
#define STK_VOID 0x0000 /* for fill a blank */
#define STK_EMPTY_CHECK_START 0x3000
#define STK_EMPTY_CHECK_END 0x5000 /* for recursive call */
#define STK_MEM_END_MARK 0x8100
#define STK_TO_VOID_START 0x1200 /* mark for "(?>...)" */
#define STK_REPEAT 0x0300
#define STK_CALL_FRAME 0x0400
#define STK_RETURN 0x0500
#define STK_SAVE_VAL 0x0600
#define STK_PREC_READ_START 0x0700
#define STK_PREC_READ_END 0x0800
/* stack type check mask */
#define STK_MASK_POP_USED STK_ALT_FLAG
#define STK_MASK_POP_HANDLED 0x0010
#define STK_MASK_POP_HANDLED_TIL (STK_MASK_POP_HANDLED | 0x0004)
#define STK_MASK_TO_VOID_TARGET 0x100e
#define STK_MASK_MEM_END_OR_MARK 0x8000 /* MEM_END or MEM_END_MARK */
typedef intptr_t StackIndex;
typedef struct _StackType {
unsigned int type;
int zid;
union {
struct {
Operation* pcode; /* byte code position */
UChar* pstr; /* string position */
UChar* pstr_prev; /* previous char position of pstr */
} state;
struct {
int count; /* for OP_REPEAT_INC, OP_REPEAT_INC_NG */
Operation* pcode; /* byte code position (head of repeated target) */
} repeat;
struct {
StackIndex si; /* index of stack */
} repeat_inc;
struct {
UChar *pstr; /* start/end position */
/* Following information is set, if this stack type is MEM-START */
StackIndex prev_start; /* prev. info (for backtrack "(...)*" ) */
StackIndex prev_end; /* prev. info (for backtrack "(...)*" ) */
} mem;
struct {
UChar *pstr; /* start position */
} empty_check;
#ifdef USE_CALL
struct {
Operation *ret_addr; /* byte code position */
UChar *pstr; /* string position */
} call_frame;
#endif
struct {
enum SaveType type;
UChar* v;
UChar* v2;
} val;
#ifdef USE_CALLOUT
struct {
int num;
OnigCalloutFunc func;
} callout;
#endif
} u;
} StackType;
#ifdef USE_CALLOUT
struct OnigCalloutArgsStruct {
OnigCalloutIn in;
int name_id; /* name id or ONIG_NON_NAME_ID */
int num;
OnigRegex regex;
const OnigUChar* string;
const OnigUChar* string_end;
const OnigUChar* start;
const OnigUChar* right_range;
const OnigUChar* current; /* current matching position */
unsigned long retry_in_match_counter;
/* invisible to users */
MatchArg* msa;
StackType* stk_base;
StackType* stk;
StackIndex* mem_start_stk;
StackIndex* mem_end_stk;
};
#endif
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
#define MATCH_ARG_INIT(msa, reg, arg_option, arg_region, arg_start, mp) do { \
(msa).stack_p = (void* )0;\
(msa).options = (arg_option);\
(msa).region = (arg_region);\
(msa).start = (arg_start);\
(msa).match_stack_limit = (mp)->match_stack_limit;\
(msa).retry_limit_in_match = (mp)->retry_limit_in_match;\
(msa).mp = mp;\
(msa).best_len = ONIG_MISMATCH;\
(msa).ptr_num = (reg)->num_repeat + ((reg)->num_mem + 1) * 2; \
} while(0)
#else
#define MATCH_ARG_INIT(msa, reg, arg_option, arg_region, arg_start, mp) do { \
(msa).stack_p = (void* )0;\
(msa).options = (arg_option);\
(msa).region = (arg_region);\
(msa).start = (arg_start);\
(msa).match_stack_limit = (mp)->match_stack_limit;\
(msa).retry_limit_in_match = (mp)->retry_limit_in_match;\
(msa).mp = mp;\
(msa).ptr_num = (reg)->num_repeat + ((reg)->num_mem + 1) * 2; \
} while(0)
#endif
#define MATCH_ARG_FREE(msa) if ((msa).stack_p) xfree((msa).stack_p)
#define ALLOCA_PTR_NUM_LIMIT 50
#define STACK_INIT(stack_num) do {\
if (msa->stack_p) {\
is_alloca = 0;\
alloc_base = msa->stack_p;\
stk_base = (StackType* )(alloc_base\
+ (sizeof(StackIndex) * msa->ptr_num));\
stk = stk_base;\
stk_end = stk_base + msa->stack_n;\
}\
else if (msa->ptr_num > ALLOCA_PTR_NUM_LIMIT) {\
is_alloca = 0;\
alloc_base = (char* )xmalloc(sizeof(StackIndex) * msa->ptr_num\
+ sizeof(StackType) * (stack_num));\
CHECK_NULL_RETURN_MEMERR(alloc_base);\
stk_base = (StackType* )(alloc_base\
+ (sizeof(StackIndex) * msa->ptr_num));\
stk = stk_base;\
stk_end = stk_base + (stack_num);\
}\
else {\
is_alloca = 1;\
alloc_base = (char* )xalloca(sizeof(StackIndex) * msa->ptr_num\
+ sizeof(StackType) * (stack_num));\
CHECK_NULL_RETURN_MEMERR(alloc_base);\
stk_base = (StackType* )(alloc_base\
+ (sizeof(StackIndex) * msa->ptr_num));\
stk = stk_base;\
stk_end = stk_base + (stack_num);\
}\
} while(0);
#define STACK_SAVE do{\
msa->stack_n = (int )(stk_end - stk_base);\
if (is_alloca != 0) {\
size_t size = sizeof(StackIndex) * msa->ptr_num \
+ sizeof(StackType) * msa->stack_n;\
msa->stack_p = xmalloc(size);\
CHECK_NULL_RETURN_MEMERR(msa->stack_p);\
xmemcpy(msa->stack_p, alloc_base, size);\
}\
else {\
msa->stack_p = alloc_base;\
};\
} while(0)
#define UPDATE_FOR_STACK_REALLOC do{\
repeat_stk = (StackIndex* )alloc_base;\
mem_start_stk = (StackIndex* )(repeat_stk + reg->num_repeat);\
mem_end_stk = mem_start_stk + num_mem + 1;\
} while(0)
static unsigned int MatchStackLimit = DEFAULT_MATCH_STACK_LIMIT_SIZE;
extern unsigned int
onig_get_match_stack_limit_size(void)
{
return MatchStackLimit;
}
extern int
onig_set_match_stack_limit_size(unsigned int size)
{
MatchStackLimit = size;
return 0;
}
#ifdef USE_RETRY_LIMIT_IN_MATCH
static unsigned long RetryLimitInMatch = DEFAULT_RETRY_LIMIT_IN_MATCH;
#define CHECK_RETRY_LIMIT_IN_MATCH do {\
if (retry_in_match_counter++ > retry_limit_in_match) goto retry_limit_in_match_over;\
} while (0)
#else
#define CHECK_RETRY_LIMIT_IN_MATCH
#endif /* USE_RETRY_LIMIT_IN_MATCH */
extern unsigned long
onig_get_retry_limit_in_match(void)
{
#ifdef USE_RETRY_LIMIT_IN_MATCH
return RetryLimitInMatch;
#else
/* return ONIG_NO_SUPPORT_CONFIG; */
return 0;
#endif
}
extern int
onig_set_retry_limit_in_match(unsigned long size)
{
#ifdef USE_RETRY_LIMIT_IN_MATCH
RetryLimitInMatch = size;
return 0;
#else
return ONIG_NO_SUPPORT_CONFIG;
#endif
}
#ifdef USE_CALLOUT
static OnigCalloutFunc DefaultProgressCallout;
static OnigCalloutFunc DefaultRetractionCallout;
#endif
extern OnigMatchParam*
onig_new_match_param(void)
{
OnigMatchParam* p;
p = (OnigMatchParam* )xmalloc(sizeof(*p));
if (IS_NOT_NULL(p)) {
onig_initialize_match_param(p);
}
return p;
}
extern void
onig_free_match_param_content(OnigMatchParam* p)
{
#ifdef USE_CALLOUT
if (IS_NOT_NULL(p->callout_data)) {
xfree(p->callout_data);
p->callout_data = 0;
}
#endif
}
extern void
onig_free_match_param(OnigMatchParam* p)
{
if (IS_NOT_NULL(p)) {
onig_free_match_param_content(p);
xfree(p);
}
}
extern int
onig_initialize_match_param(OnigMatchParam* mp)
{
mp->match_stack_limit = MatchStackLimit;
#ifdef USE_RETRY_LIMIT_IN_MATCH
mp->retry_limit_in_match = RetryLimitInMatch;
#endif
#ifdef USE_CALLOUT
mp->progress_callout_of_contents = DefaultProgressCallout;
mp->retraction_callout_of_contents = DefaultRetractionCallout;
mp->match_at_call_counter = 0;
mp->callout_user_data = 0;
mp->callout_data = 0;
mp->callout_data_alloc_num = 0;
#endif
return ONIG_NORMAL;
}
#ifdef USE_CALLOUT
static int
adjust_match_param(regex_t* reg, OnigMatchParam* mp)
{
RegexExt* ext = reg->extp;
mp->match_at_call_counter = 0;
if (IS_NULL(ext) || ext->callout_num == 0) return ONIG_NORMAL;
if (ext->callout_num > mp->callout_data_alloc_num) {
CalloutData* d;
size_t n = ext->callout_num * sizeof(*d);
if (IS_NOT_NULL(mp->callout_data))
d = (CalloutData* )xrealloc(mp->callout_data, n);
else
d = (CalloutData* )xmalloc(n);
CHECK_NULL_RETURN_MEMERR(d);
mp->callout_data = d;
mp->callout_data_alloc_num = ext->callout_num;
}
xmemset(mp->callout_data, 0, mp->callout_data_alloc_num * sizeof(CalloutData));
return ONIG_NORMAL;
}
#define ADJUST_MATCH_PARAM(reg, mp) \
r = adjust_match_param(reg, mp);\
if (r != ONIG_NORMAL) return r;
#define CALLOUT_DATA_AT_NUM(mp, num) ((mp)->callout_data + ((num) - 1))
extern int
onig_check_callout_data_and_clear_old_values(OnigCalloutArgs* args)
{
OnigMatchParam* mp;
int num;
CalloutData* d;
mp = args->msa->mp;
num = args->num;
d = CALLOUT_DATA_AT_NUM(mp, num);
if (d->last_match_at_call_counter != mp->match_at_call_counter) {
xmemset(d, 0, sizeof(*d));
d->last_match_at_call_counter = mp->match_at_call_counter;
return d->last_match_at_call_counter;
}
return 0;
}
extern int
onig_get_callout_data_dont_clear_old(regex_t* reg, OnigMatchParam* mp,
int callout_num, int slot,
OnigType* type, OnigValue* val)
{
OnigType t;
CalloutData* d;
if (callout_num <= 0) return ONIGERR_INVALID_ARGUMENT;
d = CALLOUT_DATA_AT_NUM(mp, callout_num);
t = d->slot[slot].type;
if (IS_NOT_NULL(type)) *type = t;
if (IS_NOT_NULL(val)) *val = d->slot[slot].val;
return (t == ONIG_TYPE_VOID ? 1 : ONIG_NORMAL);
}
extern int
onig_get_callout_data_by_callout_args_self_dont_clear_old(OnigCalloutArgs* args,
int slot, OnigType* type,
OnigValue* val)
{
return onig_get_callout_data_dont_clear_old(args->regex, args->msa->mp,
args->num, slot, type, val);
}
extern int
onig_get_callout_data(regex_t* reg, OnigMatchParam* mp,
int callout_num, int slot,
OnigType* type, OnigValue* val)
{
OnigType t;
CalloutData* d;
if (callout_num <= 0) return ONIGERR_INVALID_ARGUMENT;
d = CALLOUT_DATA_AT_NUM(mp, callout_num);
if (d->last_match_at_call_counter != mp->match_at_call_counter) {
xmemset(d, 0, sizeof(*d));
d->last_match_at_call_counter = mp->match_at_call_counter;
}
t = d->slot[slot].type;
if (IS_NOT_NULL(type)) *type = t;
if (IS_NOT_NULL(val)) *val = d->slot[slot].val;
return (t == ONIG_TYPE_VOID ? 1 : ONIG_NORMAL);
}
extern int
onig_get_callout_data_by_tag(regex_t* reg, OnigMatchParam* mp,
const UChar* tag, const UChar* tag_end, int slot,
OnigType* type, OnigValue* val)
{
int num;
num = onig_get_callout_num_by_tag(reg, tag, tag_end);
if (num < 0) return num;
if (num == 0) return ONIGERR_INVALID_CALLOUT_TAG_NAME;
return onig_get_callout_data(reg, mp, num, slot, type, val);
}
extern int
onig_get_callout_data_by_callout_args(OnigCalloutArgs* args,
int callout_num, int slot,
OnigType* type, OnigValue* val)
{
return onig_get_callout_data(args->regex, args->msa->mp, callout_num, slot,
type, val);
}
extern int
onig_get_callout_data_by_callout_args_self(OnigCalloutArgs* args,
int slot, OnigType* type, OnigValue* val)
{
return onig_get_callout_data(args->regex, args->msa->mp, args->num, slot,
type, val);
}
extern int
onig_set_callout_data(regex_t* reg, OnigMatchParam* mp,
int callout_num, int slot,
OnigType type, OnigValue* val)
{
CalloutData* d;
if (callout_num <= 0) return ONIGERR_INVALID_ARGUMENT;
d = CALLOUT_DATA_AT_NUM(mp, callout_num);
d->slot[slot].type = type;
d->slot[slot].val = *val;
d->last_match_at_call_counter = mp->match_at_call_counter;
return ONIG_NORMAL;
}
extern int
onig_set_callout_data_by_tag(regex_t* reg, OnigMatchParam* mp,
const UChar* tag, const UChar* tag_end, int slot,
OnigType type, OnigValue* val)
{
int num;
num = onig_get_callout_num_by_tag(reg, tag, tag_end);
if (num < 0) return num;
if (num == 0) return ONIGERR_INVALID_CALLOUT_TAG_NAME;
return onig_set_callout_data(reg, mp, num, slot, type, val);
}
extern int
onig_set_callout_data_by_callout_args(OnigCalloutArgs* args,
int callout_num, int slot,
OnigType type, OnigValue* val)
{
return onig_set_callout_data(args->regex, args->msa->mp, callout_num, slot,
type, val);
}
extern int
onig_set_callout_data_by_callout_args_self(OnigCalloutArgs* args,
int slot, OnigType type, OnigValue* val)
{
return onig_set_callout_data(args->regex, args->msa->mp, args->num, slot,
type, val);
}
#else
#define ADJUST_MATCH_PARAM(reg, mp)
#endif /* USE_CALLOUT */
static int
stack_double(int is_alloca, char** arg_alloc_base,
StackType** arg_stk_base, StackType** arg_stk_end, StackType** arg_stk,
MatchArg* msa)
{
unsigned int n;
int used;
size_t size;
size_t new_size;
char* alloc_base;
char* new_alloc_base;
StackType *stk_base, *stk_end, *stk;
alloc_base = *arg_alloc_base;
stk_base = *arg_stk_base;
stk_end = *arg_stk_end;
stk = *arg_stk;
n = (unsigned int )(stk_end - stk_base);
size = sizeof(StackIndex) * msa->ptr_num + sizeof(StackType) * n;
n *= 2;
new_size = sizeof(StackIndex) * msa->ptr_num + sizeof(StackType) * n;
if (is_alloca != 0) {
new_alloc_base = (char* )xmalloc(new_size);
if (IS_NULL(new_alloc_base)) {
STACK_SAVE;
return ONIGERR_MEMORY;
}
xmemcpy(new_alloc_base, alloc_base, size);
}
else {
if (msa->match_stack_limit != 0 && n > msa->match_stack_limit) {
if ((unsigned int )(stk_end - stk_base) == msa->match_stack_limit)
return ONIGERR_MATCH_STACK_LIMIT_OVER;
else
n = msa->match_stack_limit;
}
new_alloc_base = (char* )xrealloc(alloc_base, new_size);
if (IS_NULL(new_alloc_base)) {
STACK_SAVE;
return ONIGERR_MEMORY;
}
}
alloc_base = new_alloc_base;
used = (int )(stk - stk_base);
*arg_alloc_base = alloc_base;
*arg_stk_base = (StackType* )(alloc_base
+ (sizeof(StackIndex) * msa->ptr_num));
*arg_stk = *arg_stk_base + used;
*arg_stk_end = *arg_stk_base + n;
return 0;
}
#define STACK_ENSURE(n) do {\
if ((int )(stk_end - stk) < (n)) {\
int r = stack_double(is_alloca, &alloc_base, &stk_base, &stk_end, &stk, msa);\
if (r != 0) { STACK_SAVE; return r; } \
is_alloca = 0;\
UPDATE_FOR_STACK_REALLOC;\
}\
} while(0)
#define STACK_AT(index) (stk_base + (index))
#define GET_STACK_INDEX(stk) ((stk) - stk_base)
#define STACK_PUSH_TYPE(stack_type) do {\
STACK_ENSURE(1);\
stk->type = (stack_type);\
STACK_INC;\
} while(0)
#define IS_TO_VOID_TARGET(stk) (((stk)->type & STK_MASK_TO_VOID_TARGET) != 0)
#define STACK_PUSH(stack_type,pat,s,sprev) do {\
STACK_ENSURE(1);\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
stk->u.state.pstr = (s);\
stk->u.state.pstr_prev = (sprev);\
STACK_INC;\
} while(0)
#define STACK_PUSH_ENSURED(stack_type,pat) do {\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
STACK_INC;\
} while(0)
#ifdef ONIG_DEBUG_MATCH
#define STACK_PUSH_BOTTOM(stack_type,pat) do {\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
stk->u.state.pstr = s;\
stk->u.state.pstr_prev = sprev;\
STACK_INC;\
} while (0)
#else
#define STACK_PUSH_BOTTOM(stack_type,pat) do {\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
STACK_INC;\
} while (0)
#endif
#define STACK_PUSH_ALT(pat,s,sprev) STACK_PUSH(STK_ALT,pat,s,sprev)
#define STACK_PUSH_SUPER_ALT(pat,s,sprev) STACK_PUSH(STK_SUPER_ALT,pat,s,sprev)
#define STACK_PUSH_PREC_READ_START(s,sprev) \
STACK_PUSH(STK_PREC_READ_START,(Operation* )0,s,sprev)
#define STACK_PUSH_ALT_PREC_READ_NOT(pat,s,sprev) \
STACK_PUSH(STK_ALT_PREC_READ_NOT,pat,s,sprev)
#define STACK_PUSH_TO_VOID_START STACK_PUSH_TYPE(STK_TO_VOID_START)
#define STACK_PUSH_ALT_LOOK_BEHIND_NOT(pat,s,sprev) \
STACK_PUSH(STK_ALT_LOOK_BEHIND_NOT,pat,s,sprev)
#define STACK_PUSH_REPEAT(sid, pat) do {\
STACK_ENSURE(1);\
stk->type = STK_REPEAT;\
stk->zid = (sid);\
stk->u.repeat.pcode = (pat);\
stk->u.repeat.count = 0;\
STACK_INC;\
} while(0)
#define STACK_PUSH_REPEAT_INC(sindex) do {\
STACK_ENSURE(1);\
stk->type = STK_REPEAT_INC;\
stk->u.repeat_inc.si = (sindex);\
STACK_INC;\
} while(0)
#define STACK_PUSH_MEM_START(mnum, s) do {\
STACK_ENSURE(1);\
stk->type = STK_MEM_START;\
stk->zid = (mnum);\
stk->u.mem.pstr = (s);\
stk->u.mem.prev_start = mem_start_stk[mnum];\
stk->u.mem.prev_end = mem_end_stk[mnum];\
mem_start_stk[mnum] = GET_STACK_INDEX(stk);\
mem_end_stk[mnum] = INVALID_STACK_INDEX;\
STACK_INC;\
} while(0)
#define STACK_PUSH_MEM_END(mnum, s) do {\
STACK_ENSURE(1);\
stk->type = STK_MEM_END;\
stk->zid = (mnum);\
stk->u.mem.pstr = (s);\
stk->u.mem.prev_start = mem_start_stk[mnum];\
stk->u.mem.prev_end = mem_end_stk[mnum];\
mem_end_stk[mnum] = GET_STACK_INDEX(stk);\
STACK_INC;\
} while(0)
#define STACK_PUSH_MEM_END_MARK(mnum) do {\
STACK_ENSURE(1);\
stk->type = STK_MEM_END_MARK;\
stk->zid = (mnum);\
STACK_INC;\
} while(0)
#define STACK_GET_MEM_START(mnum, k) do {\
int level = 0;\
k = stk;\
while (k > stk_base) {\
k--;\
if ((k->type & STK_MASK_MEM_END_OR_MARK) != 0 \
&& k->zid == (mnum)) {\
level++;\
}\
else if (k->type == STK_MEM_START && k->zid == (mnum)) {\
if (level == 0) break;\
level--;\
}\
}\
} while(0)
#define STACK_GET_MEM_RANGE(k, mnum, start, end) do {\
int level = 0;\
while (k < stk) {\
if (k->type == STK_MEM_START && k->u.mem.num == (mnum)) {\
if (level == 0) (start) = k->u.mem.pstr;\
level++;\
}\
else if (k->type == STK_MEM_END && k->u.mem.num == (mnum)) {\
level--;\
if (level == 0) {\
(end) = k->u.mem.pstr;\
break;\
}\
}\
k++;\
}\
} while(0)
#define STACK_PUSH_EMPTY_CHECK_START(cnum, s) do {\
STACK_ENSURE(1);\
stk->type = STK_EMPTY_CHECK_START;\
stk->zid = (cnum);\
stk->u.empty_check.pstr = (s);\
STACK_INC;\
} while(0)
#define STACK_PUSH_EMPTY_CHECK_END(cnum) do {\
STACK_ENSURE(1);\
stk->type = STK_EMPTY_CHECK_END;\
stk->zid = (cnum);\
STACK_INC;\
} while(0)
#define STACK_PUSH_CALL_FRAME(pat) do {\
STACK_ENSURE(1);\
stk->type = STK_CALL_FRAME;\
stk->u.call_frame.ret_addr = (pat);\
STACK_INC;\
} while(0)
#define STACK_PUSH_RETURN do {\
STACK_ENSURE(1);\
stk->type = STK_RETURN;\
STACK_INC;\
} while(0)
#define STACK_PUSH_SAVE_VAL(sid, stype, sval) do {\
STACK_ENSURE(1);\
stk->type = STK_SAVE_VAL;\
stk->zid = (sid);\
stk->u.val.type = (stype);\
stk->u.val.v = (UChar* )(sval);\
STACK_INC;\
} while(0)
#define STACK_PUSH_SAVE_VAL_WITH_SPREV(sid, stype, sval) do {\
STACK_ENSURE(1);\
stk->type = STK_SAVE_VAL;\
stk->zid = (sid);\
stk->u.val.type = (stype);\
stk->u.val.v = (UChar* )(sval);\
stk->u.val.v2 = sprev;\
STACK_INC;\
} while(0)
#define STACK_GET_SAVE_VAL_TYPE_LAST(stype, sval) do {\
StackType *k = stk;\
while (k > stk_base) {\
k--;\
STACK_BASE_CHECK(k, "STACK_GET_SAVE_VAL_TYPE_LAST"); \
if (k->type == STK_SAVE_VAL && k->u.val.type == (stype)) {\
(sval) = k->u.val.v;\
break;\
}\
}\
} while (0)
#define STACK_GET_SAVE_VAL_TYPE_LAST_ID(stype, sid, sval) do { \
int level = 0;\
StackType *k = stk;\
while (k > stk_base) {\
k--;\
STACK_BASE_CHECK(k, "STACK_GET_SAVE_VAL_TYPE_LAST_ID"); \
if (k->type == STK_SAVE_VAL && k->u.val.type == (stype)\
&& k->zid == (sid)) {\
if (level == 0) {\
(sval) = k->u.val.v;\
break;\
}\
}\
else if (k->type == STK_CALL_FRAME)\
level--;\
else if (k->type == STK_RETURN)\
level++;\
}\
} while (0)
#define STACK_GET_SAVE_VAL_TYPE_LAST_ID_WITH_SPREV(stype, sid, sval) do { \
int level = 0;\
StackType *k = stk;\
while (k > stk_base) {\
k--;\
STACK_BASE_CHECK(k, "STACK_GET_SAVE_VAL_TYPE_LAST_ID"); \
if (k->type == STK_SAVE_VAL && k->u.val.type == (stype)\
&& k->zid == (sid)) {\
if (level == 0) {\
(sval) = k->u.val.v;\
sprev = k->u.val.v2;\
break;\
}\
}\
else if (k->type == STK_CALL_FRAME)\
level--;\
else if (k->type == STK_RETURN)\
level++;\
}\
} while (0)
#define STACK_GET_SAVE_VAL_TYPE_LAST_ID_FROM(stype, sid, sval, stk_from) do { \
int level = 0;\
StackType *k = (stk_from);\
while (k > stk_base) {\
STACK_BASE_CHECK(k, "STACK_GET_SAVE_VAL_TYPE_LAST_ID_FROM"); \
if (k->type == STK_SAVE_VAL && k->u.val.type == (stype)\
&& k->u.val.id == (sid)) {\
if (level == 0) {\
(sval) = k->u.val.v;\
break;\
}\
}\
else if (k->type == STK_CALL_FRAME)\
level--;\
else if (k->type == STK_RETURN)\
level++;\
k--;\
}\
} while (0)
#define STACK_PUSH_CALLOUT_CONTENTS(anum, func) do {\
STACK_ENSURE(1);\
stk->type = STK_CALLOUT;\
stk->zid = ONIG_NON_NAME_ID;\
stk->u.callout.num = (anum);\
stk->u.callout.func = (func);\
STACK_INC;\
} while(0)
#define STACK_PUSH_CALLOUT_NAME(aid, anum, func) do {\
STACK_ENSURE(1);\
stk->type = STK_CALLOUT;\
stk->zid = (aid);\
stk->u.callout.num = (anum);\
stk->u.callout.func = (func);\
STACK_INC;\
} while(0)
#ifdef ONIG_DEBUG
#define STACK_BASE_CHECK(p, at) \
if ((p) < stk_base) {\
fprintf(stderr, "at %s\n", at);\
goto stack_error;\
}
#else
#define STACK_BASE_CHECK(p, at)
#endif
#define STACK_POP_ONE do {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP_ONE"); \
} while(0)
#ifdef USE_CALLOUT
#define POP_CALLOUT_CASE \
else if (stk->type == STK_CALLOUT) {\
RETRACTION_CALLOUT(stk->u.callout.func, stk->zid, stk->u.callout.num, msa->mp->callout_user_data);\
}
#else
#define POP_CALLOUT_CASE
#endif
#define STACK_POP do {\
switch (pop_level) {\
case STACK_POP_LEVEL_FREE:\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP"); \
if ((stk->type & STK_MASK_POP_USED) != 0) break;\
}\
break;\
case STACK_POP_LEVEL_MEM_START:\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP 2"); \
if ((stk->type & STK_MASK_POP_USED) != 0) break;\
else if (stk->type == STK_MEM_START) {\
mem_start_stk[stk->zid] = stk->u.mem.prev_start;\
mem_end_stk[stk->zid] = stk->u.mem.prev_end;\
}\
}\
break;\
default:\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP 3"); \
if ((stk->type & STK_MASK_POP_USED) != 0) break;\
else if ((stk->type & STK_MASK_POP_HANDLED) != 0) {\
if (stk->type == STK_MEM_START) {\
mem_start_stk[stk->zid] = stk->u.mem.prev_start;\
mem_end_stk[stk->zid] = stk->u.mem.prev_end;\
}\
else if (stk->type == STK_REPEAT_INC) {\
STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\
}\
else if (stk->type == STK_MEM_END) {\
mem_start_stk[stk->zid] = stk->u.mem.prev_start;\
mem_end_stk[stk->zid] = stk->u.mem.prev_end;\
}\
POP_CALLOUT_CASE\
}\
}\
break;\
}\
} while(0)
#define POP_TIL_BODY(aname, til_type) do {\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, (aname));\
if ((stk->type & STK_MASK_POP_HANDLED_TIL) != 0) {\
if (stk->type == (til_type)) break;\
else {\
if (stk->type == STK_MEM_START) {\
mem_start_stk[stk->zid] = stk->u.mem.prev_start;\
mem_end_stk[stk->zid] = stk->u.mem.prev_end;\
}\
else if (stk->type == STK_REPEAT_INC) {\
STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\
}\
else if (stk->type == STK_MEM_END) {\
mem_start_stk[stk->zid] = stk->u.mem.prev_start;\
mem_end_stk[stk->zid] = stk->u.mem.prev_end;\
}\
/* Don't call callout here because negation of total success by (?!..) (?<!..) */\
}\
}\
}\
} while(0)
#define STACK_POP_TIL_ALT_PREC_READ_NOT do {\
POP_TIL_BODY("STACK_POP_TIL_ALT_PREC_READ_NOT", STK_ALT_PREC_READ_NOT);\
} while(0)
#define STACK_POP_TIL_ALT_LOOK_BEHIND_NOT do {\
POP_TIL_BODY("STACK_POP_TIL_ALT_LOOK_BEHIND_NOT", STK_ALT_LOOK_BEHIND_NOT);\
} while(0)
#define STACK_EXEC_TO_VOID(k) do {\
k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_EXEC_TO_VOID"); \
if (IS_TO_VOID_TARGET(k)) {\
if (k->type == STK_TO_VOID_START) {\
k->type = STK_VOID;\
break;\
}\
k->type = STK_VOID;\
}\
}\
} while(0)
#define STACK_GET_PREC_READ_START(k) do {\
int level = 0;\
k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_GET_PREC_READ_START");\
if (IS_TO_VOID_TARGET(k)) {\
k->type = STK_VOID;\
}\
else if (k->type == STK_PREC_READ_START) {\
if (level == 0) {\
break;\
}\
level--;\
}\
else if (k->type == STK_PREC_READ_END) {\
level++;\
}\
}\
} while(0)
#define STACK_EMPTY_CHECK(isnull,sid,s) do {\
StackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_EMPTY_CHECK"); \
if (k->type == STK_EMPTY_CHECK_START) {\
if (k->zid == (sid)) {\
(isnull) = (k->u.empty_check.pstr == (s));\
break;\
}\
}\
}\
} while(0)
#define STACK_MEM_START_GET_PREV_END_ADDR(k /* STK_MEM_START*/, reg, addr) do {\
if (k->u.mem.prev_end == INVALID_STACK_INDEX) {\
(addr) = 0;\
}\
else {\
if (MEM_STATUS_AT((reg)->bt_mem_end, k->zid))\
(addr) = STACK_AT(k->u.mem.prev_end)->u.mem.pstr;\
else\
(addr) = (UChar* )k->u.mem.prev_end;\
}\
} while (0)
#ifdef USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT
#define STACK_EMPTY_CHECK_MEM(isnull,sid,s,reg) do {\
StackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_EMPTY_CHECK_MEM"); \
if (k->type == STK_EMPTY_CHECK_START) {\
if (k->zid == (sid)) {\
if (k->u.empty_check.pstr != (s)) {\
(isnull) = 0;\
break;\
}\
else {\
UChar* endp;\
int level = 0;\
(isnull) = 1;\
while (k < stk) {\
if (k->type == STK_MEM_START && level == 0) {\
STACK_MEM_START_GET_PREV_END_ADDR(k, reg, endp);\
if (endp == 0) {\
(isnull) = 0; break;\
}\
else if (STACK_AT(k->u.mem.prev_start)->u.mem.pstr != endp) {\
(isnull) = 0; break;\
}\
else if (endp != s) {\
(isnull) = -1; /* empty, but position changed */ \
}\
}\
else if (k->type == STK_PREC_READ_START) {\
level++;\
}\
else if (k->type == STK_PREC_READ_END) {\
level--;\
}\
k++;\
}\
break;\
}\
}\
}\
}\
} while(0)
#define STACK_EMPTY_CHECK_MEM_REC(isnull,sid,s,reg) do {\
int level = 0;\
StackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_EMPTY_CHECK_MEM_REC");\
if (k->type == STK_EMPTY_CHECK_START) {\
if (k->zid == (sid)) {\
if (level == 0) {\
if (k->u.empty_check.pstr != (s)) {\
(isnull) = 0;\
break;\
}\
else {\
UChar* endp;\
int prec_level = 0;\
(isnull) = 1;\
while (k < stk) {\
if (k->type == STK_MEM_START) {\
if (level == 0 && prec_level == 0) {\
STACK_MEM_START_GET_PREV_END_ADDR(k, reg, endp);\
if (endp == 0) {\
(isnull) = 0; break;\
}\
else if (STACK_AT(k->u.mem.prev_start)->u.mem.pstr != endp) { \
(isnull) = 0; break;\
}\
else if (endp != s) {\
(isnull) = -1; /* empty, but position changed */\
}\
}\
}\
else if (k->type == STK_EMPTY_CHECK_START) {\
if (k->zid == (sid)) level++;\
}\
else if (k->type == STK_EMPTY_CHECK_END) {\
if (k->zid == (sid)) level--;\
}\
else if (k->type == STK_PREC_READ_START) {\
prec_level++;\
}\
else if (k->type == STK_PREC_READ_END) {\
prec_level--;\
}\
k++;\
}\
break;\
}\
}\
else {\
level--;\
}\
}\
}\
else if (k->type == STK_EMPTY_CHECK_END) {\
if (k->zid == (sid)) level++;\
}\
}\
} while(0)
#else
#define STACK_EMPTY_CHECK_REC(isnull,id,s) do {\
int level = 0;\
StackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_EMPTY_CHECK_REC"); \
if (k->type == STK_EMPTY_CHECK_START) {\
if (k->u.empty_check.num == (id)) {\
if (level == 0) {\
(isnull) = (k->u.empty_check.pstr == (s));\
break;\
}\
}\
level--;\
}\
else if (k->type == STK_EMPTY_CHECK_END) {\
level++;\
}\
}\
} while(0)
#endif /* USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT */
#define STACK_GET_REPEAT(sid, k) do {\
int level = 0;\
k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_GET_REPEAT"); \
if (k->type == STK_REPEAT) {\
if (level == 0) {\
if (k->zid == (sid)) {\
break;\
}\
}\
}\
else if (k->type == STK_CALL_FRAME) level--;\
else if (k->type == STK_RETURN) level++;\
}\
} while(0)
#define STACK_RETURN(addr) do {\
int level = 0;\
StackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_RETURN"); \
if (k->type == STK_CALL_FRAME) {\
if (level == 0) {\
(addr) = k->u.call_frame.ret_addr;\
break;\
}\
else level--;\
}\
else if (k->type == STK_RETURN)\
level++;\
}\
} while(0)
#define STRING_CMP(s1,s2,len) do {\
while (len-- > 0) {\
if (*s1++ != *s2++) goto fail;\
}\
} while(0)
#define STRING_CMP_IC(case_fold_flag,s1,ps2,len) do {\
if (string_cmp_ic(encode, case_fold_flag, s1, ps2, len) == 0) \
goto fail; \
} while(0)
static int string_cmp_ic(OnigEncoding enc, int case_fold_flag,
UChar* s1, UChar** ps2, int mblen)
{
UChar buf1[ONIGENC_MBC_CASE_FOLD_MAXLEN];
UChar buf2[ONIGENC_MBC_CASE_FOLD_MAXLEN];
UChar *p1, *p2, *end1, *s2, *end2;
int len1, len2;
s2 = *ps2;
end1 = s1 + mblen;
end2 = s2 + mblen;
while (s1 < end1) {
len1 = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &s1, end1, buf1);
len2 = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &s2, end2, buf2);
if (len1 != len2) return 0;
p1 = buf1;
p2 = buf2;
while (len1-- > 0) {
if (*p1 != *p2) return 0;
p1++;
p2++;
}
}
*ps2 = s2;
return 1;
}
#define STRING_CMP_VALUE(s1,s2,len,is_fail) do {\
is_fail = 0;\
while (len-- > 0) {\
if (*s1++ != *s2++) {\
is_fail = 1; break;\
}\
}\
} while(0)
#define STRING_CMP_VALUE_IC(case_fold_flag,s1,ps2,len,is_fail) do {\
if (string_cmp_ic(encode, case_fold_flag, s1, ps2, len) == 0) \
is_fail = 1; \
else \
is_fail = 0; \
} while(0)
#define IS_EMPTY_STR (str == end)
#define ON_STR_BEGIN(s) ((s) == str)
#define ON_STR_END(s) ((s) == end)
#define DATA_ENSURE_CHECK1 (s < right_range)
#define DATA_ENSURE_CHECK(n) (s + (n) <= right_range)
#define DATA_ENSURE(n) if (s + (n) > right_range) goto fail
#define INIT_RIGHT_RANGE right_range = (UChar* )in_right_range
#ifdef USE_CAPTURE_HISTORY
static int
make_capture_history_tree(OnigCaptureTreeNode* node, StackType** kp,
StackType* stk_top, UChar* str, regex_t* reg)
{
int n, r;
OnigCaptureTreeNode* child;
StackType* k = *kp;
while (k < stk_top) {
if (k->type == STK_MEM_START) {
n = k->zid;
if (n <= ONIG_MAX_CAPTURE_HISTORY_GROUP &&
MEM_STATUS_AT(reg->capture_history, n) != 0) {
child = history_node_new();
CHECK_NULL_RETURN_MEMERR(child);
child->group = n;
child->beg = (int )(k->u.mem.pstr - str);
r = history_tree_add_child(node, child);
if (r != 0) return r;
*kp = (k + 1);
r = make_capture_history_tree(child, kp, stk_top, str, reg);
if (r != 0) return r;
k = *kp;
child->end = (int )(k->u.mem.pstr - str);
}
}
else if (k->type == STK_MEM_END) {
if (k->zid == node->group) {
node->end = (int )(k->u.mem.pstr - str);
*kp = k;
return 0;
}
}
k++;
}
return 1; /* 1: root node ending. */
}
#endif
#ifdef USE_BACKREF_WITH_LEVEL
static int mem_is_in_memp(int mem, int num, MemNumType* memp)
{
int i;
for (i = 0; i < num; i++) {
if (mem == (int )memp[i]) return 1;
}
return 0;
}
static int
backref_match_at_nested_level(regex_t* reg,
StackType* top, StackType* stk_base,
int ignore_case, int case_fold_flag,
int nest, int mem_num, MemNumType* memp,
UChar** s, const UChar* send)
{
UChar *ss, *p, *pstart, *pend = NULL_UCHARP;
int level;
StackType* k;
level = 0;
k = top;
k--;
while (k >= stk_base) {
if (k->type == STK_CALL_FRAME) {
level--;
}
else if (k->type == STK_RETURN) {
level++;
}
else if (level == nest) {
if (k->type == STK_MEM_START) {
if (mem_is_in_memp(k->zid, mem_num, memp)) {
pstart = k->u.mem.pstr;
if (IS_NOT_NULL(pend)) {
if (pend - pstart > send - *s) return 0; /* or goto next_mem; */
p = pstart;
ss = *s;
if (ignore_case != 0) {
if (string_cmp_ic(reg->enc, case_fold_flag,
pstart, &ss, (int )(pend - pstart)) == 0)
return 0; /* or goto next_mem; */
}
else {
while (p < pend) {
if (*p++ != *ss++) return 0; /* or goto next_mem; */
}
}
*s = ss;
return 1;
}
}
}
else if (k->type == STK_MEM_END) {
if (mem_is_in_memp(k->zid, mem_num, memp)) {
pend = k->u.mem.pstr;
}
}
}
k--;
}
return 0;
}
static int
backref_check_at_nested_level(regex_t* reg,
StackType* top, StackType* stk_base,
int nest, int mem_num, MemNumType* memp)
{
int level;
StackType* k;
level = 0;
k = top;
k--;
while (k >= stk_base) {
if (k->type == STK_CALL_FRAME) {
level--;
}
else if (k->type == STK_RETURN) {
level++;
}
else if (level == nest) {
if (k->type == STK_MEM_END) {
if (mem_is_in_memp(k->zid, mem_num, memp)) {
return 1;
}
}
}
k--;
}
return 0;
}
#endif /* USE_BACKREF_WITH_LEVEL */
#ifdef ONIG_DEBUG_STATISTICS
#define USE_TIMEOFDAY
#ifdef USE_TIMEOFDAY
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
static struct timeval ts, te;
#define GETTIME(t) gettimeofday(&(t), (struct timezone* )0)
#define TIMEDIFF(te,ts) (((te).tv_usec - (ts).tv_usec) + \
(((te).tv_sec - (ts).tv_sec)*1000000))
#else
#ifdef HAVE_SYS_TIMES_H
#include <sys/times.h>
#endif
static struct tms ts, te;
#define GETTIME(t) times(&(t))
#define TIMEDIFF(te,ts) ((te).tms_utime - (ts).tms_utime)
#endif
static int OpCounter[256];
static int OpPrevCounter[256];
static unsigned long OpTime[256];
static int OpCurr = OP_FINISH;
static int OpPrevTarget = OP_FAIL;
static int MaxStackDepth = 0;
#define SOP_IN(opcode) do {\
if (opcode == OpPrevTarget) OpPrevCounter[OpCurr]++;\
OpCurr = opcode;\
OpCounter[opcode]++;\
GETTIME(ts);\
} while(0)
#define SOP_OUT do {\
GETTIME(te);\
OpTime[OpCurr] += TIMEDIFF(te, ts);\
} while(0)
extern void
onig_statistics_init(void)
{
int i;
for (i = 0; i < 256; i++) {
OpCounter[i] = OpPrevCounter[i] = 0; OpTime[i] = 0;
}
MaxStackDepth = 0;
}
extern int
onig_print_statistics(FILE* f)
{
int r;
int i;
r = fprintf(f, " count prev time\n");
if (r < 0) return -1;
for (i = 0; OpInfo[i].opcode >= 0; i++) {
r = fprintf(f, "%8d: %8d: %10ld: %s\n",
OpCounter[i], OpPrevCounter[i], OpTime[i], OpInfo[i].name);
if (r < 0) return -1;
}
r = fprintf(f, "\nmax stack depth: %d\n", MaxStackDepth);
if (r < 0) return -1;
return 0;
}
#define STACK_INC do {\
stk++;\
if (stk - stk_base > MaxStackDepth) \
MaxStackDepth = stk - stk_base;\
} while(0)
#else
#define STACK_INC stk++
#define SOP_IN(opcode)
#define SOP_OUT
#endif
/* matching region of POSIX API */
typedef int regoff_t;
typedef struct {
regoff_t rm_so;
regoff_t rm_eo;
} posix_regmatch_t;
#ifdef USE_THREADED_CODE
#define BYTECODE_INTERPRETER_START GOTO_OP;
#define BYTECODE_INTERPRETER_END
#define CASE_OP(x) L_##x: SOP_IN(OP_##x); sbegin = s; MATCH_DEBUG_OUT(0)
#define DEFAULT_OP /* L_DEFAULT: */
#define NEXT_OP sprev = sbegin; JUMP_OP
#define JUMP_OP GOTO_OP
#ifdef USE_DIRECT_THREADED_CODE
#define GOTO_OP goto *(p->opaddr)
#else
#define GOTO_OP goto *opcode_to_label[p->opcode]
#endif
#define BREAK_OP /* Nothing */
#else
#define BYTECODE_INTERPRETER_START \
while (1) {\
MATCH_DEBUG_OUT(0)\
sbegin = s;\
switch (p->opcode) {
#define BYTECODE_INTERPRETER_END } sprev = sbegin; }
#define CASE_OP(x) case OP_##x: SOP_IN(OP_##x);
#define DEFAULT_OP default:
#define NEXT_OP break
#define JUMP_OP GOTO_OP
#define GOTO_OP continue; break
#define BREAK_OP break
#endif /* USE_THREADED_CODE */
#define INC_OP p++
#define NEXT_OUT SOP_OUT; NEXT_OP
#define JUMP_OUT SOP_OUT; JUMP_OP
#define BREAK_OUT SOP_OUT; BREAK_OP
#define CHECK_INTERRUPT_JUMP_OUT SOP_OUT; CHECK_INTERRUPT_IN_MATCH; JUMP_OP
#ifdef ONIG_DEBUG_MATCH
#define MATCH_DEBUG_OUT(offset) do {\
Operation *xp;\
UChar *q, *bp, buf[50];\
int len, spos;\
spos = IS_NOT_NULL(s) ? (int )(s - str) : -1;\
xp = p - (offset);\
fprintf(stderr, "%7u: %7ld: %4d> \"",\
counter, GET_STACK_INDEX(stk), spos);\
counter++;\
bp = buf;\
if (IS_NOT_NULL(s)) {\
for (i = 0, q = s; i < 7 && q < end; i++) {\
len = enclen(encode, q);\
while (len-- > 0) *bp++ = *q++;\
}\
if (q < end) { xmemcpy(bp, "...\"", 4); bp += 4; }\
else { xmemcpy(bp, "\"", 1); bp += 1; }\
}\
else {\
xmemcpy(bp, "\"", 1); bp += 1;\
}\
*bp = 0;\
fputs((char* )buf, stderr);\
for (i = 0; i < 20 - (bp - buf); i++) fputc(' ', stderr);\
if (xp == FinishCode)\
fprintf(stderr, "----: finish");\
else {\
fprintf(stderr, "%4d: ", (int )(xp - reg->ops));\
print_compiled_byte_code(stderr, reg, (int )(xp - reg->ops), reg->ops, encode);\
}\
fprintf(stderr, "\n");\
} while(0);
#else
#define MATCH_DEBUG_OUT(offset)
#endif
/* match data(str - end) from position (sstart). */
/* if sstart == str then set sprev to NULL. */
static int
match_at(regex_t* reg, const UChar* str, const UChar* end,
const UChar* in_right_range, const UChar* sstart, UChar* sprev,
MatchArg* msa)
{
#if defined(USE_DIRECT_THREADED_CODE)
static Operation FinishCode[] = { { .opaddr=&&L_FINISH } };
#else
static Operation FinishCode[] = { { OP_FINISH } };
#endif
#ifdef USE_THREADED_CODE
static const void *opcode_to_label[] = {
&&L_FINISH,
&&L_END,
&&L_EXACT1,
&&L_EXACT2,
&&L_EXACT3,
&&L_EXACT4,
&&L_EXACT5,
&&L_EXACTN,
&&L_EXACTMB2N1,
&&L_EXACTMB2N2,
&&L_EXACTMB2N3,
&&L_EXACTMB2N,
&&L_EXACTMB3N,
&&L_EXACTMBN,
&&L_EXACT1_IC,
&&L_EXACTN_IC,
&&L_CCLASS,
&&L_CCLASS_MB,
&&L_CCLASS_MIX,
&&L_CCLASS_NOT,
&&L_CCLASS_MB_NOT,
&&L_CCLASS_MIX_NOT,
&&L_ANYCHAR,
&&L_ANYCHAR_ML,
&&L_ANYCHAR_STAR,
&&L_ANYCHAR_ML_STAR,
&&L_ANYCHAR_STAR_PEEK_NEXT,
&&L_ANYCHAR_ML_STAR_PEEK_NEXT,
&&L_WORD,
&&L_WORD_ASCII,
&&L_NO_WORD,
&&L_NO_WORD_ASCII,
&&L_WORD_BOUNDARY,
&&L_NO_WORD_BOUNDARY,
&&L_WORD_BEGIN,
&&L_WORD_END,
&&L_TEXT_SEGMENT_BOUNDARY,
&&L_BEGIN_BUF,
&&L_END_BUF,
&&L_BEGIN_LINE,
&&L_END_LINE,
&&L_SEMI_END_BUF,
&&L_BEGIN_POSITION,
&&L_BACKREF1,
&&L_BACKREF2,
&&L_BACKREF_N,
&&L_BACKREF_N_IC,
&&L_BACKREF_MULTI,
&&L_BACKREF_MULTI_IC,
&&L_BACKREF_WITH_LEVEL,
&&L_BACKREF_WITH_LEVEL_IC,
&&L_BACKREF_CHECK,
&&L_BACKREF_CHECK_WITH_LEVEL,
&&L_MEMORY_START,
&&L_MEMORY_START_PUSH,
&&L_MEMORY_END_PUSH,
&&L_MEMORY_END_PUSH_REC,
&&L_MEMORY_END,
&&L_MEMORY_END_REC,
&&L_FAIL,
&&L_JUMP,
&&L_PUSH,
&&L_PUSH_SUPER,
&&L_POP_OUT,
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
&&L_PUSH_OR_JUMP_EXACT1,
#endif
&&L_PUSH_IF_PEEK_NEXT,
&&L_REPEAT,
&&L_REPEAT_NG,
&&L_REPEAT_INC,
&&L_REPEAT_INC_NG,
&&L_REPEAT_INC_SG,
&&L_REPEAT_INC_NG_SG,
&&L_EMPTY_CHECK_START,
&&L_EMPTY_CHECK_END,
&&L_EMPTY_CHECK_END_MEMST,
&&L_EMPTY_CHECK_END_MEMST_PUSH,
&&L_PREC_READ_START,
&&L_PREC_READ_END,
&&L_PREC_READ_NOT_START,
&&L_PREC_READ_NOT_END,
&&L_ATOMIC_START,
&&L_ATOMIC_END,
&&L_LOOK_BEHIND,
&&L_LOOK_BEHIND_NOT_START,
&&L_LOOK_BEHIND_NOT_END,
&&L_CALL,
&&L_RETURN,
&&L_PUSH_SAVE_VAL,
&&L_UPDATE_VAR,
#ifdef USE_CALLOUT
&&L_CALLOUT_CONTENTS,
&&L_CALLOUT_NAME,
#endif
};
#endif
int i, n, num_mem, best_len, pop_level;
LengthType tlen, tlen2;
MemNumType mem;
RelAddrType addr;
UChar *s, *q, *ps, *sbegin;
UChar *right_range;
int is_alloca;
char *alloc_base;
StackType *stk_base, *stk, *stk_end;
StackType *stkp; /* used as any purpose. */
StackIndex si;
StackIndex *repeat_stk;
StackIndex *mem_start_stk, *mem_end_stk;
UChar* keep;
#ifdef USE_RETRY_LIMIT_IN_MATCH
unsigned long retry_limit_in_match;
unsigned long retry_in_match_counter;
#endif
#ifdef USE_CALLOUT
int of;
#endif
Operation* p = reg->ops;
OnigOptionType option = reg->options;
OnigEncoding encode = reg->enc;
OnigCaseFoldType case_fold_flag = reg->case_fold_flag;
#ifdef ONIG_DEBUG_MATCH
static unsigned int counter = 1;
#endif
#ifdef USE_DIRECT_THREADED_CODE
if (IS_NULL(msa)) {
for (i = 0; i < reg->ops_used; i++) {
const void* addr;
addr = opcode_to_label[reg->ocs[i]];
p->opaddr = addr;
p++;
}
return ONIG_NORMAL;
}
#endif
#ifdef USE_CALLOUT
msa->mp->match_at_call_counter++;
#endif
#ifdef USE_RETRY_LIMIT_IN_MATCH
retry_limit_in_match = msa->retry_limit_in_match;
#endif
pop_level = reg->stack_pop_level;
num_mem = reg->num_mem;
STACK_INIT(INIT_MATCH_STACK_SIZE);
UPDATE_FOR_STACK_REALLOC;
for (i = 1; i <= num_mem; i++) {
mem_start_stk[i] = mem_end_stk[i] = INVALID_STACK_INDEX;
}
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "match_at: str: %p, end: %p, start: %p, sprev: %p\n",
str, end, sstart, sprev);
fprintf(stderr, "size: %d, start offset: %d\n",
(int )(end - str), (int )(sstart - str));
#endif
best_len = ONIG_MISMATCH;
keep = s = (UChar* )sstart;
STACK_PUSH_BOTTOM(STK_ALT, FinishCode); /* bottom stack */
INIT_RIGHT_RANGE;
#ifdef USE_RETRY_LIMIT_IN_MATCH
retry_in_match_counter = 0;
#endif
BYTECODE_INTERPRETER_START {
CASE_OP(END)
n = (int )(s - sstart);
if (n > best_len) {
OnigRegion* region;
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
if (IS_FIND_LONGEST(option)) {
if (n > msa->best_len) {
msa->best_len = n;
msa->best_s = (UChar* )sstart;
}
else
goto end_best_len;
}
#endif
best_len = n;
region = msa->region;
if (region) {
if (keep > s) keep = s;
#ifdef USE_POSIX_API_REGION_OPTION
if (IS_POSIX_REGION(msa->options)) {
posix_regmatch_t* rmt = (posix_regmatch_t* )region;
rmt[0].rm_so = (regoff_t )(keep - str);
rmt[0].rm_eo = (regoff_t )(s - str);
for (i = 1; i <= num_mem; i++) {
if (mem_end_stk[i] != INVALID_STACK_INDEX) {
if (MEM_STATUS_AT(reg->bt_mem_start, i))
rmt[i].rm_so = (regoff_t )(STACK_AT(mem_start_stk[i])->u.mem.pstr - str);
else
rmt[i].rm_so = (regoff_t )((UChar* )((void* )(mem_start_stk[i])) - str);
rmt[i].rm_eo = (regoff_t )((MEM_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[i]))
- str);
}
else {
rmt[i].rm_so = rmt[i].rm_eo = ONIG_REGION_NOTPOS;
}
}
}
else {
#endif /* USE_POSIX_API_REGION_OPTION */
region->beg[0] = (int )(keep - str);
region->end[0] = (int )(s - str);
for (i = 1; i <= num_mem; i++) {
if (mem_end_stk[i] != INVALID_STACK_INDEX) {
if (MEM_STATUS_AT(reg->bt_mem_start, i))
region->beg[i] = (int )(STACK_AT(mem_start_stk[i])->u.mem.pstr - str);
else
region->beg[i] = (int )((UChar* )((void* )mem_start_stk[i]) - str);
region->end[i] = (int )((MEM_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[i])) - str);
}
else {
region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS;
}
}
#ifdef USE_CAPTURE_HISTORY
if (reg->capture_history != 0) {
int r;
OnigCaptureTreeNode* node;
if (IS_NULL(region->history_root)) {
region->history_root = node = history_node_new();
CHECK_NULL_RETURN_MEMERR(node);
}
else {
node = region->history_root;
history_tree_clear(node);
}
node->group = 0;
node->beg = (int )(keep - str);
node->end = (int )(s - str);
stkp = stk_base;
r = make_capture_history_tree(region->history_root, &stkp,
stk, (UChar* )str, reg);
if (r < 0) {
best_len = r; /* error code */
goto finish;
}
}
#endif /* USE_CAPTURE_HISTORY */
#ifdef USE_POSIX_API_REGION_OPTION
} /* else IS_POSIX_REGION() */
#endif
} /* if (region) */
} /* n > best_len */
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
end_best_len:
#endif
SOP_OUT;
if (IS_FIND_CONDITION(option)) {
if (IS_FIND_NOT_EMPTY(option) && s == sstart) {
best_len = ONIG_MISMATCH;
goto fail; /* for retry */
}
if (IS_FIND_LONGEST(option) && DATA_ENSURE_CHECK1) {
goto fail; /* for retry */
}
}
/* default behavior: return first-matching result. */
goto finish;
CASE_OP(EXACT1)
DATA_ENSURE(1);
ps = p->exact.s;
if (*ps != *s) goto fail;
s++;
INC_OP;
NEXT_OUT;
CASE_OP(EXACT1_IC)
{
int len;
UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
DATA_ENSURE(1);
len = ONIGENC_MBC_CASE_FOLD(encode,
/* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */
case_fold_flag,
&s, end, lowbuf);
DATA_ENSURE(0);
q = lowbuf;
ps = p->exact.s;
while (len-- > 0) {
if (*ps != *q) goto fail;
ps++; q++;
}
}
INC_OP;
NEXT_OUT;
CASE_OP(EXACT2)
DATA_ENSURE(2);
ps = p->exact.s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
sprev = s;
s++;
INC_OP;
JUMP_OUT;
CASE_OP(EXACT3)
DATA_ENSURE(3);
ps = p->exact.s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
sprev = s;
s++;
INC_OP;
JUMP_OUT;
CASE_OP(EXACT4)
DATA_ENSURE(4);
ps = p->exact.s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
sprev = s;
s++;
INC_OP;
JUMP_OUT;
CASE_OP(EXACT5)
DATA_ENSURE(5);
ps = p->exact.s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
sprev = s;
s++;
INC_OP;
JUMP_OUT;
CASE_OP(EXACTN)
tlen = p->exact_n.n;
DATA_ENSURE(tlen);
ps = p->exact_n.s;
while (tlen-- > 0) {
if (*ps++ != *s++) goto fail;
}
sprev = s - 1;
INC_OP;
JUMP_OUT;
CASE_OP(EXACTN_IC)
{
int len;
UChar *q, *endp, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
tlen = p->exact_n.n;
ps = p->exact_n.s;
endp = ps + tlen;
while (ps < endp) {
sprev = s;
DATA_ENSURE(1);
len = ONIGENC_MBC_CASE_FOLD(encode,
/* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */
case_fold_flag,
&s, end, lowbuf);
DATA_ENSURE(0);
q = lowbuf;
while (len-- > 0) {
if (*ps != *q) goto fail;
ps++; q++;
}
}
}
INC_OP;
JUMP_OUT;
CASE_OP(EXACTMB2N1)
DATA_ENSURE(2);
ps = p->exact.s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
s++;
INC_OP;
NEXT_OUT;
CASE_OP(EXACTMB2N2)
DATA_ENSURE(4);
ps = p->exact.s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
sprev = s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
s++;
INC_OP;
JUMP_OUT;
CASE_OP(EXACTMB2N3)
DATA_ENSURE(6);
ps = p->exact.s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
sprev = s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
INC_OP;
JUMP_OUT;
CASE_OP(EXACTMB2N)
tlen = p->exact_n.n;
DATA_ENSURE(tlen * 2);
ps = p->exact_n.s;
while (tlen-- > 0) {
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
}
sprev = s - 2;
INC_OP;
JUMP_OUT;
CASE_OP(EXACTMB3N)
tlen = p->exact_n.n;
DATA_ENSURE(tlen * 3);
ps = p->exact_n.s;
while (tlen-- > 0) {
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
}
sprev = s - 3;
INC_OP;
JUMP_OUT;
CASE_OP(EXACTMBN)
tlen = p->exact_len_n.len; /* mb byte len */
tlen2 = p->exact_len_n.n; /* number of chars */
tlen2 *= tlen;
DATA_ENSURE(tlen2);
ps = p->exact_len_n.s;
while (tlen2-- > 0) {
if (*ps != *s) goto fail;
ps++; s++;
}
sprev = s - tlen;
INC_OP;
JUMP_OUT;
CASE_OP(CCLASS)
DATA_ENSURE(1);
if (BITSET_AT(p->cclass.bsp, *s) == 0) goto fail;
s++;
INC_OP;
NEXT_OUT;
CASE_OP(CCLASS_MB)
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_HEAD(encode, s)) goto fail;
cclass_mb:
{
OnigCodePoint code;
UChar *ss;
int mb_len;
DATA_ENSURE(1);
mb_len = enclen(encode, s);
DATA_ENSURE(mb_len);
ss = s;
s += mb_len;
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
if (! onig_is_in_code_range(p->cclass_mb.mb, code)) goto fail;
}
INC_OP;
NEXT_OUT;
CASE_OP(CCLASS_MIX)
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_HEAD(encode, s)) {
goto cclass_mb;
}
else {
if (BITSET_AT(p->cclass_mix.bsp, *s) == 0)
goto fail;
s++;
}
INC_OP;
NEXT_OUT;
CASE_OP(CCLASS_NOT)
DATA_ENSURE(1);
if (BITSET_AT(p->cclass.bsp, *s) != 0) goto fail;
s += enclen(encode, s);
INC_OP;
NEXT_OUT;
CASE_OP(CCLASS_MB_NOT)
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_HEAD(encode, s)) {
s++;
goto cc_mb_not_success;
}
cclass_mb_not:
{
OnigCodePoint code;
UChar *ss;
int mb_len = enclen(encode, s);
if (! DATA_ENSURE_CHECK(mb_len)) {
DATA_ENSURE(1);
s = (UChar* )end;
goto cc_mb_not_success;
}
ss = s;
s += mb_len;
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
if (onig_is_in_code_range(p->cclass_mb.mb, code)) goto fail;
}
cc_mb_not_success:
INC_OP;
NEXT_OUT;
CASE_OP(CCLASS_MIX_NOT)
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_HEAD(encode, s)) {
goto cclass_mb_not;
}
else {
if (BITSET_AT(p->cclass_mix.bsp, *s) != 0)
goto fail;
s++;
}
INC_OP;
NEXT_OUT;
CASE_OP(ANYCHAR)
DATA_ENSURE(1);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
s += n;
INC_OP;
NEXT_OUT;
CASE_OP(ANYCHAR_ML)
DATA_ENSURE(1);
n = enclen(encode, s);
DATA_ENSURE(n);
s += n;
INC_OP;
NEXT_OUT;
CASE_OP(ANYCHAR_STAR)
INC_OP;
while (DATA_ENSURE_CHECK1) {
STACK_PUSH_ALT(p, s, sprev);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
JUMP_OUT;
CASE_OP(ANYCHAR_ML_STAR)
INC_OP;
while (DATA_ENSURE_CHECK1) {
STACK_PUSH_ALT(p, s, sprev);
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
JUMP_OUT;
CASE_OP(ANYCHAR_STAR_PEEK_NEXT)
{
UChar c;
c = p->anychar_star_peek_next.c;
INC_OP;
while (DATA_ENSURE_CHECK1) {
if (c == *s) {
STACK_PUSH_ALT(p, s, sprev);
}
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
}
NEXT_OUT;
CASE_OP(ANYCHAR_ML_STAR_PEEK_NEXT)
{
UChar c;
c = p->anychar_star_peek_next.c;
INC_OP;
while (DATA_ENSURE_CHECK1) {
if (c == *s) {
STACK_PUSH_ALT(p, s, sprev);
}
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
}
NEXT_OUT;
CASE_OP(WORD)
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
s += enclen(encode, s);
INC_OP;
NEXT_OUT;
CASE_OP(WORD_ASCII)
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_WORD_ASCII(encode, s, end))
goto fail;
s += enclen(encode, s);
INC_OP;
NEXT_OUT;
CASE_OP(NO_WORD)
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
s += enclen(encode, s);
INC_OP;
NEXT_OUT;
CASE_OP(NO_WORD_ASCII)
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_WORD_ASCII(encode, s, end))
goto fail;
s += enclen(encode, s);
INC_OP;
NEXT_OUT;
CASE_OP(WORD_BOUNDARY)
{
ModeType mode;
mode = p->word_boundary.mode;
if (ON_STR_BEGIN(s)) {
DATA_ENSURE(1);
if (! IS_MBC_WORD_ASCII_MODE(encode, s, end, mode))
goto fail;
}
else if (ON_STR_END(s)) {
if (! IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode))
goto fail;
}
else {
if (IS_MBC_WORD_ASCII_MODE(encode, s, end, mode)
== IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode))
goto fail;
}
}
INC_OP;
JUMP_OUT;
CASE_OP(NO_WORD_BOUNDARY)
{
ModeType mode;
mode = p->word_boundary.mode;
if (ON_STR_BEGIN(s)) {
if (DATA_ENSURE_CHECK1 && IS_MBC_WORD_ASCII_MODE(encode, s, end, mode))
goto fail;
}
else if (ON_STR_END(s)) {
if (IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode))
goto fail;
}
else {
if (IS_MBC_WORD_ASCII_MODE(encode, s, end, mode)
!= IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode))
goto fail;
}
}
INC_OP;
JUMP_OUT;
#ifdef USE_WORD_BEGIN_END
CASE_OP(WORD_BEGIN)
{
ModeType mode;
mode = p->word_boundary.mode;
if (DATA_ENSURE_CHECK1 && IS_MBC_WORD_ASCII_MODE(encode, s, end, mode)) {
if (ON_STR_BEGIN(s) || !IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode)) {
INC_OP;
JUMP_OUT;
}
}
}
goto fail;
CASE_OP(WORD_END)
{
ModeType mode;
mode = p->word_boundary.mode;
if (!ON_STR_BEGIN(s) && IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode)) {
if (ON_STR_END(s) || ! IS_MBC_WORD_ASCII_MODE(encode, s, end, mode)) {
INC_OP;
JUMP_OUT;
}
}
}
goto fail;
#endif
CASE_OP(TEXT_SEGMENT_BOUNDARY)
{
int is_break;
switch (p->text_segment_boundary.type) {
case EXTENDED_GRAPHEME_CLUSTER_BOUNDARY:
is_break = onigenc_egcb_is_break_position(encode, s, sprev, str, end);
break;
#ifdef USE_UNICODE_WORD_BREAK
case WORD_BOUNDARY:
is_break = onigenc_wb_is_break_position(encode, s, sprev, str, end);
break;
#endif
default:
goto bytecode_error;
break;
}
if (p->text_segment_boundary.not != 0)
is_break = ! is_break;
if (is_break != 0) {
INC_OP;
JUMP_OUT;
}
else {
goto fail;
}
}
CASE_OP(BEGIN_BUF)
if (! ON_STR_BEGIN(s)) goto fail;
INC_OP;
JUMP_OUT;
CASE_OP(END_BUF)
if (! ON_STR_END(s)) goto fail;
INC_OP;
JUMP_OUT;
CASE_OP(BEGIN_LINE)
if (ON_STR_BEGIN(s)) {
if (IS_NOTBOL(msa->options)) goto fail;
INC_OP;
JUMP_OUT;
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, sprev, end) && !ON_STR_END(s)) {
INC_OP;
JUMP_OUT;
}
goto fail;
CASE_OP(END_LINE)
if (ON_STR_END(s)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) {
#endif
if (IS_NOTEOL(msa->options)) goto fail;
INC_OP;
JUMP_OUT;
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
}
#endif
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) {
INC_OP;
JUMP_OUT;
}
#ifdef USE_CRNL_AS_LINE_TERMINATOR
else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) {
INC_OP;
JUMP_OUT;
}
#endif
goto fail;
CASE_OP(SEMI_END_BUF)
if (ON_STR_END(s)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) {
#endif
if (IS_NOTEOL(msa->options)) goto fail;
INC_OP;
JUMP_OUT;
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
}
#endif
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end) &&
ON_STR_END(s + enclen(encode, s))) {
INC_OP;
JUMP_OUT;
}
#ifdef USE_CRNL_AS_LINE_TERMINATOR
else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) {
UChar* ss = s + enclen(encode, s);
ss += enclen(encode, ss);
if (ON_STR_END(ss)) {
INC_OP;
JUMP_OUT;
}
}
#endif
goto fail;
CASE_OP(BEGIN_POSITION)
if (s != msa->start)
goto fail;
INC_OP;
JUMP_OUT;
CASE_OP(MEMORY_START_PUSH)
mem = p->memory_start.num;
STACK_PUSH_MEM_START(mem, s);
INC_OP;
JUMP_OUT;
CASE_OP(MEMORY_START)
mem = p->memory_start.num;
mem_start_stk[mem] = (StackIndex )((void* )s);
INC_OP;
JUMP_OUT;
CASE_OP(MEMORY_END_PUSH)
mem = p->memory_end.num;
STACK_PUSH_MEM_END(mem, s);
INC_OP;
JUMP_OUT;
CASE_OP(MEMORY_END)
mem = p->memory_end.num;
mem_end_stk[mem] = (StackIndex )((void* )s);
INC_OP;
JUMP_OUT;
#ifdef USE_CALL
CASE_OP(MEMORY_END_PUSH_REC)
mem = p->memory_end.num;
STACK_GET_MEM_START(mem, stkp); /* should be before push mem-end. */
si = GET_STACK_INDEX(stkp);
STACK_PUSH_MEM_END(mem, s);
mem_start_stk[mem] = si;
INC_OP;
JUMP_OUT;
CASE_OP(MEMORY_END_REC)
mem = p->memory_end.num;
mem_end_stk[mem] = (StackIndex )((void* )s);
STACK_GET_MEM_START(mem, stkp);
if (MEM_STATUS_AT(reg->bt_mem_start, mem))
mem_start_stk[mem] = GET_STACK_INDEX(stkp);
else
mem_start_stk[mem] = (StackIndex )((void* )stkp->u.mem.pstr);
STACK_PUSH_MEM_END_MARK(mem);
INC_OP;
JUMP_OUT;
#endif
CASE_OP(BACKREF1)
mem = 1;
goto backref;
CASE_OP(BACKREF2)
mem = 2;
goto backref;
CASE_OP(BACKREF_N)
mem = p->backref_n.n1;
backref:
{
int len;
UChar *pstart, *pend;
if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (MEM_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (MEM_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = (int )(pend - pstart);
if (n != 0) {
DATA_ENSURE(n);
sprev = s;
STRING_CMP(s, pstart, n);
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
}
}
INC_OP;
JUMP_OUT;
CASE_OP(BACKREF_N_IC)
mem = p->backref_n.n1;
{
int len;
UChar *pstart, *pend;
if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (MEM_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (MEM_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = (int )(pend - pstart);
if (n != 0) {
DATA_ENSURE(n);
sprev = s;
STRING_CMP_IC(case_fold_flag, pstart, &s, n);
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
}
}
INC_OP;
JUMP_OUT;
CASE_OP(BACKREF_MULTI)
{
int len, is_fail;
UChar *pstart, *pend, *swork;
tlen = p->backref_general.num;
for (i = 0; i < tlen; i++) {
mem = tlen == 1 ? p->backref_general.n1 : p->backref_general.ns[i];
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
if (MEM_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (MEM_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = (int )(pend - pstart);
if (n != 0) {
DATA_ENSURE(n);
sprev = s;
swork = s;
STRING_CMP_VALUE(swork, pstart, n, is_fail);
if (is_fail) continue;
s = swork;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
}
break; /* success */
}
if (i == tlen) goto fail;
}
INC_OP;
JUMP_OUT;
CASE_OP(BACKREF_MULTI_IC)
{
int len, is_fail;
UChar *pstart, *pend, *swork;
tlen = p->backref_general.num;
for (i = 0; i < tlen; i++) {
mem = tlen == 1 ? p->backref_general.n1 : p->backref_general.ns[i];
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
if (MEM_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (MEM_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = (int )(pend - pstart);
if (n != 0) {
DATA_ENSURE(n);
sprev = s;
swork = s;
STRING_CMP_VALUE_IC(case_fold_flag, pstart, &swork, n, is_fail);
if (is_fail) continue;
s = swork;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
}
break; /* success */
}
if (i == tlen) goto fail;
}
INC_OP;
JUMP_OUT;
#ifdef USE_BACKREF_WITH_LEVEL
CASE_OP(BACKREF_WITH_LEVEL_IC)
n = 1; /* ignore case */
goto backref_with_level;
CASE_OP(BACKREF_WITH_LEVEL)
{
int len;
int level;
MemNumType* mems;
UChar* ssave;
n = 0;
backref_with_level:
level = p->backref_general.nest_level;
tlen = p->backref_general.num;
mems = tlen == 1 ? &(p->backref_general.n1) : p->backref_general.ns;
ssave = s;
if (backref_match_at_nested_level(reg, stk, stk_base, n,
case_fold_flag, level, (int )tlen, mems, &s, end)) {
if (ssave != s) {
sprev = ssave;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
}
}
else
goto fail;
}
INC_OP;
JUMP_OUT;
#endif
CASE_OP(BACKREF_CHECK)
{
MemNumType* mems;
tlen = p->backref_general.num;
mems = tlen == 1 ? &(p->backref_general.n1) : p->backref_general.ns;
for (i = 0; i < tlen; i++) {
mem = mems[i];
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
break; /* success */
}
if (i == tlen) goto fail;
}
INC_OP;
JUMP_OUT;
#ifdef USE_BACKREF_WITH_LEVEL
CASE_OP(BACKREF_CHECK_WITH_LEVEL)
{
LengthType level;
MemNumType* mems;
level = p->backref_general.nest_level;
tlen = p->backref_general.num;
mems = tlen == 1 ? &(p->backref_general.n1) : p->backref_general.ns;
if (backref_check_at_nested_level(reg, stk, stk_base,
(int )level, (int )tlen, mems) == 0)
goto fail;
}
INC_OP;
JUMP_OUT;
#endif
CASE_OP(EMPTY_CHECK_START)
mem = p->empty_check_start.mem; /* mem: null check id */
STACK_PUSH_EMPTY_CHECK_START(mem, s);
INC_OP;
JUMP_OUT;
CASE_OP(EMPTY_CHECK_END)
{
int is_empty;
mem = p->empty_check_end.mem; /* mem: null check id */
STACK_EMPTY_CHECK(is_empty, mem, s);
INC_OP;
if (is_empty) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "EMPTY_CHECK_END: skip id:%d, s:%p\n", (int )mem, s);
#endif
empty_check_found:
/* empty loop founded, skip next instruction */
#if defined(ONIG_DEBUG) && !defined(USE_DIRECT_THREADED_CODE)
switch (p->opcode) {
case OP_JUMP:
case OP_PUSH:
case OP_REPEAT_INC:
case OP_REPEAT_INC_NG:
case OP_REPEAT_INC_SG:
case OP_REPEAT_INC_NG_SG:
INC_OP;
break;
default:
goto unexpected_bytecode_error;
break;
}
#else
INC_OP;
#endif
}
}
JUMP_OUT;
#ifdef USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT
CASE_OP(EMPTY_CHECK_END_MEMST)
{
int is_empty;
mem = p->empty_check_end.mem; /* mem: null check id */
STACK_EMPTY_CHECK_MEM(is_empty, mem, s, reg);
INC_OP;
if (is_empty) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "EMPTY_CHECK_END_MEM: skip id:%d, s:%p\n", (int)mem, s);
#endif
if (is_empty == -1) goto fail;
goto empty_check_found;
}
}
JUMP_OUT;
#endif
#ifdef USE_CALL
CASE_OP(EMPTY_CHECK_END_MEMST_PUSH)
{
int is_empty;
mem = p->empty_check_end.mem; /* mem: null check id */
#ifdef USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT
STACK_EMPTY_CHECK_MEM_REC(is_empty, mem, s, reg);
#else
STACK_EMPTY_CHECK_REC(is_empty, mem, s);
#endif
INC_OP;
if (is_empty) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "EMPTY_CHECK_END_MEM_PUSH: skip id:%d, s:%p\n",
(int )mem, s);
#endif
if (is_empty == -1) goto fail;
goto empty_check_found;
}
else {
STACK_PUSH_EMPTY_CHECK_END(mem);
}
}
JUMP_OUT;
#endif
CASE_OP(JUMP)
addr = p->jump.addr;
p += addr;
CHECK_INTERRUPT_JUMP_OUT;
CASE_OP(PUSH)
addr = p->push.addr;
STACK_PUSH_ALT(p + addr, s, sprev);
INC_OP;
JUMP_OUT;
CASE_OP(PUSH_SUPER)
addr = p->push.addr;
STACK_PUSH_SUPER_ALT(p + addr, s, sprev);
INC_OP;
JUMP_OUT;
CASE_OP(POP_OUT)
STACK_POP_ONE;
/* for stop backtrack */
/* CHECK_RETRY_LIMIT_IN_MATCH; */
INC_OP;
JUMP_OUT;
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
CASE_OP(PUSH_OR_JUMP_EXACT1)
{
UChar c;
addr = p->push_or_jump_exact1.addr;
c = p->push_or_jump_exact1.c;
if (DATA_ENSURE_CHECK1 && c == *s) {
STACK_PUSH_ALT(p + addr, s, sprev);
INC_OP;
JUMP_OUT;
}
}
p += addr;
JUMP_OUT;
#endif
CASE_OP(PUSH_IF_PEEK_NEXT)
{
UChar c;
addr = p->push_if_peek_next.addr;
c = p->push_if_peek_next.c;
if (c == *s) {
STACK_PUSH_ALT(p + addr, s, sprev);
INC_OP;
JUMP_OUT;
}
}
INC_OP;
JUMP_OUT;
CASE_OP(REPEAT)
mem = p->repeat.id; /* mem: OP_REPEAT ID */
addr = p->repeat.addr;
STACK_ENSURE(1);
repeat_stk[mem] = GET_STACK_INDEX(stk);
STACK_PUSH_REPEAT(mem, p + 1);
if (reg->repeat_range[mem].lower == 0) {
STACK_PUSH_ALT(p + addr, s, sprev);
}
INC_OP;
JUMP_OUT;
CASE_OP(REPEAT_NG)
mem = p->repeat.id; /* mem: OP_REPEAT ID */
addr = p->repeat.addr;
STACK_ENSURE(1);
repeat_stk[mem] = GET_STACK_INDEX(stk);
STACK_PUSH_REPEAT(mem, p + 1);
if (reg->repeat_range[mem].lower == 0) {
STACK_PUSH_ALT(p + 1, s, sprev);
p += addr;
}
else
INC_OP;
JUMP_OUT;
CASE_OP(REPEAT_INC)
mem = p->repeat_inc.id; /* mem: OP_REPEAT ID */
si = repeat_stk[mem];
stkp = STACK_AT(si);
repeat_inc:
stkp->u.repeat.count++;
if (stkp->u.repeat.count >= reg->repeat_range[mem].upper) {
/* end of repeat. Nothing to do. */
INC_OP;
}
else if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) {
INC_OP;
STACK_PUSH_ALT(p, s, sprev);
p = STACK_AT(si)->u.repeat.pcode; /* Don't use stkp after PUSH. */
}
else {
p = stkp->u.repeat.pcode;
}
STACK_PUSH_REPEAT_INC(si);
CHECK_INTERRUPT_JUMP_OUT;
CASE_OP(REPEAT_INC_SG)
mem = p->repeat_inc.id; /* mem: OP_REPEAT ID */
STACK_GET_REPEAT(mem, stkp);
si = GET_STACK_INDEX(stkp);
goto repeat_inc;
CASE_OP(REPEAT_INC_NG)
mem = p->repeat_inc.id; /* mem: OP_REPEAT ID */
si = repeat_stk[mem];
stkp = STACK_AT(si);
repeat_inc_ng:
stkp->u.repeat.count++;
if (stkp->u.repeat.count < reg->repeat_range[mem].upper) {
if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) {
Operation* pcode = stkp->u.repeat.pcode;
STACK_PUSH_REPEAT_INC(si);
STACK_PUSH_ALT(pcode, s, sprev);
INC_OP;
}
else {
p = stkp->u.repeat.pcode;
STACK_PUSH_REPEAT_INC(si);
}
}
else if (stkp->u.repeat.count == reg->repeat_range[mem].upper) {
STACK_PUSH_REPEAT_INC(si);
INC_OP;
}
CHECK_INTERRUPT_JUMP_OUT;
CASE_OP(REPEAT_INC_NG_SG)
mem = p->repeat_inc.id; /* mem: OP_REPEAT ID */
STACK_GET_REPEAT(mem, stkp);
si = GET_STACK_INDEX(stkp);
goto repeat_inc_ng;
CASE_OP(PREC_READ_START)
STACK_PUSH_PREC_READ_START(s, sprev);
INC_OP;
JUMP_OUT;
CASE_OP(PREC_READ_END)
STACK_GET_PREC_READ_START(stkp);
s = stkp->u.state.pstr;
sprev = stkp->u.state.pstr_prev;
STACK_PUSH(STK_PREC_READ_END,0,0,0);
INC_OP;
JUMP_OUT;
CASE_OP(PREC_READ_NOT_START)
addr = p->prec_read_not_start.addr;
STACK_PUSH_ALT_PREC_READ_NOT(p + addr, s, sprev);
INC_OP;
JUMP_OUT;
CASE_OP(PREC_READ_NOT_END)
STACK_POP_TIL_ALT_PREC_READ_NOT;
goto fail;
CASE_OP(ATOMIC_START)
STACK_PUSH_TO_VOID_START;
INC_OP;
JUMP_OUT;
CASE_OP(ATOMIC_END)
STACK_EXEC_TO_VOID(stkp);
INC_OP;
JUMP_OUT;
CASE_OP(LOOK_BEHIND)
tlen = p->look_behind.len;
s = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen);
if (IS_NULL(s)) goto fail;
sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s);
INC_OP;
JUMP_OUT;
CASE_OP(LOOK_BEHIND_NOT_START)
addr = p->look_behind_not_start.addr;
tlen = p->look_behind_not_start.len;
q = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen);
if (IS_NULL(q)) {
/* too short case -> success. ex. /(?<!XXX)a/.match("a")
If you want to change to fail, replace following line. */
p += addr;
/* goto fail; */
}
else {
STACK_PUSH_ALT_LOOK_BEHIND_NOT(p + addr, s, sprev);
s = q;
sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s);
INC_OP;
}
JUMP_OUT;
CASE_OP(LOOK_BEHIND_NOT_END)
STACK_POP_TIL_ALT_LOOK_BEHIND_NOT;
INC_OP;
goto fail;
#ifdef USE_CALL
CASE_OP(CALL)
addr = p->call.addr;
INC_OP; STACK_PUSH_CALL_FRAME(p);
p = reg->ops + addr;
JUMP_OUT;
CASE_OP(RETURN)
STACK_RETURN(p);
STACK_PUSH_RETURN;
JUMP_OUT;
#endif
CASE_OP(PUSH_SAVE_VAL)
{
SaveType type;
type = p->push_save_val.type;
mem = p->push_save_val.id; /* mem: save id */
switch ((enum SaveType )type) {
case SAVE_KEEP:
STACK_PUSH_SAVE_VAL(mem, type, s);
break;
case SAVE_S:
STACK_PUSH_SAVE_VAL_WITH_SPREV(mem, type, s);
break;
case SAVE_RIGHT_RANGE:
STACK_PUSH_SAVE_VAL(mem, SAVE_RIGHT_RANGE, right_range);
break;
}
}
INC_OP;
JUMP_OUT;
CASE_OP(UPDATE_VAR)
{
UpdateVarType type;
enum SaveType save_type;
type = p->update_var.type;
mem = p->update_var.id; /* mem: save id */
switch ((enum UpdateVarType )type) {
case UPDATE_VAR_KEEP_FROM_STACK_LAST:
STACK_GET_SAVE_VAL_TYPE_LAST(SAVE_KEEP, keep);
break;
case UPDATE_VAR_S_FROM_STACK:
STACK_GET_SAVE_VAL_TYPE_LAST_ID_WITH_SPREV(SAVE_S, mem, s);
break;
case UPDATE_VAR_RIGHT_RANGE_FROM_S_STACK:
save_type = SAVE_S;
goto get_save_val_type_last_id;
break;
case UPDATE_VAR_RIGHT_RANGE_FROM_STACK:
save_type = SAVE_RIGHT_RANGE;
get_save_val_type_last_id:
STACK_GET_SAVE_VAL_TYPE_LAST_ID(save_type, mem, right_range);
break;
case UPDATE_VAR_RIGHT_RANGE_INIT:
INIT_RIGHT_RANGE;
break;
}
}
INC_OP;
JUMP_OUT;
#ifdef USE_CALLOUT
CASE_OP(CALLOUT_CONTENTS)
of = ONIG_CALLOUT_OF_CONTENTS;
mem = p->callout_contents.num;
goto callout_common_entry;
BREAK_OUT;
CASE_OP(CALLOUT_NAME)
{
int call_result;
int name_id;
int in;
CalloutListEntry* e;
OnigCalloutFunc func;
OnigCalloutArgs args;
of = ONIG_CALLOUT_OF_NAME;
name_id = p->callout_name.id;
mem = p->callout_name.num;
callout_common_entry:
e = onig_reg_callout_list_at(reg, mem);
in = e->in;
if (of == ONIG_CALLOUT_OF_NAME) {
func = onig_get_callout_start_func(reg, mem);
}
else {
name_id = ONIG_NON_NAME_ID;
func = msa->mp->progress_callout_of_contents;
}
if (IS_NOT_NULL(func) && (in & ONIG_CALLOUT_IN_PROGRESS) != 0) {
CALLOUT_BODY(func, ONIG_CALLOUT_IN_PROGRESS, name_id,
(int )mem, msa->mp->callout_user_data, args, call_result);
switch (call_result) {
case ONIG_CALLOUT_FAIL:
goto fail;
break;
case ONIG_CALLOUT_SUCCESS:
goto retraction_callout2;
break;
default: /* error code */
if (call_result > 0) {
call_result = ONIGERR_INVALID_ARGUMENT;
}
best_len = call_result;
goto finish;
break;
}
}
else {
retraction_callout2:
if ((in & ONIG_CALLOUT_IN_RETRACTION) != 0) {
if (of == ONIG_CALLOUT_OF_NAME) {
if (IS_NOT_NULL(func)) {
STACK_PUSH_CALLOUT_NAME(name_id, mem, func);
}
}
else {
func = msa->mp->retraction_callout_of_contents;
if (IS_NOT_NULL(func)) {
STACK_PUSH_CALLOUT_CONTENTS(mem, func);
}
}
}
}
}
INC_OP;
JUMP_OUT;
#endif
CASE_OP(FINISH)
goto finish;
#ifdef ONIG_DEBUG_STATISTICS
fail:
SOP_OUT;
goto fail2;
#endif
CASE_OP(FAIL)
#ifdef ONIG_DEBUG_STATISTICS
fail2:
#else
fail:
#endif
STACK_POP;
p = stk->u.state.pcode;
s = stk->u.state.pstr;
sprev = stk->u.state.pstr_prev;
CHECK_RETRY_LIMIT_IN_MATCH;
JUMP_OUT;
DEFAULT_OP
goto bytecode_error;
} BYTECODE_INTERPRETER_END;
finish:
STACK_SAVE;
return best_len;
#ifdef ONIG_DEBUG
stack_error:
STACK_SAVE;
return ONIGERR_STACK_BUG;
#endif
bytecode_error:
STACK_SAVE;
return ONIGERR_UNDEFINED_BYTECODE;
#if defined(ONIG_DEBUG) && !defined(USE_DIRECT_THREADED_CODE)
unexpected_bytecode_error:
STACK_SAVE;
return ONIGERR_UNEXPECTED_BYTECODE;
#endif
#ifdef USE_RETRY_LIMIT_IN_MATCH
retry_limit_in_match_over:
STACK_SAVE;
return ONIGERR_RETRY_LIMIT_IN_MATCH_OVER;
#endif
}
static UChar*
slow_search(OnigEncoding enc, UChar* target, UChar* target_end,
const UChar* text, const UChar* text_end, UChar* text_range)
{
UChar *t, *p, *s, *end;
end = (UChar* )text_end;
end -= target_end - target - 1;
if (end > text_range)
end = text_range;
s = (UChar* )text;
while (s < end) {
if (*s == *target) {
p = s + 1;
t = target + 1;
while (t < target_end) {
if (*t != *p++)
break;
t++;
}
if (t == target_end)
return s;
}
s += enclen(enc, s);
}
return (UChar* )NULL;
}
static int
str_lower_case_match(OnigEncoding enc, int case_fold_flag,
const UChar* t, const UChar* tend,
const UChar* p, const UChar* end)
{
int lowlen;
UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
while (t < tend) {
lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf);
q = lowbuf;
while (lowlen > 0) {
if (t >= tend) return 0;
if (*t++ != *q++) return 0;
lowlen--;
}
}
return 1;
}
static UChar*
slow_search_ic(OnigEncoding enc, int case_fold_flag,
UChar* target, UChar* target_end,
const UChar* text, const UChar* text_end, UChar* text_range)
{
UChar *s, *end;
end = (UChar* )text_end;
end -= target_end - target - 1;
if (end > text_range)
end = text_range;
s = (UChar* )text;
while (s < end) {
if (str_lower_case_match(enc, case_fold_flag, target, target_end,
s, text_end))
return s;
s += enclen(enc, s);
}
return (UChar* )NULL;
}
static UChar*
slow_search_backward(OnigEncoding enc, UChar* target, UChar* target_end,
const UChar* text, const UChar* adjust_text,
const UChar* text_end, const UChar* text_start)
{
UChar *t, *p, *s;
s = (UChar* )text_end;
s -= (target_end - target);
if (s > text_start)
s = (UChar* )text_start;
else
s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, adjust_text, s);
while (s >= text) {
if (*s == *target) {
p = s + 1;
t = target + 1;
while (t < target_end) {
if (*t != *p++)
break;
t++;
}
if (t == target_end)
return s;
}
s = (UChar* )onigenc_get_prev_char_head(enc, adjust_text, s);
}
return (UChar* )NULL;
}
static UChar*
slow_search_backward_ic(OnigEncoding enc, int case_fold_flag,
UChar* target, UChar* target_end,
const UChar* text, const UChar* adjust_text,
const UChar* text_end, const UChar* text_start)
{
UChar *s;
s = (UChar* )text_end;
s -= (target_end - target);
if (s > text_start)
s = (UChar* )text_start;
else
s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, adjust_text, s);
while (s >= text) {
if (str_lower_case_match(enc, case_fold_flag,
target, target_end, s, text_end))
return s;
s = (UChar* )onigenc_get_prev_char_head(enc, adjust_text, s);
}
return (UChar* )NULL;
}
static UChar*
sunday_quick_search_step_forward(regex_t* reg,
const UChar* target, const UChar* target_end,
const UChar* text, const UChar* text_end,
const UChar* text_range)
{
const UChar *s, *se, *t, *p, *end;
const UChar *tail;
int skip, tlen1;
int map_offset;
OnigEncoding enc;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"sunday_quick_search_step_forward: text: %p, text_end: %p, text_range: %p\n", text, text_end, text_range);
#endif
enc = reg->enc;
tail = target_end - 1;
tlen1 = (int )(tail - target);
end = text_range;
if (end + tlen1 > text_end)
end = text_end - tlen1;
map_offset = reg->map_offset;
s = text;
while (s < end) {
p = se = s + tlen1;
t = tail;
while (*p == *t) {
if (t == target) return (UChar* )s;
p--; t--;
}
if (se + map_offset >= text_end) break;
skip = reg->map[*(se + map_offset)];
#if 0
t = s;
do {
s += enclen(enc, s);
} while ((s - t) < skip && s < end);
#else
s += skip;
if (s < end)
s = onigenc_get_right_adjust_char_head(enc, text, s);
#endif
}
return (UChar* )NULL;
}
static UChar*
sunday_quick_search(regex_t* reg, const UChar* target, const UChar* target_end,
const UChar* text, const UChar* text_end,
const UChar* text_range)
{
const UChar *s, *t, *p, *end;
const UChar *tail;
int map_offset;
end = text_range + (target_end - target);
if (end > text_end)
end = text_end;
map_offset = reg->map_offset;
tail = target_end - 1;
s = text + (tail - target);
while (s < end) {
p = s;
t = tail;
while (*p == *t) {
if (t == target) return (UChar* )p;
p--; t--;
}
if (s + map_offset >= text_end) break;
s += reg->map[*(s + map_offset)];
}
return (UChar* )NULL;
}
static UChar*
sunday_quick_search_case_fold(regex_t* reg,
const UChar* target, const UChar* target_end,
const UChar* text, const UChar* text_end,
const UChar* text_range)
{
const UChar *s, *se, *end;
const UChar *tail;
int skip, tlen1;
int map_offset;
int case_fold_flag;
OnigEncoding enc;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"sunday_quick_search_case_fold: text: %p, text_end: %p, text_range: %p\n", text, text_end, text_range);
#endif
enc = reg->enc;
case_fold_flag = reg->case_fold_flag;
tail = target_end - 1;
tlen1 = (int )(tail - target);
end = text_range;
if (end + tlen1 > text_end)
end = text_end - tlen1;
map_offset = reg->map_offset;
s = text;
while (s < end) {
if (str_lower_case_match(enc, case_fold_flag, target, target_end,
s, text_end))
return (UChar* )s;
se = s + tlen1;
if (se + map_offset >= text_end) break;
skip = reg->map[*(se + map_offset)];
#if 0
p = s;
do {
s += enclen(enc, s);
} while ((s - p) < skip && s < end);
#else
/* This is faster than prev code for long text. ex: /(?i)Twain/ */
s += skip;
if (s < end)
s = onigenc_get_right_adjust_char_head(enc, text, s);
#endif
}
return (UChar* )NULL;
}
static UChar*
map_search(OnigEncoding enc, UChar map[],
const UChar* text, const UChar* text_range)
{
const UChar *s = text;
while (s < text_range) {
if (map[*s]) return (UChar* )s;
s += enclen(enc, s);
}
return (UChar* )NULL;
}
static UChar*
map_search_backward(OnigEncoding enc, UChar map[],
const UChar* text, const UChar* adjust_text,
const UChar* text_start)
{
const UChar *s = text_start;
while (s >= text) {
if (map[*s]) return (UChar* )s;
s = onigenc_get_prev_char_head(enc, adjust_text, s);
}
return (UChar* )NULL;
}
extern int
onig_match(regex_t* reg, const UChar* str, const UChar* end, const UChar* at,
OnigRegion* region, OnigOptionType option)
{
int r;
OnigMatchParam mp;
onig_initialize_match_param(&mp);
r = onig_match_with_param(reg, str, end, at, region, option, &mp);
onig_free_match_param_content(&mp);
return r;
}
extern int
onig_match_with_param(regex_t* reg, const UChar* str, const UChar* end,
const UChar* at, OnigRegion* region, OnigOptionType option,
OnigMatchParam* mp)
{
int r;
UChar *prev;
MatchArg msa;
ADJUST_MATCH_PARAM(reg, mp);
MATCH_ARG_INIT(msa, reg, option, region, at, mp);
if (region
#ifdef USE_POSIX_API_REGION_OPTION
&& !IS_POSIX_REGION(option)
#endif
) {
r = onig_region_resize_clear(region, reg->num_mem + 1);
}
else
r = 0;
if (r == 0) {
if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) {
if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) {
r = ONIGERR_INVALID_WIDE_CHAR_VALUE;
goto end;
}
}
prev = (UChar* )onigenc_get_prev_char_head(reg->enc, str, at);
r = match_at(reg, str, end, end, at, prev, &msa);
}
end:
MATCH_ARG_FREE(msa);
return r;
}
static int
forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %p, end: %p, s: %p, range: %p\n",
str, end, s, range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
if (q >= end) return 0; /* fail */
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case OPTIMIZE_STR:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case OPTIMIZE_STR_CASE_FOLD:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case OPTIMIZE_STR_CASE_FOLD_FAST:
p = sunday_quick_search_case_fold(reg, reg->exact, reg->exact_end, p, end,
range);
break;
case OPTIMIZE_STR_FAST:
p = sunday_quick_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case OPTIMIZE_STR_FAST_STEP_FORWARD:
p = sunday_quick_search_step_forward(reg, reg->exact, reg->exact_end,
p, end, range);
break;
case OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != INFINITE_LEN) {
if (p - str < reg->dmax) {
*low = (UChar* )str;
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc, str, *low);
}
else {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
}
static int
backward_search_range(regex_t* reg, const UChar* str, const UChar* end,
UChar* s, const UChar* range, UChar* adjrange,
UChar** low, UChar** high)
{
UChar *p;
if (range == 0) goto fail;
range += reg->dmin;
p = s;
retry:
switch (reg->optimize) {
case OPTIMIZE_STR:
exact_method:
p = slow_search_backward(reg->enc, reg->exact, reg->exact_end,
range, adjrange, end, p);
break;
case OPTIMIZE_STR_CASE_FOLD:
case OPTIMIZE_STR_CASE_FOLD_FAST:
p = slow_search_backward_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end,
range, adjrange, end, p);
break;
case OPTIMIZE_STR_FAST:
case OPTIMIZE_STR_FAST_STEP_FORWARD:
goto exact_method;
break;
case OPTIMIZE_MAP:
p = map_search_backward(reg->enc, reg->map, range, adjrange, p);
break;
}
if (p) {
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc, str, p);
if (IS_NOT_NULL(prev) && !ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) {
p = prev;
goto retry;
}
}
break;
case ANCR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = onigenc_get_prev_char_head(reg->enc, adjrange, p);
if (IS_NULL(prev)) goto fail;
if (ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) {
p = prev;
goto retry;
}
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
) {
p = onigenc_get_prev_char_head(reg->enc, adjrange, p);
if (IS_NULL(p)) goto fail;
goto retry;
}
break;
}
}
/* no needs to adjust *high, *high is used as range check only */
if (reg->dmax != INFINITE_LEN) {
*low = p - reg->dmax;
*high = p - reg->dmin;
*high = onigenc_get_right_adjust_char_head(reg->enc, adjrange, *high);
}
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "backward_search_range: low: %d, high: %d\n",
(int )(*low - str), (int )(*high - str));
#endif
return 1; /* success */
}
fail:
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "backward_search_range: fail.\n");
#endif
return 0; /* fail */
}
extern int
onig_search(regex_t* reg, const UChar* str, const UChar* end,
const UChar* start, const UChar* range, OnigRegion* region,
OnigOptionType option)
{
int r;
OnigMatchParam mp;
onig_initialize_match_param(&mp);
r = onig_search_with_param(reg, str, end, start, range, region, option, &mp);
onig_free_match_param_content(&mp);
return r;
}
extern int
onig_search_with_param(regex_t* reg, const UChar* str, const UChar* end,
const UChar* start, const UChar* range, OnigRegion* region,
OnigOptionType option, OnigMatchParam* mp)
{
int r;
UChar *s, *prev;
MatchArg msa;
const UChar *orig_start = start;
const UChar *orig_range = range;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"onig_search (entry point): str: %p, end: %d, start: %d, range: %d\n",
str, (int )(end - str), (int )(start - str), (int )(range - str));
#endif
ADJUST_MATCH_PARAM(reg, mp);
if (region
#ifdef USE_POSIX_API_REGION_OPTION
&& !IS_POSIX_REGION(option)
#endif
) {
r = onig_region_resize_clear(region, reg->num_mem + 1);
if (r != 0) goto finish_no_msa;
}
if (start > end || start < str) goto mismatch_no_msa;
if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) {
if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) {
r = ONIGERR_INVALID_WIDE_CHAR_VALUE;
goto finish_no_msa;
}
}
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
#define MATCH_AND_RETURN_CHECK(upper_range) \
r = match_at(reg, str, end, (upper_range), s, prev, &msa); \
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
if (! IS_FIND_LONGEST(reg->options)) {\
goto match;\
}\
}\
else goto finish; /* error */ \
}
#else
#define MATCH_AND_RETURN_CHECK(upper_range) \
r = match_at(reg, str, end, (upper_range), s, prev, &msa); \
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
goto match;\
}\
else goto finish; /* error */ \
}
#endif /* USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE */
/* anchor optimize: resume search range */
if (reg->anchor != 0 && str < end) {
UChar *min_semi_end, *max_semi_end;
if (reg->anchor & ANCR_BEGIN_POSITION) {
/* search start-position only */
begin_position:
if (range > start)
range = start + 1;
else
range = start;
}
else if (reg->anchor & ANCR_BEGIN_BUF) {
/* search str-position only */
if (range > start) {
if (start != str) goto mismatch_no_msa;
range = str + 1;
}
else {
if (range <= str) {
start = str;
range = str;
}
else
goto mismatch_no_msa;
}
}
else if (reg->anchor & ANCR_END_BUF) {
min_semi_end = max_semi_end = (UChar* )end;
end_buf:
if ((OnigLen )(max_semi_end - str) < reg->anchor_dmin)
goto mismatch_no_msa;
if (range > start) {
if ((OnigLen )(min_semi_end - start) > reg->anchor_dmax) {
start = min_semi_end - reg->anchor_dmax;
if (start < end)
start = onigenc_get_right_adjust_char_head(reg->enc, str, start);
}
if ((OnigLen )(max_semi_end - (range - 1)) < reg->anchor_dmin) {
range = max_semi_end - reg->anchor_dmin + 1;
}
if (start > range) goto mismatch_no_msa;
/* If start == range, match with empty at end.
Backward search is used. */
}
else {
if ((OnigLen )(min_semi_end - range) > reg->anchor_dmax) {
range = min_semi_end - reg->anchor_dmax;
}
if ((OnigLen )(max_semi_end - start) < reg->anchor_dmin) {
start = max_semi_end - reg->anchor_dmin;
start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, start);
}
if (range > start) goto mismatch_no_msa;
}
}
else if (reg->anchor & ANCR_SEMI_END_BUF) {
UChar* pre_end = ONIGENC_STEP_BACK(reg->enc, str, end, 1);
max_semi_end = (UChar* )end;
if (ONIGENC_IS_MBC_NEWLINE(reg->enc, pre_end, end)) {
min_semi_end = pre_end;
#ifdef USE_CRNL_AS_LINE_TERMINATOR
pre_end = ONIGENC_STEP_BACK(reg->enc, str, pre_end, 1);
if (IS_NOT_NULL(pre_end) &&
ONIGENC_IS_MBC_CRNL(reg->enc, pre_end, end)) {
min_semi_end = pre_end;
}
#endif
if (min_semi_end > str && start <= min_semi_end) {
goto end_buf;
}
}
else {
min_semi_end = (UChar* )end;
goto end_buf;
}
}
else if ((reg->anchor & ANCR_ANYCHAR_INF_ML)) {
goto begin_position;
}
}
else if (str == end) { /* empty string */
static const UChar* address_for_empty_string = (UChar* )"";
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "onig_search: empty string.\n");
#endif
if (reg->threshold_len == 0) {
start = end = str = address_for_empty_string;
s = (UChar* )start;
prev = (UChar* )NULL;
MATCH_ARG_INIT(msa, reg, option, region, start, mp);
MATCH_AND_RETURN_CHECK(end);
goto mismatch;
}
goto mismatch_no_msa;
}
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "onig_search(apply anchor): end: %d, start: %d, range: %d\n",
(int )(end - str), (int )(start - str), (int )(range - str));
#endif
MATCH_ARG_INIT(msa, reg, option, region, orig_start, mp);
s = (UChar* )start;
if (range > start) { /* forward search */
if (s > str)
prev = onigenc_get_prev_char_head(reg->enc, str, s);
else
prev = (UChar* )NULL;
if (reg->optimize != OPTIMIZE_NONE) {
UChar *sch_range, *low, *high, *low_prev;
sch_range = (UChar* )range;
if (reg->dmax != 0) {
if (reg->dmax == INFINITE_LEN)
sch_range = (UChar* )end;
else {
sch_range += reg->dmax;
if (sch_range > end) sch_range = (UChar* )end;
}
}
if ((end - start) < reg->threshold_len)
goto mismatch;
if (reg->dmax != INFINITE_LEN) {
do {
if (! forward_search_range(reg, str, end, s, sch_range,
&low, &high, &low_prev)) goto mismatch;
if (s < low) {
s = low;
prev = low_prev;
}
while (s <= high) {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
}
} while (s < range);
goto mismatch;
}
else { /* check only. */
if (! forward_search_range(reg, str, end, s, sch_range,
&low, &high, (UChar** )NULL)) goto mismatch;
if ((reg->anchor & ANCR_ANYCHAR_INF) != 0) {
do {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
if ((reg->anchor & (ANCR_LOOK_BEHIND | ANCR_PREC_READ_NOT)) == 0) {
while (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end) && s < range) {
prev = s;
s += enclen(reg->enc, s);
}
}
} while (s < range);
goto mismatch;
}
}
}
do {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
} while (s < range);
if (s == range) { /* because empty match with /$/. */
MATCH_AND_RETURN_CHECK(orig_range);
}
}
else { /* backward search */
if (range < str) goto mismatch;
if (orig_start < end)
orig_start += enclen(reg->enc, orig_start); /* is upper range */
if (reg->optimize != OPTIMIZE_NONE) {
UChar *low, *high, *adjrange, *sch_start;
if (range < end)
adjrange = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, range);
else
adjrange = (UChar* )end;
if (reg->dmax != INFINITE_LEN &&
(end - range) >= reg->threshold_len) {
do {
sch_start = s + reg->dmax;
if (sch_start > end) sch_start = (UChar* )end;
if (backward_search_range(reg, str, end, sch_start, range, adjrange,
&low, &high) <= 0)
goto mismatch;
if (s > high)
s = high;
while (s >= low) {
prev = onigenc_get_prev_char_head(reg->enc, str, s);
MATCH_AND_RETURN_CHECK(orig_start);
s = prev;
}
} while (s >= range);
goto mismatch;
}
else { /* check only. */
if ((end - range) < reg->threshold_len) goto mismatch;
sch_start = s;
if (reg->dmax != 0) {
if (reg->dmax == INFINITE_LEN)
sch_start = (UChar* )end;
else {
sch_start += reg->dmax;
if (sch_start > end) sch_start = (UChar* )end;
else
sch_start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc,
start, sch_start);
}
}
if (backward_search_range(reg, str, end, sch_start, range, adjrange,
&low, &high) <= 0) goto mismatch;
}
}
do {
prev = onigenc_get_prev_char_head(reg->enc, str, s);
MATCH_AND_RETURN_CHECK(orig_start);
s = prev;
} while (s >= range);
}
mismatch:
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
if (IS_FIND_LONGEST(reg->options)) {
if (msa.best_len >= 0) {
s = msa.best_s;
goto match;
}
}
#endif
r = ONIG_MISMATCH;
finish:
MATCH_ARG_FREE(msa);
/* If result is mismatch and no FIND_NOT_EMPTY option,
then the region is not set in match_at(). */
if (IS_FIND_NOT_EMPTY(reg->options) && region
#ifdef USE_POSIX_API_REGION_OPTION
&& !IS_POSIX_REGION(option)
#endif
) {
onig_region_clear(region);
}
#ifdef ONIG_DEBUG
if (r != ONIG_MISMATCH)
fprintf(stderr, "onig_search: error %d\n", r);
#endif
return r;
mismatch_no_msa:
r = ONIG_MISMATCH;
finish_no_msa:
#ifdef ONIG_DEBUG
if (r != ONIG_MISMATCH)
fprintf(stderr, "onig_search: error %d\n", r);
#endif
return r;
match:
MATCH_ARG_FREE(msa);
return (int )(s - str);
}
extern int
onig_scan(regex_t* reg, const UChar* str, const UChar* end,
OnigRegion* region, OnigOptionType option,
int (*scan_callback)(int, int, OnigRegion*, void*),
void* callback_arg)
{
int r;
int n;
int rs;
const UChar* start;
if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) {
if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end))
return ONIGERR_INVALID_WIDE_CHAR_VALUE;
ONIG_OPTION_OFF(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING);
}
n = 0;
start = str;
while (1) {
r = onig_search(reg, str, end, start, end, region, option);
if (r >= 0) {
rs = scan_callback(n, r, region, callback_arg);
n++;
if (rs != 0)
return rs;
if (region->end[0] == start - str) {
if (start >= end) break;
start += enclen(reg->enc, start);
}
else
start = str + region->end[0];
if (start > end)
break;
}
else if (r == ONIG_MISMATCH) {
break;
}
else { /* error */
return r;
}
}
return n;
}
extern OnigEncoding
onig_get_encoding(regex_t* reg)
{
return reg->enc;
}
extern OnigOptionType
onig_get_options(regex_t* reg)
{
return reg->options;
}
extern OnigCaseFoldType
onig_get_case_fold_flag(regex_t* reg)
{
return reg->case_fold_flag;
}
extern OnigSyntaxType*
onig_get_syntax(regex_t* reg)
{
return reg->syntax;
}
extern int
onig_number_of_captures(regex_t* reg)
{
return reg->num_mem;
}
extern int
onig_number_of_capture_histories(regex_t* reg)
{
#ifdef USE_CAPTURE_HISTORY
int i, n;
n = 0;
for (i = 0; i <= ONIG_MAX_CAPTURE_HISTORY_GROUP; i++) {
if (MEM_STATUS_AT(reg->capture_history, i) != 0)
n++;
}
return n;
#else
return 0;
#endif
}
extern void
onig_copy_encoding(OnigEncoding to, OnigEncoding from)
{
*to = *from;
}
#ifdef USE_DIRECT_THREADED_CODE
extern int
onig_init_for_match_at(regex_t* reg)
{
return match_at(reg, (const UChar* )NULL, (const UChar* )NULL,
(const UChar* )NULL, (const UChar* )NULL, (UChar* )NULL,
(MatchArg* )NULL);
}
#endif
/* for callout functions */
#ifdef USE_CALLOUT
extern OnigCalloutFunc
onig_get_progress_callout(void)
{
return DefaultProgressCallout;
}
extern int
onig_set_progress_callout(OnigCalloutFunc f)
{
DefaultProgressCallout = f;
return ONIG_NORMAL;
}
extern OnigCalloutFunc
onig_get_retraction_callout(void)
{
return DefaultRetractionCallout;
}
extern int
onig_set_retraction_callout(OnigCalloutFunc f)
{
DefaultRetractionCallout = f;
return ONIG_NORMAL;
}
extern int
onig_get_callout_num_by_callout_args(OnigCalloutArgs* args)
{
return args->num;
}
extern OnigCalloutIn
onig_get_callout_in_by_callout_args(OnigCalloutArgs* args)
{
return args->in;
}
extern int
onig_get_name_id_by_callout_args(OnigCalloutArgs* args)
{
return args->name_id;
}
extern const UChar*
onig_get_contents_by_callout_args(OnigCalloutArgs* args)
{
int num;
CalloutListEntry* e;
num = args->num;
e = onig_reg_callout_list_at(args->regex, num);
if (IS_NULL(e)) return 0;
if (e->of == ONIG_CALLOUT_OF_CONTENTS) {
return e->u.content.start;
}
return 0;
}
extern const UChar*
onig_get_contents_end_by_callout_args(OnigCalloutArgs* args)
{
int num;
CalloutListEntry* e;
num = args->num;
e = onig_reg_callout_list_at(args->regex, num);
if (IS_NULL(e)) return 0;
if (e->of == ONIG_CALLOUT_OF_CONTENTS) {
return e->u.content.end;
}
return 0;
}
extern int
onig_get_args_num_by_callout_args(OnigCalloutArgs* args)
{
int num;
CalloutListEntry* e;
num = args->num;
e = onig_reg_callout_list_at(args->regex, num);
if (IS_NULL(e)) return ONIGERR_INVALID_ARGUMENT;
if (e->of == ONIG_CALLOUT_OF_NAME) {
return e->u.arg.num;
}
return ONIGERR_INVALID_ARGUMENT;
}
extern int
onig_get_passed_args_num_by_callout_args(OnigCalloutArgs* args)
{
int num;
CalloutListEntry* e;
num = args->num;
e = onig_reg_callout_list_at(args->regex, num);
if (IS_NULL(e)) return ONIGERR_INVALID_ARGUMENT;
if (e->of == ONIG_CALLOUT_OF_NAME) {
return e->u.arg.passed_num;
}
return ONIGERR_INVALID_ARGUMENT;
}
extern int
onig_get_arg_by_callout_args(OnigCalloutArgs* args, int index,
OnigType* type, OnigValue* val)
{
int num;
CalloutListEntry* e;
num = args->num;
e = onig_reg_callout_list_at(args->regex, num);
if (IS_NULL(e)) return ONIGERR_INVALID_ARGUMENT;
if (e->of == ONIG_CALLOUT_OF_NAME) {
if (IS_NOT_NULL(type)) *type = e->u.arg.types[index];
if (IS_NOT_NULL(val)) *val = e->u.arg.vals[index];
return ONIG_NORMAL;
}
return ONIGERR_INVALID_ARGUMENT;
}
extern const UChar*
onig_get_string_by_callout_args(OnigCalloutArgs* args)
{
return args->string;
}
extern const UChar*
onig_get_string_end_by_callout_args(OnigCalloutArgs* args)
{
return args->string_end;
}
extern const UChar*
onig_get_start_by_callout_args(OnigCalloutArgs* args)
{
return args->start;
}
extern const UChar*
onig_get_right_range_by_callout_args(OnigCalloutArgs* args)
{
return args->right_range;
}
extern const UChar*
onig_get_current_by_callout_args(OnigCalloutArgs* args)
{
return args->current;
}
extern OnigRegex
onig_get_regex_by_callout_args(OnigCalloutArgs* args)
{
return args->regex;
}
extern unsigned long
onig_get_retry_counter_by_callout_args(OnigCalloutArgs* args)
{
return args->retry_in_match_counter;
}
extern int
onig_get_capture_range_in_callout(OnigCalloutArgs* a, int mem_num, int* begin, int* end)
{
OnigRegex reg;
const UChar* str;
StackType* stk_base;
int i;
i = mem_num;
reg = a->regex;
str = a->string;
stk_base = a->stk_base;
if (i > 0) {
if (a->mem_end_stk[i] != INVALID_STACK_INDEX) {
if (MEM_STATUS_AT(reg->bt_mem_start, i))
*begin = (int )(STACK_AT(a->mem_start_stk[i])->u.mem.pstr - str);
else
*begin = (int )((UChar* )((void* )a->mem_start_stk[i]) - str);
*end = (int )((MEM_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(a->mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )a->mem_end_stk[i])) - str);
}
else {
*begin = *end = ONIG_REGION_NOTPOS;
}
}
else
return ONIGERR_INVALID_ARGUMENT;
return ONIG_NORMAL;
}
extern int
onig_get_used_stack_size_in_callout(OnigCalloutArgs* a, int* used_num, int* used_bytes)
{
int n;
n = (int )(a->stk - a->stk_base);
if (used_num != 0)
*used_num = n;
if (used_bytes != 0)
*used_bytes = n * sizeof(StackType);
return ONIG_NORMAL;
}
/* builtin callout functions */
extern int
onig_builtin_fail(OnigCalloutArgs* args ARG_UNUSED, void* user_data ARG_UNUSED)
{
return ONIG_CALLOUT_FAIL;
}
extern int
onig_builtin_mismatch(OnigCalloutArgs* args ARG_UNUSED, void* user_data ARG_UNUSED)
{
return ONIG_MISMATCH;
}
extern int
onig_builtin_error(OnigCalloutArgs* args, void* user_data ARG_UNUSED)
{
int r;
int n;
OnigValue val;
r = onig_get_arg_by_callout_args(args, 0, 0, &val);
if (r != ONIG_NORMAL) return r;
n = (int )val.l;
if (n >= 0) {
n = ONIGERR_INVALID_CALLOUT_BODY;
}
else if (onig_is_error_code_needs_param(n)) {
n = ONIGERR_INVALID_CALLOUT_BODY;
}
return n;
}
extern int
onig_builtin_count(OnigCalloutArgs* args, void* user_data)
{
(void )onig_check_callout_data_and_clear_old_values(args);
return onig_builtin_total_count(args, user_data);
}
extern int
onig_builtin_total_count(OnigCalloutArgs* args, void* user_data ARG_UNUSED)
{
int r;
int slot;
OnigType type;
OnigValue val;
OnigValue aval;
OnigCodePoint count_type;
r = onig_get_arg_by_callout_args(args, 0, &type, &aval);
if (r != ONIG_NORMAL) return r;
count_type = aval.c;
if (count_type != '>' && count_type != 'X' && count_type != '<')
return ONIGERR_INVALID_CALLOUT_ARG;
r = onig_get_callout_data_by_callout_args_self_dont_clear_old(args, 0,
&type, &val);
if (r < ONIG_NORMAL)
return r;
else if (r > ONIG_NORMAL) {
/* type == void: initial state */
val.l = 0;
}
if (args->in == ONIG_CALLOUT_IN_RETRACTION) {
slot = 2;
if (count_type == '<')
val.l++;
else if (count_type == 'X')
val.l--;
}
else {
slot = 1;
if (count_type != '<')
val.l++;
}
r = onig_set_callout_data_by_callout_args_self(args, 0, ONIG_TYPE_LONG, &val);
if (r != ONIG_NORMAL) return r;
/* slot 1: in progress counter, slot 2: in retraction counter */
r = onig_get_callout_data_by_callout_args_self_dont_clear_old(args, slot,
&type, &val);
if (r < ONIG_NORMAL)
return r;
else if (r > ONIG_NORMAL) {
val.l = 0;
}
val.l++;
r = onig_set_callout_data_by_callout_args_self(args, slot, ONIG_TYPE_LONG, &val);
if (r != ONIG_NORMAL) return r;
return ONIG_CALLOUT_SUCCESS;
}
extern int
onig_builtin_max(OnigCalloutArgs* args, void* user_data ARG_UNUSED)
{
int r;
int slot;
long max_val;
OnigCodePoint count_type;
OnigType type;
OnigValue val;
OnigValue aval;
(void )onig_check_callout_data_and_clear_old_values(args);
slot = 0;
r = onig_get_callout_data_by_callout_args_self(args, slot, &type, &val);
if (r < ONIG_NORMAL)
return r;
else if (r > ONIG_NORMAL) {
/* type == void: initial state */
type = ONIG_TYPE_LONG;
val.l = 0;
}
r = onig_get_arg_by_callout_args(args, 0, &type, &aval);
if (r != ONIG_NORMAL) return r;
if (type == ONIG_TYPE_TAG) {
r = onig_get_callout_data_by_callout_args(args, aval.tag, 0, &type, &aval);
if (r < ONIG_NORMAL) return r;
else if (r > ONIG_NORMAL)
max_val = 0L;
else
max_val = aval.l;
}
else { /* LONG */
max_val = aval.l;
}
r = onig_get_arg_by_callout_args(args, 1, &type, &aval);
if (r != ONIG_NORMAL) return r;
count_type = aval.c;
if (count_type != '>' && count_type != 'X' && count_type != '<')
return ONIGERR_INVALID_CALLOUT_ARG;
if (args->in == ONIG_CALLOUT_IN_RETRACTION) {
if (count_type == '<') {
if (val.l >= max_val) return ONIG_CALLOUT_FAIL;
val.l++;
}
else if (count_type == 'X')
val.l--;
}
else {
if (count_type != '<') {
if (val.l >= max_val) return ONIG_CALLOUT_FAIL;
val.l++;
}
}
r = onig_set_callout_data_by_callout_args_self(args, slot, ONIG_TYPE_LONG, &val);
if (r != ONIG_NORMAL) return r;
return ONIG_CALLOUT_SUCCESS;
}
enum OP_CMP {
OP_EQ,
OP_NE,
OP_LT,
OP_GT,
OP_LE,
OP_GE
};
extern int
onig_builtin_cmp(OnigCalloutArgs* args, void* user_data ARG_UNUSED)
{
int r;
int slot;
long lv;
long rv;
OnigType type;
OnigValue val;
regex_t* reg;
enum OP_CMP op;
reg = args->regex;
r = onig_get_arg_by_callout_args(args, 0, &type, &val);
if (r != ONIG_NORMAL) return r;
if (type == ONIG_TYPE_TAG) {
r = onig_get_callout_data_by_callout_args(args, val.tag, 0, &type, &val);
if (r < ONIG_NORMAL) return r;
else if (r > ONIG_NORMAL)
lv = 0L;
else
lv = val.l;
}
else { /* ONIG_TYPE_LONG */
lv = val.l;
}
r = onig_get_arg_by_callout_args(args, 2, &type, &val);
if (r != ONIG_NORMAL) return r;
if (type == ONIG_TYPE_TAG) {
r = onig_get_callout_data_by_callout_args(args, val.tag, 0, &type, &val);
if (r < ONIG_NORMAL) return r;
else if (r > ONIG_NORMAL)
rv = 0L;
else
rv = val.l;
}
else { /* ONIG_TYPE_LONG */
rv = val.l;
}
slot = 0;
r = onig_get_callout_data_by_callout_args_self(args, slot, &type, &val);
if (r < ONIG_NORMAL)
return r;
else if (r > ONIG_NORMAL) {
/* type == void: initial state */
OnigCodePoint c1, c2;
UChar* p;
r = onig_get_arg_by_callout_args(args, 1, &type, &val);
if (r != ONIG_NORMAL) return r;
p = val.s.start;
c1 = ONIGENC_MBC_TO_CODE(reg->enc, p, val.s.end);
p += ONIGENC_MBC_ENC_LEN(reg->enc, p);
if (p < val.s.end) {
c2 = ONIGENC_MBC_TO_CODE(reg->enc, p, val.s.end);
p += ONIGENC_MBC_ENC_LEN(reg->enc, p);
if (p != val.s.end) return ONIGERR_INVALID_CALLOUT_ARG;
}
else
c2 = 0;
switch (c1) {
case '=':
if (c2 != '=') return ONIGERR_INVALID_CALLOUT_ARG;
op = OP_EQ;
break;
case '!':
if (c2 != '=') return ONIGERR_INVALID_CALLOUT_ARG;
op = OP_NE;
break;
case '<':
if (c2 == '=') op = OP_LE;
else if (c2 == 0) op = OP_LT;
else return ONIGERR_INVALID_CALLOUT_ARG;
break;
case '>':
if (c2 == '=') op = OP_GE;
else if (c2 == 0) op = OP_GT;
else return ONIGERR_INVALID_CALLOUT_ARG;
break;
default:
return ONIGERR_INVALID_CALLOUT_ARG;
break;
}
val.l = (long )op;
r = onig_set_callout_data_by_callout_args_self(args, slot, ONIG_TYPE_LONG, &val);
if (r != ONIG_NORMAL) return r;
}
else {
op = (enum OP_CMP )val.l;
}
switch (op) {
case OP_EQ: r = (lv == rv); break;
case OP_NE: r = (lv != rv); break;
case OP_LT: r = (lv < rv); break;
case OP_GT: r = (lv > rv); break;
case OP_LE: r = (lv <= rv); break;
case OP_GE: r = (lv >= rv); break;
}
return r == 0 ? ONIG_CALLOUT_FAIL : ONIG_CALLOUT_SUCCESS;
}
#include <stdio.h>
static FILE* OutFp;
/* name start with "onig_" for macros. */
static int
onig_builtin_monitor(OnigCalloutArgs* args, void* user_data)
{
int r;
int num;
size_t tag_len;
const UChar* start;
const UChar* right;
const UChar* current;
const UChar* string;
const UChar* strend;
const UChar* tag_start;
const UChar* tag_end;
regex_t* reg;
OnigCalloutIn in;
OnigType type;
OnigValue val;
char buf[20];
FILE* fp;
fp = OutFp;
r = onig_get_arg_by_callout_args(args, 0, &type, &val);
if (r != ONIG_NORMAL) return r;
in = onig_get_callout_in_by_callout_args(args);
if (in == ONIG_CALLOUT_IN_PROGRESS) {
if (val.c == '<')
return ONIG_CALLOUT_SUCCESS;
}
else {
if (val.c != 'X' && val.c != '<')
return ONIG_CALLOUT_SUCCESS;
}
num = onig_get_callout_num_by_callout_args(args);
start = onig_get_start_by_callout_args(args);
right = onig_get_right_range_by_callout_args(args);
current = onig_get_current_by_callout_args(args);
string = onig_get_string_by_callout_args(args);
strend = onig_get_string_end_by_callout_args(args);
reg = onig_get_regex_by_callout_args(args);
tag_start = onig_get_callout_tag_start(reg, num);
tag_end = onig_get_callout_tag_end(reg, num);
if (tag_start == 0)
xsnprintf(buf, sizeof(buf), "#%d", num);
else {
/* CAUTION: tag string is not terminated with NULL. */
int i;
tag_len = tag_end - tag_start;
if (tag_len >= sizeof(buf)) tag_len = sizeof(buf) - 1;
for (i = 0; i < tag_len; i++) buf[i] = tag_start[i];
buf[tag_len] = '\0';
}
fprintf(fp, "ONIG-MONITOR: %-4s %s at: %d [%d - %d] len: %d\n",
buf,
in == ONIG_CALLOUT_IN_PROGRESS ? "=>" : "<=",
(int )(current - string),
(int )(start - string),
(int )(right - string),
(int )(strend - string));
fflush(fp);
return ONIG_CALLOUT_SUCCESS;
}
extern int
onig_setup_builtin_monitors_by_ascii_encoded_name(void* fp /* FILE* */)
{
int id;
char* name;
OnigEncoding enc;
unsigned int ts[4];
OnigValue opts[4];
if (IS_NOT_NULL(fp))
OutFp = (FILE* )fp;
else
OutFp = stdout;
enc = ONIG_ENCODING_ASCII;
name = "MON";
ts[0] = ONIG_TYPE_CHAR;
opts[0].c = '>';
BC_B_O(name, monitor, 1, ts, 1, opts);
return ONIG_NORMAL;
}
#endif /* USE_CALLOUT */
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1277_0 |
crossvul-cpp_data_good_5240_4 | /**
* Test that the crafted TGA file doesn't trigger OOB reads.
*/
#include "gd.h"
#include "gdtest.h"
static size_t read_test_file(char **buffer, char *basename);
int main()
{
gdImagePtr im;
char *buffer;
size_t size;
size = read_test_file(&buffer, "heap_overflow.tga");
im = gdImageCreateFromTgaPtr(size, (void *) buffer);
gdTestAssert(im == NULL);
free(buffer);
return gdNumFailures();
}
static size_t read_test_file(char **buffer, char *basename)
{
char *filename;
FILE *fp;
size_t exp_size, act_size;
filename = gdTestFilePath2("tga", basename);
fp = fopen(filename, "rb");
gdTestAssert(fp != NULL);
fseek(fp, 0, SEEK_END);
exp_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
*buffer = malloc(exp_size);
gdTestAssert(*buffer != NULL);
act_size = fread(*buffer, sizeof(**buffer), exp_size, fp);
gdTestAssert(act_size == exp_size);
fclose(fp);
free(filename);
return act_size;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5240_4 |
crossvul-cpp_data_good_5341_0 | /*
* Copyright (C) 2006 Evgeniy Stepanov <eugeni.stepanov@gmail.com>
*
* This file is part of libass.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "config.h"
#include "ass_compat.h"
#include <assert.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
#include "ass_render.h"
#include "ass_parse.h"
#include "ass_shaper.h"
#define MAX_GLYPHS_INITIAL 1024
#define MAX_LINES_INITIAL 64
#define MAX_BITMAPS_INITIAL 16
#define MAX_SUB_BITMAPS_INITIAL 64
#define SUBPIXEL_MASK 63
#define SUBPIXEL_ACCURACY 7
ASS_Renderer *ass_renderer_init(ASS_Library *library)
{
int error;
FT_Library ft;
ASS_Renderer *priv = 0;
int vmajor, vminor, vpatch;
error = FT_Init_FreeType(&ft);
if (error) {
ass_msg(library, MSGL_FATAL, "%s failed", "FT_Init_FreeType");
goto ass_init_exit;
}
FT_Library_Version(ft, &vmajor, &vminor, &vpatch);
ass_msg(library, MSGL_V, "Raster: FreeType %d.%d.%d",
vmajor, vminor, vpatch);
priv = calloc(1, sizeof(ASS_Renderer));
if (!priv) {
FT_Done_FreeType(ft);
goto ass_init_exit;
}
priv->library = library;
priv->ftlibrary = ft;
// images_root and related stuff is zero-filled in calloc
#if (defined(__i386__) || defined(__x86_64__)) && CONFIG_ASM
if (has_avx2())
priv->engine = &ass_bitmap_engine_avx2;
else if (has_sse2())
priv->engine = &ass_bitmap_engine_sse2;
else
priv->engine = &ass_bitmap_engine_c;
#else
priv->engine = &ass_bitmap_engine_c;
#endif
#if CONFIG_RASTERIZER
rasterizer_init(&priv->rasterizer, 16);
#endif
priv->cache.font_cache = ass_font_cache_create();
priv->cache.bitmap_cache = ass_bitmap_cache_create();
priv->cache.composite_cache = ass_composite_cache_create();
priv->cache.outline_cache = ass_outline_cache_create();
priv->cache.glyph_max = GLYPH_CACHE_MAX;
priv->cache.bitmap_max_size = BITMAP_CACHE_MAX_SIZE;
priv->cache.composite_max_size = COMPOSITE_CACHE_MAX_SIZE;
priv->text_info.max_bitmaps = MAX_BITMAPS_INITIAL;
priv->text_info.max_glyphs = MAX_GLYPHS_INITIAL;
priv->text_info.max_lines = MAX_LINES_INITIAL;
priv->text_info.n_bitmaps = 0;
priv->text_info.combined_bitmaps = calloc(MAX_BITMAPS_INITIAL, sizeof(CombinedBitmapInfo));
priv->text_info.glyphs = calloc(MAX_GLYPHS_INITIAL, sizeof(GlyphInfo));
priv->text_info.lines = calloc(MAX_LINES_INITIAL, sizeof(LineInfo));
priv->settings.font_size_coeff = 1.;
priv->settings.selective_style_overrides = ASS_OVERRIDE_BIT_SELECTIVE_FONT_SCALE;
priv->shaper = ass_shaper_new(0);
ass_shaper_info(library);
#ifdef CONFIG_HARFBUZZ
priv->settings.shaper = ASS_SHAPING_COMPLEX;
#else
priv->settings.shaper = ASS_SHAPING_SIMPLE;
#endif
ass_init_exit:
if (priv)
ass_msg(library, MSGL_V, "Initialized");
else
ass_msg(library, MSGL_ERR, "Initialization failed");
return priv;
}
void ass_renderer_done(ASS_Renderer *render_priv)
{
ass_frame_unref(render_priv->images_root);
ass_frame_unref(render_priv->prev_images_root);
ass_cache_done(render_priv->cache.composite_cache);
ass_cache_done(render_priv->cache.bitmap_cache);
ass_cache_done(render_priv->cache.outline_cache);
ass_shaper_free(render_priv->shaper);
ass_cache_done(render_priv->cache.font_cache);
#if CONFIG_RASTERIZER
rasterizer_done(&render_priv->rasterizer);
#endif
if (render_priv->state.stroker) {
FT_Stroker_Done(render_priv->state.stroker);
render_priv->state.stroker = 0;
}
if (render_priv->fontselect)
ass_fontselect_free(render_priv->fontselect);
if (render_priv->ftlibrary)
FT_Done_FreeType(render_priv->ftlibrary);
free(render_priv->eimg);
free(render_priv->text_info.glyphs);
free(render_priv->text_info.lines);
free(render_priv->text_info.combined_bitmaps);
free(render_priv->settings.default_font);
free(render_priv->settings.default_family);
free(render_priv->user_override_style.FontName);
free(render_priv);
}
/**
* \brief Create a new ASS_Image
* Parameters are the same as ASS_Image fields.
*/
static ASS_Image *my_draw_bitmap(unsigned char *bitmap, int bitmap_w,
int bitmap_h, int stride, int dst_x,
int dst_y, uint32_t color,
CompositeHashValue *source)
{
ASS_ImagePriv *img = malloc(sizeof(ASS_ImagePriv));
if (!img) {
if (!source)
ass_aligned_free(bitmap);
return NULL;
}
img->result.w = bitmap_w;
img->result.h = bitmap_h;
img->result.stride = stride;
img->result.bitmap = bitmap;
img->result.color = color;
img->result.dst_x = dst_x;
img->result.dst_y = dst_y;
img->source = source;
ass_cache_inc_ref(source);
img->ref_count = 0;
return &img->result;
}
/**
* \brief Mapping between script and screen coordinates
*/
static double x2scr_pos(ASS_Renderer *render_priv, double x)
{
return x * render_priv->orig_width / render_priv->font_scale_x / render_priv->track->PlayResX +
render_priv->settings.left_margin;
}
static double x2scr(ASS_Renderer *render_priv, double x)
{
if (render_priv->state.explicit)
return x2scr_pos(render_priv, x);
return x * render_priv->orig_width_nocrop / render_priv->font_scale_x /
render_priv->track->PlayResX +
FFMAX(render_priv->settings.left_margin, 0);
}
static double x2scr_pos_scaled(ASS_Renderer *render_priv, double x)
{
return x * render_priv->orig_width / render_priv->track->PlayResX +
render_priv->settings.left_margin;
}
static double x2scr_scaled(ASS_Renderer *render_priv, double x)
{
if (render_priv->state.explicit)
return x2scr_pos_scaled(render_priv, x);
return x * render_priv->orig_width_nocrop /
render_priv->track->PlayResX +
FFMAX(render_priv->settings.left_margin, 0);
}
/**
* \brief Mapping between script and screen coordinates
*/
static double y2scr_pos(ASS_Renderer *render_priv, double y)
{
return y * render_priv->orig_height / render_priv->track->PlayResY +
render_priv->settings.top_margin;
}
static double y2scr(ASS_Renderer *render_priv, double y)
{
if (render_priv->state.explicit)
return y2scr_pos(render_priv, y);
return y * render_priv->orig_height_nocrop /
render_priv->track->PlayResY +
FFMAX(render_priv->settings.top_margin, 0);
}
// the same for toptitles
static double y2scr_top(ASS_Renderer *render_priv, double y)
{
if (render_priv->state.explicit)
return y2scr_pos(render_priv, y);
if (render_priv->settings.use_margins)
return y * render_priv->orig_height_nocrop /
render_priv->track->PlayResY;
else
return y * render_priv->orig_height_nocrop /
render_priv->track->PlayResY +
FFMAX(render_priv->settings.top_margin, 0);
}
// the same for subtitles
static double y2scr_sub(ASS_Renderer *render_priv, double y)
{
if (render_priv->state.explicit)
return y2scr_pos(render_priv, y);
if (render_priv->settings.use_margins)
return y * render_priv->orig_height_nocrop /
render_priv->track->PlayResY +
FFMAX(render_priv->settings.top_margin, 0)
+ FFMAX(render_priv->settings.bottom_margin, 0);
else
return y * render_priv->orig_height_nocrop /
render_priv->track->PlayResY +
FFMAX(render_priv->settings.top_margin, 0);
}
/*
* \brief Convert bitmap glyphs into ASS_Image list with inverse clipping
*
* Inverse clipping with the following strategy:
* - find rectangle from (x0, y0) to (cx0, y1)
* - find rectangle from (cx0, y0) to (cx1, cy0)
* - find rectangle from (cx0, cy1) to (cx1, y1)
* - find rectangle from (cx1, y0) to (x1, y1)
* These rectangles can be invalid and in this case are discarded.
* Afterwards, they are clipped against the screen coordinates.
* In an additional pass, the rectangles need to be split up left/right for
* karaoke effects. This can result in a lot of bitmaps (6 to be exact).
*/
static ASS_Image **render_glyph_i(ASS_Renderer *render_priv,
Bitmap *bm, int dst_x, int dst_y,
uint32_t color, uint32_t color2, int brk,
ASS_Image **tail, unsigned type,
CompositeHashValue *source)
{
int i, j, x0, y0, x1, y1, cx0, cy0, cx1, cy1, sx, sy, zx, zy;
Rect r[4];
ASS_Image *img;
dst_x += bm->left;
dst_y += bm->top;
// we still need to clip against screen boundaries
zx = x2scr_pos_scaled(render_priv, 0);
zy = y2scr_pos(render_priv, 0);
sx = x2scr_pos_scaled(render_priv, render_priv->track->PlayResX);
sy = y2scr_pos(render_priv, render_priv->track->PlayResY);
x0 = 0;
y0 = 0;
x1 = bm->w;
y1 = bm->h;
cx0 = render_priv->state.clip_x0 - dst_x;
cy0 = render_priv->state.clip_y0 - dst_y;
cx1 = render_priv->state.clip_x1 - dst_x;
cy1 = render_priv->state.clip_y1 - dst_y;
// calculate rectangles and discard invalid ones while we're at it.
i = 0;
r[i].x0 = x0;
r[i].y0 = y0;
r[i].x1 = (cx0 > x1) ? x1 : cx0;
r[i].y1 = y1;
if (r[i].x1 > r[i].x0 && r[i].y1 > r[i].y0) i++;
r[i].x0 = (cx0 < 0) ? x0 : cx0;
r[i].y0 = y0;
r[i].x1 = (cx1 > x1) ? x1 : cx1;
r[i].y1 = (cy0 > y1) ? y1 : cy0;
if (r[i].x1 > r[i].x0 && r[i].y1 > r[i].y0) i++;
r[i].x0 = (cx0 < 0) ? x0 : cx0;
r[i].y0 = (cy1 < 0) ? y0 : cy1;
r[i].x1 = (cx1 > x1) ? x1 : cx1;
r[i].y1 = y1;
if (r[i].x1 > r[i].x0 && r[i].y1 > r[i].y0) i++;
r[i].x0 = (cx1 < 0) ? x0 : cx1;
r[i].y0 = y0;
r[i].x1 = x1;
r[i].y1 = y1;
if (r[i].x1 > r[i].x0 && r[i].y1 > r[i].y0) i++;
// clip each rectangle to screen coordinates
for (j = 0; j < i; j++) {
r[j].x0 = (r[j].x0 + dst_x < zx) ? zx - dst_x : r[j].x0;
r[j].y0 = (r[j].y0 + dst_y < zy) ? zy - dst_y : r[j].y0;
r[j].x1 = (r[j].x1 + dst_x > sx) ? sx - dst_x : r[j].x1;
r[j].y1 = (r[j].y1 + dst_y > sy) ? sy - dst_y : r[j].y1;
}
// draw the rectangles
for (j = 0; j < i; j++) {
int lbrk = brk;
// kick out rectangles that are invalid now
if (r[j].x1 <= r[j].x0 || r[j].y1 <= r[j].y0)
continue;
// split up into left and right for karaoke, if needed
if (lbrk > r[j].x0) {
if (lbrk > r[j].x1) lbrk = r[j].x1;
img = my_draw_bitmap(bm->buffer + r[j].y0 * bm->stride + r[j].x0,
lbrk - r[j].x0, r[j].y1 - r[j].y0, bm->stride,
dst_x + r[j].x0, dst_y + r[j].y0, color, source);
if (!img) break;
img->type = type;
*tail = img;
tail = &img->next;
}
if (lbrk < r[j].x1) {
if (lbrk < r[j].x0) lbrk = r[j].x0;
img = my_draw_bitmap(bm->buffer + r[j].y0 * bm->stride + lbrk,
r[j].x1 - lbrk, r[j].y1 - r[j].y0, bm->stride,
dst_x + lbrk, dst_y + r[j].y0, color2, source);
if (!img) break;
img->type = type;
*tail = img;
tail = &img->next;
}
}
return tail;
}
/**
* \brief convert bitmap glyph into ASS_Image struct(s)
* \param bit freetype bitmap glyph, FT_PIXEL_MODE_GRAY
* \param dst_x bitmap x coordinate in video frame
* \param dst_y bitmap y coordinate in video frame
* \param color first color, RGBA
* \param color2 second color, RGBA
* \param brk x coordinate relative to glyph origin, color is used to the left of brk, color2 - to the right
* \param tail pointer to the last image's next field, head of the generated list should be stored here
* \return pointer to the new list tail
* Performs clipping. Uses my_draw_bitmap for actual bitmap convertion.
*/
static ASS_Image **
render_glyph(ASS_Renderer *render_priv, Bitmap *bm, int dst_x, int dst_y,
uint32_t color, uint32_t color2, int brk, ASS_Image **tail,
unsigned type, CompositeHashValue *source)
{
// Inverse clipping in use?
if (render_priv->state.clip_mode)
return render_glyph_i(render_priv, bm, dst_x, dst_y, color, color2,
brk, tail, type, source);
// brk is relative to dst_x
// color = color left of brk
// color2 = color right of brk
int b_x0, b_y0, b_x1, b_y1; // visible part of the bitmap
int clip_x0, clip_y0, clip_x1, clip_y1;
int tmp;
ASS_Image *img;
dst_x += bm->left;
dst_y += bm->top;
brk -= bm->left;
// clipping
clip_x0 = FFMINMAX(render_priv->state.clip_x0, 0, render_priv->width);
clip_y0 = FFMINMAX(render_priv->state.clip_y0, 0, render_priv->height);
clip_x1 = FFMINMAX(render_priv->state.clip_x1, 0, render_priv->width);
clip_y1 = FFMINMAX(render_priv->state.clip_y1, 0, render_priv->height);
b_x0 = 0;
b_y0 = 0;
b_x1 = bm->w;
b_y1 = bm->h;
tmp = dst_x - clip_x0;
if (tmp < 0) {
b_x0 = -tmp;
render_priv->state.has_clips = 1;
}
tmp = dst_y - clip_y0;
if (tmp < 0) {
b_y0 = -tmp;
render_priv->state.has_clips = 1;
}
tmp = clip_x1 - dst_x - bm->w;
if (tmp < 0) {
b_x1 = bm->w + tmp;
render_priv->state.has_clips = 1;
}
tmp = clip_y1 - dst_y - bm->h;
if (tmp < 0) {
b_y1 = bm->h + tmp;
render_priv->state.has_clips = 1;
}
if ((b_y0 >= b_y1) || (b_x0 >= b_x1))
return tail;
if (brk > b_x0) { // draw left part
if (brk > b_x1)
brk = b_x1;
img = my_draw_bitmap(bm->buffer + bm->stride * b_y0 + b_x0,
brk - b_x0, b_y1 - b_y0, bm->stride,
dst_x + b_x0, dst_y + b_y0, color, source);
if (!img) return tail;
img->type = type;
*tail = img;
tail = &img->next;
}
if (brk < b_x1) { // draw right part
if (brk < b_x0)
brk = b_x0;
img = my_draw_bitmap(bm->buffer + bm->stride * b_y0 + brk,
b_x1 - brk, b_y1 - b_y0, bm->stride,
dst_x + brk, dst_y + b_y0, color2, source);
if (!img) return tail;
img->type = type;
*tail = img;
tail = &img->next;
}
return tail;
}
// Calculate bitmap memory footprint
static inline size_t bitmap_size(Bitmap *bm)
{
return bm ? sizeof(Bitmap) + bm->stride * bm->h : 0;
}
/**
* Iterate through a list of bitmaps and blend with clip vector, if
* applicable. The blended bitmaps are added to a free list which is freed
* at the start of a new frame.
*/
static void blend_vector_clip(ASS_Renderer *render_priv,
ASS_Image *head)
{
ASS_Drawing *drawing = render_priv->state.clip_drawing;
if (!drawing)
return;
// Try to get mask from cache
BitmapHashKey key;
memset(&key, 0, sizeof(key));
key.type = BITMAP_CLIP;
key.u.clip.text = drawing->text;
BitmapHashValue *val;
if (!ass_cache_get(render_priv->cache.bitmap_cache, &key, &val)) {
if (!val)
return;
val->bm = val->bm_o = NULL;
// Not found in cache, parse and rasterize it
ASS_Outline *outline = ass_drawing_parse(drawing, 1);
if (!outline) {
ass_msg(render_priv->library, MSGL_WARN,
"Clip vector parsing failed. Skipping.");
ass_cache_commit(val, sizeof(BitmapHashKey) + sizeof(BitmapHashValue));
ass_cache_dec_ref(val);
return;
}
// We need to translate the clip according to screen borders
if (render_priv->settings.left_margin != 0 ||
render_priv->settings.top_margin != 0) {
FT_Vector trans = {
.x = int_to_d6(render_priv->settings.left_margin),
.y = -int_to_d6(render_priv->settings.top_margin),
};
outline_translate(outline, trans.x, trans.y);
}
val->bm = outline_to_bitmap(render_priv, outline, 0);
ass_cache_commit(val, bitmap_size(val->bm) +
sizeof(BitmapHashKey) + sizeof(BitmapHashValue));
}
Bitmap *clip_bm = val->bm;
if (!clip_bm) {
ass_cache_dec_ref(val);
return;
}
// Iterate through bitmaps and blend/clip them
for (ASS_Image *cur = head; cur; cur = cur->next) {
int left, top, right, bottom, w, h;
int ax, ay, aw, ah, as;
int bx, by, bw, bh, bs;
int aleft, atop, bleft, btop;
unsigned char *abuffer, *bbuffer, *nbuffer;
render_priv->state.has_clips = 1;
abuffer = cur->bitmap;
bbuffer = clip_bm->buffer;
ax = cur->dst_x;
ay = cur->dst_y;
aw = cur->w;
ah = cur->h;
as = cur->stride;
bx = clip_bm->left;
by = clip_bm->top;
bw = clip_bm->w;
bh = clip_bm->h;
bs = clip_bm->stride;
// Calculate overlap coordinates
left = (ax > bx) ? ax : bx;
top = (ay > by) ? ay : by;
right = ((ax + aw) < (bx + bw)) ? (ax + aw) : (bx + bw);
bottom = ((ay + ah) < (by + bh)) ? (ay + ah) : (by + bh);
aleft = left - ax;
atop = top - ay;
w = right - left;
h = bottom - top;
bleft = left - bx;
btop = top - by;
if (render_priv->state.clip_drawing_mode) {
// Inverse clip
if (ax + aw < bx || ay + ah < by || ax > bx + bw ||
ay > by + bh || !h || !w) {
continue;
}
// Allocate new buffer and add to free list
nbuffer = ass_aligned_alloc(32, as * ah, false);
if (!nbuffer)
break;
// Blend together
memcpy(nbuffer, abuffer, ((ah - 1) * as) + aw);
render_priv->engine->sub_bitmaps(nbuffer + atop * as + aleft, as,
bbuffer + btop * bs + bleft, bs,
h, w);
} else {
// Regular clip
if (ax + aw < bx || ay + ah < by || ax > bx + bw ||
ay > by + bh || !h || !w) {
cur->w = cur->h = cur->stride = 0;
continue;
}
// Allocate new buffer and add to free list
unsigned align = (w >= 16) ? 16 : ((w >= 8) ? 8 : 1);
unsigned ns = ass_align(align, w);
nbuffer = ass_aligned_alloc(align, ns * h, false);
if (!nbuffer)
break;
// Blend together
render_priv->engine->mul_bitmaps(nbuffer, ns,
abuffer + atop * as + aleft, as,
bbuffer + btop * bs + bleft, bs,
w, h);
cur->dst_x += aleft;
cur->dst_y += atop;
cur->w = w;
cur->h = h;
cur->stride = ns;
}
cur->bitmap = nbuffer;
ASS_ImagePriv *priv = (ASS_ImagePriv *) cur;
ass_cache_dec_ref(priv->source);
priv->source = NULL;
}
ass_cache_dec_ref(val);
}
/**
* \brief Convert TextInfo struct to ASS_Image list
* Splits glyphs in halves when needed (for \kf karaoke).
*/
static ASS_Image *render_text(ASS_Renderer *render_priv)
{
ASS_Image *head;
ASS_Image **tail = &head;
unsigned n_bitmaps = render_priv->text_info.n_bitmaps;
CombinedBitmapInfo *bitmaps = render_priv->text_info.combined_bitmaps;
for (unsigned i = 0; i < n_bitmaps; i++) {
CombinedBitmapInfo *info = &bitmaps[i];
if (!info->bm_s || render_priv->state.border_style == 4)
continue;
tail =
render_glyph(render_priv, info->bm_s, info->x, info->y, info->c[3], 0,
1000000, tail, IMAGE_TYPE_SHADOW, info->image);
}
for (unsigned i = 0; i < n_bitmaps; i++) {
CombinedBitmapInfo *info = &bitmaps[i];
if (!info->bm_o)
continue;
if ((info->effect_type == EF_KARAOKE_KO)
&& (info->effect_timing <= info->first_pos_x)) {
// do nothing
} else {
tail =
render_glyph(render_priv, info->bm_o, info->x, info->y, info->c[2],
0, 1000000, tail, IMAGE_TYPE_OUTLINE, info->image);
}
}
for (unsigned i = 0; i < n_bitmaps; i++) {
CombinedBitmapInfo *info = &bitmaps[i];
if (!info->bm)
continue;
if ((info->effect_type == EF_KARAOKE)
|| (info->effect_type == EF_KARAOKE_KO)) {
if (info->effect_timing > info->first_pos_x)
tail =
render_glyph(render_priv, info->bm, info->x, info->y,
info->c[0], 0, 1000000, tail,
IMAGE_TYPE_CHARACTER, info->image);
else
tail =
render_glyph(render_priv, info->bm, info->x, info->y,
info->c[1], 0, 1000000, tail,
IMAGE_TYPE_CHARACTER, info->image);
} else if (info->effect_type == EF_KARAOKE_KF) {
tail =
render_glyph(render_priv, info->bm, info->x, info->y, info->c[0],
info->c[1], info->effect_timing, tail,
IMAGE_TYPE_CHARACTER, info->image);
} else
tail =
render_glyph(render_priv, info->bm, info->x, info->y, info->c[0],
0, 1000000, tail, IMAGE_TYPE_CHARACTER, info->image);
}
for (unsigned i = 0; i < n_bitmaps; i++)
ass_cache_dec_ref(bitmaps[i].image);
*tail = 0;
blend_vector_clip(render_priv, head);
return head;
}
static void compute_string_bbox(TextInfo *text, DBBox *bbox)
{
int i;
if (text->length > 0) {
bbox->xMin = 32000;
bbox->xMax = -32000;
bbox->yMin = -1 * text->lines[0].asc + d6_to_double(text->glyphs[0].pos.y);
bbox->yMax = text->height - text->lines[0].asc +
d6_to_double(text->glyphs[0].pos.y);
for (i = 0; i < text->length; ++i) {
GlyphInfo *info = text->glyphs + i;
if (info->skip) continue;
double s = d6_to_double(info->pos.x);
double e = s + d6_to_double(info->cluster_advance.x);
bbox->xMin = FFMIN(bbox->xMin, s);
bbox->xMax = FFMAX(bbox->xMax, e);
}
} else
bbox->xMin = bbox->xMax = bbox->yMin = bbox->yMax = 0.;
}
static ASS_Style *handle_selective_style_overrides(ASS_Renderer *render_priv,
ASS_Style *rstyle)
{
// The script style is the one the event was declared with.
ASS_Style *script = render_priv->track->styles +
render_priv->state.event->Style;
// The user style was set with ass_set_selective_style_override().
ASS_Style *user = &render_priv->user_override_style;
ASS_Style *new = &render_priv->state.override_style_temp_storage;
int explicit = event_has_hard_overrides(render_priv->state.event->Text) ||
render_priv->state.evt_type != EVENT_NORMAL;
int requested = render_priv->settings.selective_style_overrides;
double scale;
user->Name = "OverrideStyle"; // name insignificant
// Either the event's style, or the style forced with a \r tag.
if (!rstyle)
rstyle = script;
// Create a new style that contains a mix of the original style and
// user_style (the user's override style). Copy only fields from the
// script's style that are deemed necessary.
*new = *rstyle;
render_priv->state.explicit = explicit;
render_priv->state.apply_font_scale =
!explicit || !(requested & ASS_OVERRIDE_BIT_SELECTIVE_FONT_SCALE);
// On positioned events, do not apply most overrides.
if (explicit)
requested = 0;
if (requested & ASS_OVERRIDE_BIT_STYLE)
requested |= ASS_OVERRIDE_BIT_FONT_NAME |
ASS_OVERRIDE_BIT_FONT_SIZE_FIELDS |
ASS_OVERRIDE_BIT_COLORS |
ASS_OVERRIDE_BIT_BORDER |
ASS_OVERRIDE_BIT_ATTRIBUTES;
// Copies fields even not covered by any of the other bits.
if (requested & ASS_OVERRIDE_FULL_STYLE)
*new = *user;
// The user style is supposed to be independent of the script resolution.
// Treat the user style's values as if they were specified for a script with
// PlayResY=288, and rescale the values to the current script.
scale = render_priv->track->PlayResY / 288.0;
if (requested & ASS_OVERRIDE_BIT_FONT_SIZE_FIELDS) {
new->FontSize = user->FontSize * scale;
new->Spacing = user->Spacing * scale;
new->ScaleX = user->ScaleX;
new->ScaleY = user->ScaleY;
}
if (requested & ASS_OVERRIDE_BIT_FONT_NAME) {
new->FontName = user->FontName;
new->treat_fontname_as_pattern = user->treat_fontname_as_pattern;
}
if (requested & ASS_OVERRIDE_BIT_COLORS) {
new->PrimaryColour = user->PrimaryColour;
new->SecondaryColour = user->SecondaryColour;
new->OutlineColour = user->OutlineColour;
new->BackColour = user->BackColour;
}
if (requested & ASS_OVERRIDE_BIT_ATTRIBUTES) {
new->Bold = user->Bold;
new->Italic = user->Italic;
new->Underline = user->Underline;
new->StrikeOut = user->StrikeOut;
}
if (requested & ASS_OVERRIDE_BIT_BORDER) {
new->BorderStyle = user->BorderStyle;
new->Outline = user->Outline * scale;
new->Shadow = user->Shadow * scale;
}
if (requested & ASS_OVERRIDE_BIT_ALIGNMENT)
new->Alignment = user->Alignment;
if (requested & ASS_OVERRIDE_BIT_MARGINS) {
new->MarginL = user->MarginL;
new->MarginR = user->MarginR;
new->MarginV = user->MarginV;
}
if (!new->FontName)
new->FontName = rstyle->FontName;
render_priv->state.style = new;
render_priv->state.overrides = requested;
return new;
}
static void init_font_scale(ASS_Renderer *render_priv)
{
ASS_Settings *settings_priv = &render_priv->settings;
render_priv->font_scale = ((double) render_priv->orig_height) /
render_priv->track->PlayResY;
if (settings_priv->storage_height)
render_priv->blur_scale = ((double) render_priv->orig_height) /
settings_priv->storage_height;
else
render_priv->blur_scale = 1.;
if (render_priv->track->ScaledBorderAndShadow)
render_priv->border_scale =
((double) render_priv->orig_height) /
render_priv->track->PlayResY;
else
render_priv->border_scale = render_priv->blur_scale;
if (!settings_priv->storage_height)
render_priv->blur_scale = render_priv->border_scale;
if (render_priv->state.apply_font_scale) {
render_priv->font_scale *= settings_priv->font_size_coeff;
render_priv->border_scale *= settings_priv->font_size_coeff;
render_priv->blur_scale *= settings_priv->font_size_coeff;
}
}
/**
* \brief partially reset render_context to style values
* Works like {\r}: resets some style overrides
*/
void reset_render_context(ASS_Renderer *render_priv, ASS_Style *style)
{
style = handle_selective_style_overrides(render_priv, style);
init_font_scale(render_priv);
render_priv->state.c[0] = style->PrimaryColour;
render_priv->state.c[1] = style->SecondaryColour;
render_priv->state.c[2] = style->OutlineColour;
render_priv->state.c[3] = style->BackColour;
render_priv->state.flags =
(style->Underline ? DECO_UNDERLINE : 0) |
(style->StrikeOut ? DECO_STRIKETHROUGH : 0);
render_priv->state.font_size = style->FontSize;
free(render_priv->state.family);
render_priv->state.family = NULL;
render_priv->state.family = strdup(style->FontName);
render_priv->state.treat_family_as_pattern =
style->treat_fontname_as_pattern;
render_priv->state.bold = style->Bold;
render_priv->state.italic = style->Italic;
update_font(render_priv);
render_priv->state.border_style = style->BorderStyle;
render_priv->state.border_x = style->Outline;
render_priv->state.border_y = style->Outline;
change_border(render_priv, render_priv->state.border_x, render_priv->state.border_y);
render_priv->state.scale_x = style->ScaleX;
render_priv->state.scale_y = style->ScaleY;
render_priv->state.hspacing = style->Spacing;
render_priv->state.be = 0;
render_priv->state.blur = style->Blur;
render_priv->state.shadow_x = style->Shadow;
render_priv->state.shadow_y = style->Shadow;
render_priv->state.frx = render_priv->state.fry = 0.;
render_priv->state.frz = M_PI * style->Angle / 180.;
render_priv->state.fax = render_priv->state.fay = 0.;
render_priv->state.font_encoding = style->Encoding;
}
/**
* \brief Start new event. Reset render_priv->state.
*/
static void
init_render_context(ASS_Renderer *render_priv, ASS_Event *event)
{
render_priv->state.event = event;
render_priv->state.parsed_tags = 0;
render_priv->state.has_clips = 0;
render_priv->state.evt_type = EVENT_NORMAL;
reset_render_context(render_priv, NULL);
render_priv->state.wrap_style = render_priv->track->WrapStyle;
render_priv->state.alignment = render_priv->state.style->Alignment;
render_priv->state.pos_x = 0;
render_priv->state.pos_y = 0;
render_priv->state.org_x = 0;
render_priv->state.org_y = 0;
render_priv->state.have_origin = 0;
render_priv->state.clip_x0 = 0;
render_priv->state.clip_y0 = 0;
render_priv->state.clip_x1 = render_priv->track->PlayResX;
render_priv->state.clip_y1 = render_priv->track->PlayResY;
render_priv->state.clip_mode = 0;
render_priv->state.detect_collisions = 1;
render_priv->state.fade = 0;
render_priv->state.drawing_scale = 0;
render_priv->state.pbo = 0;
render_priv->state.effect_type = EF_NONE;
render_priv->state.effect_timing = 0;
render_priv->state.effect_skip_timing = 0;
apply_transition_effects(render_priv, event);
}
static void free_render_context(ASS_Renderer *render_priv)
{
ass_cache_dec_ref(render_priv->state.font);
free(render_priv->state.family);
ass_drawing_free(render_priv->state.clip_drawing);
render_priv->state.font = NULL;
render_priv->state.family = NULL;
render_priv->state.clip_drawing = NULL;
TextInfo *text_info = &render_priv->text_info;
for (int n = 0; n < text_info->length; n++)
ass_drawing_free(text_info->glyphs[n].drawing);
text_info->length = 0;
}
/*
* Replace the outline of a glyph by a contour which makes up a simple
* opaque rectangle.
*/
static void draw_opaque_box(ASS_Renderer *render_priv, GlyphInfo *info,
int asc, int desc, ASS_Outline *ol,
FT_Vector advance, int sx, int sy)
{
int adv = advance.x;
double scale_y = info->orig_scale_y;
double scale_x = info->orig_scale_x;
// to avoid gaps
sx = FFMAX(64, sx);
sy = FFMAX(64, sy);
// Emulate the WTFish behavior of VSFilter, i.e. double-scale
// the sizes of the opaque box.
adv += double_to_d6(info->hspacing * render_priv->font_scale * scale_x);
adv *= scale_x;
sx *= scale_x;
sy *= scale_y;
desc *= scale_y;
desc += asc * (scale_y - 1.0);
FT_Vector points[4] = {
{ .x = -sx, .y = asc + sy },
{ .x = adv + sx, .y = asc + sy },
{ .x = adv + sx, .y = -desc - sy },
{ .x = -sx, .y = -desc - sy },
};
ol->n_points = ol->n_contours = 0;
if (!outline_alloc(ol, 4, 1))
return;
for (int i = 0; i < 4; ++i) {
ol->points[ol->n_points] = points[i];
ol->tags[ol->n_points++] = 1;
}
ol->contours[ol->n_contours++] = ol->n_points - 1;
}
/*
* Stroke an outline glyph in x/y direction. Applies various fixups to get
* around limitations of the FreeType stroker.
*/
static void stroke_outline(ASS_Renderer *render_priv, ASS_Outline *outline,
int sx, int sy)
{
if (sx <= 0 && sy <= 0)
return;
fix_freetype_stroker(outline, sx, sy);
size_t n_points = outline->n_points;
if (n_points > SHRT_MAX) {
ass_msg(render_priv->library, MSGL_WARN, "Too many outline points: %d",
outline->n_points);
n_points = SHRT_MAX;
}
size_t n_contours = FFMIN(outline->n_contours, SHRT_MAX);
short contours_small[EFFICIENT_CONTOUR_COUNT];
short *contours = contours_small;
short *contours_large = NULL;
if (n_contours > EFFICIENT_CONTOUR_COUNT) {
contours_large = malloc(n_contours * sizeof(short));
if (!contours_large)
return;
contours = contours_large;
}
for (size_t i = 0; i < n_contours; ++i)
contours[i] = FFMIN(outline->contours[i], n_points - 1);
FT_Outline ftol;
ftol.n_points = n_points;
ftol.n_contours = n_contours;
ftol.points = outline->points;
ftol.tags = outline->tags;
ftol.contours = contours;
ftol.flags = 0;
// Borders are equal; use the regular stroker
if (sx == sy && render_priv->state.stroker) {
int error;
FT_StrokerBorder border = FT_Outline_GetOutsideBorder(&ftol);
error = FT_Stroker_ParseOutline(render_priv->state.stroker, &ftol, 0);
if (error) {
ass_msg(render_priv->library, MSGL_WARN,
"FT_Stroker_ParseOutline failed, error: %d", error);
}
unsigned new_points, new_contours;
error = FT_Stroker_GetBorderCounts(render_priv->state.stroker, border,
&new_points, &new_contours);
if (error) {
ass_msg(render_priv->library, MSGL_WARN,
"FT_Stroker_GetBorderCounts failed, error: %d", error);
}
outline_free(outline);
outline->n_points = outline->n_contours = 0;
if (new_contours > FFMAX(EFFICIENT_CONTOUR_COUNT, n_contours)) {
if (!ASS_REALLOC_ARRAY(contours_large, new_contours)) {
free(contours_large);
return;
}
}
n_points = new_points;
n_contours = new_contours;
if (!outline_alloc(outline, n_points, n_contours)) {
ass_msg(render_priv->library, MSGL_WARN,
"Not enough memory for border outline");
free(contours_large);
return;
}
ftol.n_points = ftol.n_contours = 0;
ftol.points = outline->points;
ftol.tags = outline->tags;
FT_Stroker_ExportBorder(render_priv->state.stroker, border, &ftol);
outline->n_points = n_points;
outline->n_contours = n_contours;
for (size_t i = 0; i < n_contours; ++i)
outline->contours[i] = (unsigned short) contours[i];
// "Stroke" with the outline emboldener (in two passes if needed).
// The outlines look uglier, but the emboldening never adds any points
} else {
#if (FREETYPE_MAJOR > 2) || \
((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR > 4)) || \
((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR == 4) && (FREETYPE_PATCH >= 10))
FT_Outline_EmboldenXY(&ftol, sx * 2, sy * 2);
FT_Outline_Translate(&ftol, -sx, -sy);
#else
int i;
FT_Outline nol;
FT_Outline_New(render_priv->ftlibrary, ftol.n_points,
ftol.n_contours, &nol);
FT_Outline_Copy(&ftol, &nol);
FT_Outline_Embolden(&ftol, sx * 2);
FT_Outline_Translate(&ftol, -sx, -sx);
FT_Outline_Embolden(&nol, sy * 2);
FT_Outline_Translate(&nol, -sy, -sy);
for (i = 0; i < ftol.n_points; i++)
ftol.points[i].y = nol.points[i].y;
FT_Outline_Done(render_priv->ftlibrary, &nol);
#endif
}
free(contours_large);
}
/**
* \brief Prepare glyph hash
*/
static void
fill_glyph_hash(ASS_Renderer *priv, OutlineHashKey *outline_key,
GlyphInfo *info)
{
if (info->drawing) {
DrawingHashKey *key = &outline_key->u.drawing;
outline_key->type = OUTLINE_DRAWING;
key->scale_x = double_to_d16(info->scale_x);
key->scale_y = double_to_d16(info->scale_y);
key->outline.x = double_to_d16(info->border_x);
key->outline.y = double_to_d16(info->border_y);
key->border_style = info->border_style;
// hpacing only matters for opaque box borders (see draw_opaque_box),
// so for normal borders, maximize cache utility by ignoring it
key->hspacing =
info->border_style == 3 ? double_to_d16(info->hspacing) : 0;
key->hash = info->drawing->hash;
key->text = info->drawing->text;
key->pbo = info->drawing->pbo;
key->scale = info->drawing->scale;
} else {
GlyphHashKey *key = &outline_key->u.glyph;
outline_key->type = OUTLINE_GLYPH;
key->font = info->font;
key->size = info->font_size;
key->face_index = info->face_index;
key->glyph_index = info->glyph_index;
key->bold = info->bold;
key->italic = info->italic;
key->scale_x = double_to_d16(info->scale_x);
key->scale_y = double_to_d16(info->scale_y);
key->outline.x = double_to_d16(info->border_x);
key->outline.y = double_to_d16(info->border_y);
key->flags = info->flags;
key->border_style = info->border_style;
key->hspacing =
info->border_style == 3 ? double_to_d16(info->hspacing) : 0;
}
}
/**
* \brief Prepare combined-bitmap hash
*/
static void fill_composite_hash(CompositeHashKey *hk, CombinedBitmapInfo *info)
{
hk->filter = info->filter;
hk->bitmap_count = info->bitmap_count;
hk->bitmaps = info->bitmaps;
}
/**
* \brief Get normal and outline (border) glyphs
* \param info out: struct filled with extracted data
* Tries to get both glyphs from cache.
* If they can't be found, gets a glyph from font face, generates outline with FT_Stroker,
* and add them to cache.
* The glyphs are returned in info->glyph and info->outline_glyph
*/
static void
get_outline_glyph(ASS_Renderer *priv, GlyphInfo *info)
{
memset(&info->hash_key, 0, sizeof(info->hash_key));
OutlineHashKey key;
OutlineHashValue *val;
fill_glyph_hash(priv, &key, info);
if (!ass_cache_get(priv->cache.outline_cache, &key, &val)) {
if (!val)
return;
memset(val, 0, sizeof(*val));
if (info->drawing) {
ASS_Drawing *drawing = info->drawing;
ass_drawing_hash(drawing);
if(!ass_drawing_parse(drawing, 0)) {
ass_cache_commit(val, 1);
ass_cache_dec_ref(val);
return;
}
val->outline = outline_copy(&drawing->outline);
val->advance.x = drawing->advance.x;
val->advance.y = drawing->advance.y;
val->asc = drawing->asc;
val->desc = drawing->desc;
} else {
ass_face_set_size(info->font->faces[info->face_index],
info->font_size);
ass_font_set_transform(info->font, info->scale_x,
info->scale_y, NULL);
FT_Glyph glyph =
ass_font_get_glyph(info->font,
info->symbol, info->face_index, info->glyph_index,
priv->settings.hinting, info->flags);
if (glyph != NULL) {
val->outline = outline_convert(&((FT_OutlineGlyph) glyph)->outline);
if (priv->settings.shaper == ASS_SHAPING_SIMPLE) {
val->advance.x = d16_to_d6(glyph->advance.x);
val->advance.y = d16_to_d6(glyph->advance.y);
}
FT_Done_Glyph(glyph);
ass_font_get_asc_desc(info->font, info->symbol,
&val->asc, &val->desc);
val->asc *= info->scale_y;
val->desc *= info->scale_y;
}
}
if (!val->outline) {
ass_cache_commit(val, 1);
ass_cache_dec_ref(val);
return;
}
outline_get_cbox(val->outline, &val->bbox_scaled);
if (info->border_style == 3) {
val->border = calloc(1, sizeof(ASS_Outline));
if (!val->border) {
outline_free(val->outline);
free(val->outline);
val->outline = NULL;
ass_cache_commit(val, 1);
ass_cache_dec_ref(val);
return;
}
FT_Vector advance;
if (priv->settings.shaper == ASS_SHAPING_SIMPLE || info->drawing)
advance = val->advance;
else
advance = info->advance;
draw_opaque_box(priv, info, val->asc, val->desc, val->border, advance,
double_to_d6(info->border_x * priv->border_scale),
double_to_d6(info->border_y * priv->border_scale));
} else if ((info->border_x > 0 || info->border_y > 0)
&& double_to_d6(info->scale_x) && double_to_d6(info->scale_y)) {
change_border(priv, info->border_x, info->border_y);
val->border = outline_copy(val->outline);
stroke_outline(priv, val->border,
double_to_d6(info->border_x * priv->border_scale),
double_to_d6(info->border_y * priv->border_scale));
}
ass_cache_commit(val, 1);
}
if (!val->outline) {
ass_cache_dec_ref(val);
return;
}
info->hash_key.u.outline.outline = val;
info->outline = val->outline;
info->border = val->border;
info->bbox = val->bbox_scaled;
if (info->drawing || priv->settings.shaper == ASS_SHAPING_SIMPLE) {
info->cluster_advance.x = info->advance.x = val->advance.x;
info->cluster_advance.y = info->advance.y = val->advance.y;
}
info->asc = val->asc;
info->desc = val->desc;
}
/**
* \brief Apply transformation to outline points of a glyph
* Applies rotations given by frx, fry and frz and projects the points back
* onto the screen plane.
*/
static void
transform_3d_points(FT_Vector shift, ASS_Outline *outline, double frx, double fry,
double frz, double fax, double fay, double scale,
int yshift)
{
double sx = sin(frx);
double sy = sin(fry);
double sz = sin(frz);
double cx = cos(frx);
double cy = cos(fry);
double cz = cos(frz);
FT_Vector *p = outline->points;
double x, y, z, xx, yy, zz;
int dist;
dist = 20000 * scale;
for (size_t i = 0; i < outline->n_points; ++i) {
x = (double) p[i].x + shift.x + (fax * (yshift - p[i].y));
y = (double) p[i].y + shift.y + (-fay * p[i].x);
z = 0.;
xx = x * cz + y * sz;
yy = -(x * sz - y * cz);
zz = z;
x = xx;
y = yy * cx + zz * sx;
z = yy * sx - zz * cx;
xx = x * cy + z * sy;
yy = y;
zz = x * sy - z * cy;
zz = FFMAX(zz, 1000 - dist);
x = (xx * dist) / (zz + dist);
y = (yy * dist) / (zz + dist);
p[i].x = x - shift.x + 0.5;
p[i].y = y - shift.y + 0.5;
}
}
/**
* \brief Apply 3d transformation to several objects
* \param shift FreeType vector
* \param glyph FreeType glyph
* \param glyph2 FreeType glyph
* \param frx x-axis rotation angle
* \param fry y-axis rotation angle
* \param frz z-axis rotation angle
* Rotates both glyphs by frx, fry and frz. Shift vector is added before rotation and subtracted after it.
*/
static void
transform_3d(FT_Vector shift, ASS_Outline *outline, ASS_Outline *border,
double frx, double fry, double frz, double fax, double fay,
double scale, int yshift)
{
frx = -frx;
frz = -frz;
if (frx != 0. || fry != 0. || frz != 0. || fax != 0. || fay != 0.) {
if (outline)
transform_3d_points(shift, outline, frx, fry, frz,
fax, fay, scale, yshift);
if (border)
transform_3d_points(shift, border, frx, fry, frz,
fax, fay, scale, yshift);
}
}
/**
* \brief Get bitmaps for a glyph
* \param info glyph info
* Tries to get glyph bitmaps from bitmap cache.
* If they can't be found, they are generated by rotating and rendering the glyph.
* After that, bitmaps are added to the cache.
* They are returned in info->bm (glyph), info->bm_o (outline) and info->bm_s (shadow).
*/
static void
get_bitmap_glyph(ASS_Renderer *render_priv, GlyphInfo *info)
{
if (!info->outline || info->symbol == '\n' || info->symbol == 0 || info->skip)
return;
BitmapHashValue *val;
OutlineBitmapHashKey *key = &info->hash_key.u.outline;
if (ass_cache_get(render_priv->cache.bitmap_cache, &info->hash_key, &val)) {
info->image = val;
return;
}
if (!val)
return;
ASS_Outline *outline = outline_copy(info->outline);
ASS_Outline *border = outline_copy(info->border);
// calculating rotation shift vector (from rotation origin to the glyph basepoint)
FT_Vector shift = { key->shift_x, key->shift_y };
double scale_x = render_priv->font_scale_x;
double fax_scaled = info->fax / info->scale_y * info->scale_x;
double fay_scaled = info->fay / info->scale_x * info->scale_y;
// apply rotation
// use blur_scale because, like blurs, VSFilter forgets to scale this
transform_3d(shift, outline, border,
info->frx, info->fry, info->frz, fax_scaled,
fay_scaled, render_priv->blur_scale, info->asc);
// PAR correction scaling
FT_Matrix m = { double_to_d16(scale_x), 0,
0, double_to_d16(1.0) };
// subpixel shift
if (outline) {
if (scale_x != 1.0)
outline_transform(outline, &m);
outline_translate(outline, key->advance.x, -key->advance.y);
}
if (border) {
if (scale_x != 1.0)
outline_transform(border, &m);
outline_translate(border, key->advance.x, -key->advance.y);
}
// render glyph
int error = outline_to_bitmap2(render_priv, outline, border,
&val->bm, &val->bm_o);
if (error)
info->symbol = 0;
ass_cache_commit(val, bitmap_size(val->bm) + bitmap_size(val->bm_o) +
sizeof(BitmapHashKey) + sizeof(BitmapHashValue));
info->image = val;
outline_free(outline);
free(outline);
outline_free(border);
free(border);
}
/**
* This function goes through text_info and calculates text parameters.
* The following text_info fields are filled:
* height
* lines[].height
* lines[].asc
* lines[].desc
*/
static void measure_text(ASS_Renderer *render_priv)
{
TextInfo *text_info = &render_priv->text_info;
int cur_line = 0;
double max_asc = 0., max_desc = 0.;
GlyphInfo *last = NULL;
int i;
int empty_line = 1;
text_info->height = 0.;
for (i = 0; i < text_info->length + 1; ++i) {
if ((i == text_info->length) || text_info->glyphs[i].linebreak) {
if (empty_line && cur_line > 0 && last) {
max_asc = d6_to_double(last->asc) / 2.0;
max_desc = d6_to_double(last->desc) / 2.0;
}
text_info->lines[cur_line].asc = max_asc;
text_info->lines[cur_line].desc = max_desc;
text_info->height += max_asc + max_desc;
cur_line++;
max_asc = max_desc = 0.;
empty_line = 1;
}
if (i < text_info->length) {
GlyphInfo *cur = text_info->glyphs + i;
if (d6_to_double(cur->asc) > max_asc)
max_asc = d6_to_double(cur->asc);
if (d6_to_double(cur->desc) > max_desc)
max_desc = d6_to_double(cur->desc);
if (cur->symbol != '\n' && cur->symbol != 0) {
empty_line = 0;
last = cur;
}
}
}
text_info->height +=
(text_info->n_lines -
1) * render_priv->settings.line_spacing;
}
/**
* Mark extra whitespace for later removal.
*/
#define IS_WHITESPACE(x) ((x->symbol == ' ' || x->symbol == '\n') \
&& !x->linebreak)
static void trim_whitespace(ASS_Renderer *render_priv)
{
int i, j;
GlyphInfo *cur;
TextInfo *ti = &render_priv->text_info;
// Mark trailing spaces
i = ti->length - 1;
cur = ti->glyphs + i;
while (i && IS_WHITESPACE(cur)) {
cur->skip++;
cur = ti->glyphs + --i;
}
// Mark leading whitespace
i = 0;
cur = ti->glyphs;
while (i < ti->length && IS_WHITESPACE(cur)) {
cur->skip++;
cur = ti->glyphs + ++i;
}
// Mark all extraneous whitespace inbetween
for (i = 0; i < ti->length; ++i) {
cur = ti->glyphs + i;
if (cur->linebreak) {
// Mark whitespace before
j = i - 1;
cur = ti->glyphs + j;
while (j && IS_WHITESPACE(cur)) {
cur->skip++;
cur = ti->glyphs + --j;
}
// A break itself can contain a whitespace, too
cur = ti->glyphs + i;
if (cur->symbol == ' ' || cur->symbol == '\n') {
cur->skip++;
// Mark whitespace after
j = i + 1;
cur = ti->glyphs + j;
while (j < ti->length && IS_WHITESPACE(cur)) {
cur->skip++;
cur = ti->glyphs + ++j;
}
i = j - 1;
}
}
}
}
#undef IS_WHITESPACE
/**
* \brief rearrange text between lines
* \param max_text_width maximal text line width in pixels
* The algo is similar to the one in libvo/sub.c:
* 1. Place text, wrapping it when current line is full
* 2. Try moving words from the end of a line to the beginning of the next one while it reduces
* the difference in lengths between this two lines.
* The result may not be optimal, but usually is good enough.
*
* FIXME: implement style 0 and 3 correctly
*/
static void
wrap_lines_smart(ASS_Renderer *render_priv, double max_text_width)
{
int i;
GlyphInfo *cur, *s1, *e1, *s2, *s3;
int last_space;
int break_type;
int exit;
double pen_shift_x;
double pen_shift_y;
int cur_line;
int run_offset;
TextInfo *text_info = &render_priv->text_info;
last_space = -1;
text_info->n_lines = 1;
break_type = 0;
s1 = text_info->glyphs; // current line start
for (i = 0; i < text_info->length; ++i) {
int break_at = -1;
double s_offset, len;
cur = text_info->glyphs + i;
s_offset = d6_to_double(s1->bbox.xMin + s1->pos.x);
len = d6_to_double(cur->bbox.xMax + cur->pos.x) - s_offset;
if (cur->symbol == '\n') {
break_type = 2;
break_at = i;
ass_msg(render_priv->library, MSGL_DBG2,
"forced line break at %d", break_at);
} else if (cur->symbol == ' ') {
last_space = i;
} else if (len >= max_text_width
&& (render_priv->state.wrap_style != 2)) {
break_type = 1;
break_at = last_space;
if (break_at >= 0)
ass_msg(render_priv->library, MSGL_DBG2, "line break at %d",
break_at);
}
if (break_at != -1) {
// need to use one more line
// marking break_at+1 as start of a new line
int lead = break_at + 1; // the first symbol of the new line
if (text_info->n_lines >= text_info->max_lines) {
// Raise maximum number of lines
text_info->max_lines *= 2;
text_info->lines = realloc(text_info->lines,
sizeof(LineInfo) *
text_info->max_lines);
}
if (lead < text_info->length) {
text_info->glyphs[lead].linebreak = break_type;
last_space = -1;
s1 = text_info->glyphs + lead;
text_info->n_lines++;
}
}
}
#define DIFF(x,y) (((x) < (y)) ? (y - x) : (x - y))
exit = 0;
while (!exit && render_priv->state.wrap_style != 1) {
exit = 1;
s3 = text_info->glyphs;
s1 = s2 = 0;
for (i = 0; i <= text_info->length; ++i) {
cur = text_info->glyphs + i;
if ((i == text_info->length) || cur->linebreak) {
s1 = s2;
s2 = s3;
s3 = cur;
if (s1 && (s2->linebreak == 1)) { // have at least 2 lines, and linebreak is 'soft'
double l1, l2, l1_new, l2_new;
GlyphInfo *w = s2;
do {
--w;
} while ((w > s1) && (w->symbol == ' '));
while ((w > s1) && (w->symbol != ' ')) {
--w;
}
e1 = w;
while ((e1 > s1) && (e1->symbol == ' ')) {
--e1;
}
if (w->symbol == ' ')
++w;
l1 = d6_to_double(((s2 - 1)->bbox.xMax + (s2 - 1)->pos.x) -
(s1->bbox.xMin + s1->pos.x));
l2 = d6_to_double(((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -
(s2->bbox.xMin + s2->pos.x));
l1_new = d6_to_double(
(e1->bbox.xMax + e1->pos.x) -
(s1->bbox.xMin + s1->pos.x));
l2_new = d6_to_double(
((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -
(w->bbox.xMin + w->pos.x));
if (DIFF(l1_new, l2_new) < DIFF(l1, l2) && w > text_info->glyphs) {
if (w->linebreak)
text_info->n_lines--;
w->linebreak = 1;
s2->linebreak = 0;
exit = 0;
}
}
}
if (i == text_info->length)
break;
}
}
assert(text_info->n_lines >= 1);
#undef DIFF
measure_text(render_priv);
trim_whitespace(render_priv);
cur_line = 1;
run_offset = 0;
i = 0;
cur = text_info->glyphs + i;
while (i < text_info->length && cur->skip)
cur = text_info->glyphs + ++i;
pen_shift_x = d6_to_double(-cur->pos.x);
pen_shift_y = 0.;
for (i = 0; i < text_info->length; ++i) {
cur = text_info->glyphs + i;
if (cur->linebreak) {
while (i < text_info->length && cur->skip && cur->symbol != '\n')
cur = text_info->glyphs + ++i;
double height =
text_info->lines[cur_line - 1].desc +
text_info->lines[cur_line].asc;
text_info->lines[cur_line - 1].len = i -
text_info->lines[cur_line - 1].offset;
text_info->lines[cur_line].offset = i;
cur_line++;
run_offset++;
pen_shift_x = d6_to_double(-cur->pos.x);
pen_shift_y += height + render_priv->settings.line_spacing;
}
cur->pos.x += double_to_d6(pen_shift_x);
cur->pos.y += double_to_d6(pen_shift_y);
}
text_info->lines[cur_line - 1].len =
text_info->length - text_info->lines[cur_line - 1].offset;
#if 0
// print line info
for (i = 0; i < text_info->n_lines; i++) {
printf("line %d offset %d length %d\n", i, text_info->lines[i].offset,
text_info->lines[i].len);
}
#endif
}
/**
* \brief Calculate base point for positioning and rotation
* \param bbox text bbox
* \param alignment alignment
* \param bx, by out: base point coordinates
*/
static void get_base_point(DBBox *bbox, int alignment, double *bx, double *by)
{
const int halign = alignment & 3;
const int valign = alignment & 12;
if (bx)
switch (halign) {
case HALIGN_LEFT:
*bx = bbox->xMin;
break;
case HALIGN_CENTER:
*bx = (bbox->xMax + bbox->xMin) / 2.0;
break;
case HALIGN_RIGHT:
*bx = bbox->xMax;
break;
}
if (by)
switch (valign) {
case VALIGN_TOP:
*by = bbox->yMin;
break;
case VALIGN_CENTER:
*by = (bbox->yMax + bbox->yMin) / 2.0;
break;
case VALIGN_SUB:
*by = bbox->yMax;
break;
}
}
/**
* Prepare bitmap hash key of a glyph
*/
static void
fill_bitmap_hash(ASS_Renderer *priv, GlyphInfo *info,
OutlineBitmapHashKey *hash_key)
{
hash_key->frx = rot_key(info->frx);
hash_key->fry = rot_key(info->fry);
hash_key->frz = rot_key(info->frz);
hash_key->fax = double_to_d16(info->fax);
hash_key->fay = double_to_d16(info->fay);
}
/**
* \brief Adjust the glyph's font size and scale factors to ensure smooth
* scaling and handle pathological font sizes. The main problem here is
* freetype's grid fitting, which destroys animations by font size, or will
* result in incorrect final text size if font sizes are very small and
* scale factors very large. See Google Code issue #46.
* \param priv guess what
* \param glyph the glyph to be modified
*/
static void
fix_glyph_scaling(ASS_Renderer *priv, GlyphInfo *glyph)
{
double ft_size;
if (priv->settings.hinting == ASS_HINTING_NONE) {
// arbitrary, not too small to prevent grid fitting rounding effects
// XXX: this is a rather crude hack
ft_size = 256.0;
} else {
// If hinting is enabled, we want to pass the real font size
// to freetype. Normalize scale_y to 1.0.
ft_size = glyph->scale_y * glyph->font_size;
}
glyph->scale_x = glyph->scale_x * glyph->font_size / ft_size;
glyph->scale_y = glyph->scale_y * glyph->font_size / ft_size;
glyph->font_size = ft_size;
}
/**
* \brief Checks whether a glyph should start a new bitmap run
* \param info Pointer to new GlyphInfo to check
* \param current_info Pointer to CombinedBitmapInfo for current run (may be NULL)
* \return 1 if a new run should be started
*/
static int is_new_bm_run(GlyphInfo *info, GlyphInfo *last)
{
// FIXME: Don't break on glyph substitutions
return !last || info->effect || info->drawing || last->drawing ||
strcmp(last->font->desc.family, info->font->desc.family) ||
last->font->desc.vertical != info->font->desc.vertical ||
last->face_index != info->face_index ||
last->font_size != info->font_size ||
last->c[0] != info->c[0] ||
last->c[1] != info->c[1] ||
last->c[2] != info->c[2] ||
last->c[3] != info->c[3] ||
last->be != info->be ||
last->blur != info->blur ||
last->shadow_x != info->shadow_x ||
last->shadow_y != info->shadow_y ||
last->frx != info->frx ||
last->fry != info->fry ||
last->frz != info->frz ||
last->fax != info->fax ||
last->fay != info->fay ||
last->scale_x != info->scale_x ||
last->scale_y != info->scale_y ||
last->border_style != info->border_style ||
last->border_x != info->border_x ||
last->border_y != info->border_y ||
last->hspacing != info->hspacing ||
last->italic != info->italic ||
last->bold != info->bold ||
last->flags != info->flags;
}
static void make_shadow_bitmap(CombinedBitmapInfo *info, ASS_Renderer *render_priv)
{
if (!(info->filter.flags & FILTER_NONZERO_SHADOW)) {
if (info->bm && info->bm_o && !(info->filter.flags & FILTER_BORDER_STYLE_3)) {
fix_outline(info->bm, info->bm_o);
} else if (info->bm_o && !(info->filter.flags & FILTER_NONZERO_BORDER)) {
ass_free_bitmap(info->bm_o);
info->bm_o = 0;
}
return;
}
// Create shadow and fix outline as needed
if (info->bm && info->bm_o && !(info->filter.flags & FILTER_BORDER_STYLE_3)) {
info->bm_s = copy_bitmap(render_priv->engine, info->bm_o);
fix_outline(info->bm, info->bm_o);
} else if (info->bm_o && (info->filter.flags & FILTER_NONZERO_BORDER)) {
info->bm_s = copy_bitmap(render_priv->engine, info->bm_o);
} else if (info->bm_o) {
info->bm_s = info->bm_o;
info->bm_o = 0;
} else if (info->bm)
info->bm_s = copy_bitmap(render_priv->engine, info->bm);
if (!info->bm_s)
return;
// Works right even for negative offsets
// '>>' rounds toward negative infinity, '&' returns correct remainder
info->bm_s->left += info->filter.shadow.x >> 6;
info->bm_s->top += info->filter.shadow.y >> 6;
shift_bitmap(info->bm_s, info->filter.shadow.x & SUBPIXEL_MASK, info->filter.shadow.y & SUBPIXEL_MASK);
}
// Parse event text.
// Fill render_priv->text_info.
static int parse_events(ASS_Renderer *render_priv, ASS_Event *event)
{
TextInfo *text_info = &render_priv->text_info;
ASS_Drawing *drawing = NULL;
unsigned code;
char *p, *q;
int i;
p = event->Text;
// Event parsing.
while (1) {
// get next char, executing style override
// this affects render_context
code = 0;
while (*p) {
if ((*p == '{') && (q = strchr(p, '}'))) {
while (p < q)
p = parse_tag(render_priv, p, q, 1.);
assert(*p == '}');
p++;
} else if (render_priv->state.drawing_scale) {
q = p;
if (*p == '{')
q++;
while ((*q != '{') && (*q != 0))
q++;
if (!drawing) {
drawing = ass_drawing_new(render_priv->library,
render_priv->ftlibrary);
if (!drawing)
return 1;
}
ass_drawing_set_text(drawing, p, q - p);
code = 0xfffc; // object replacement character
p = q;
break;
} else {
code = get_next_char(render_priv, &p);
break;
}
}
if (code == 0)
break;
// face could have been changed in get_next_char
if (!render_priv->state.font) {
free_render_context(render_priv);
ass_drawing_free(drawing);
return 1;
}
if (text_info->length >= text_info->max_glyphs) {
// Raise maximum number of glyphs
text_info->max_glyphs *= 2;
text_info->glyphs =
realloc(text_info->glyphs,
sizeof(GlyphInfo) * text_info->max_glyphs);
}
GlyphInfo *info = &text_info->glyphs[text_info->length];
// Clear current GlyphInfo
memset(info, 0, sizeof(GlyphInfo));
// Parse drawing
if (drawing && drawing->text) {
drawing->scale_x = render_priv->state.scale_x *
render_priv->font_scale;
drawing->scale_y = render_priv->state.scale_y *
render_priv->font_scale;
drawing->scale = render_priv->state.drawing_scale;
drawing->pbo = render_priv->state.pbo;
info->drawing = drawing;
drawing = NULL;
}
// Fill glyph information
info->symbol = code;
info->font = render_priv->state.font;
if (!info->drawing)
ass_cache_inc_ref(info->font);
for (i = 0; i < 4; ++i) {
uint32_t clr = render_priv->state.c[i];
// VSFilter compatibility: apply fade only when it's positive
if (render_priv->state.fade > 0)
change_alpha(&clr,
mult_alpha(_a(clr), render_priv->state.fade), 1.);
info->c[i] = clr;
}
info->effect_type = render_priv->state.effect_type;
info->effect_timing = render_priv->state.effect_timing;
info->effect_skip_timing = render_priv->state.effect_skip_timing;
info->font_size =
render_priv->state.font_size * render_priv->font_scale;
info->be = render_priv->state.be;
info->blur = render_priv->state.blur;
info->shadow_x = render_priv->state.shadow_x;
info->shadow_y = render_priv->state.shadow_y;
info->scale_x = info->orig_scale_x = render_priv->state.scale_x;
info->scale_y = info->orig_scale_y = render_priv->state.scale_y;
info->border_style = render_priv->state.border_style;
info->border_x= render_priv->state.border_x;
info->border_y = render_priv->state.border_y;
info->hspacing = render_priv->state.hspacing;
info->bold = render_priv->state.bold;
info->italic = render_priv->state.italic;
info->flags = render_priv->state.flags;
info->frx = render_priv->state.frx;
info->fry = render_priv->state.fry;
info->frz = render_priv->state.frz;
info->fax = render_priv->state.fax;
info->fay = render_priv->state.fay;
if (!info->drawing)
fix_glyph_scaling(render_priv, info);
text_info->length++;
render_priv->state.effect_type = EF_NONE;
render_priv->state.effect_timing = 0;
render_priv->state.effect_skip_timing = 0;
}
ass_drawing_free(drawing);
return 0;
}
// Process render_priv->text_info and load glyph outlines.
static void retrieve_glyphs(ASS_Renderer *render_priv)
{
GlyphInfo *glyphs = render_priv->text_info.glyphs;
int i;
for (i = 0; i < render_priv->text_info.length; i++) {
GlyphInfo *info = glyphs + i;
while (info) {
get_outline_glyph(render_priv, info);
info = info->next;
}
info = glyphs + i;
// Add additional space after italic to non-italic style changes
if (i && glyphs[i - 1].italic && !info->italic) {
int back = i - 1;
GlyphInfo *og = &glyphs[back];
while (back && og->bbox.xMax - og->bbox.xMin == 0
&& og->italic)
og = &glyphs[--back];
if (og->bbox.xMax > og->cluster_advance.x)
og->cluster_advance.x = og->bbox.xMax;
}
// add horizontal letter spacing
info->cluster_advance.x += double_to_d6(info->hspacing *
render_priv->font_scale * info->orig_scale_x);
// add displacement for vertical shearing
info->cluster_advance.y += (info->fay / info->scale_x * info->scale_y) * info->cluster_advance.x;
}
}
// Preliminary layout (for line wrapping)
static void preliminary_layout(ASS_Renderer *render_priv)
{
FT_Vector pen;
int i;
pen.x = 0;
pen.y = 0;
for (i = 0; i < render_priv->text_info.length; i++) {
GlyphInfo *info = render_priv->text_info.glyphs + i;
FT_Vector cluster_pen = pen;
while (info) {
info->pos.x = cluster_pen.x;
info->pos.y = cluster_pen.y;
cluster_pen.x += info->advance.x;
cluster_pen.y += info->advance.y;
// fill bitmap hash
info->hash_key.type = BITMAP_OUTLINE;
fill_bitmap_hash(render_priv, info, &info->hash_key.u.outline);
info = info->next;
}
info = render_priv->text_info.glyphs + i;
pen.x += info->cluster_advance.x;
pen.y += info->cluster_advance.y;
}
}
// Reorder text into visual order
static void reorder_text(ASS_Renderer *render_priv)
{
TextInfo *text_info = &render_priv->text_info;
FT_Vector pen;
int i;
FriBidiStrIndex *cmap = ass_shaper_reorder(render_priv->shaper, text_info);
if (!cmap) {
ass_msg(render_priv->library, MSGL_ERR, "Failed to reorder text");
ass_shaper_cleanup(render_priv->shaper, text_info);
free_render_context(render_priv);
return;
}
// Reposition according to the map
pen.x = 0;
pen.y = 0;
int lineno = 1;
double last_pen_x = 0;
double last_fay = 0;
for (i = 0; i < text_info->length; i++) {
GlyphInfo *info = text_info->glyphs + cmap[i];
if (text_info->glyphs[i].linebreak) {
pen.y -= (last_fay / info->scale_x * info->scale_y) * (pen.x - last_pen_x);
last_pen_x = pen.x = 0;
pen.y += double_to_d6(text_info->lines[lineno-1].desc);
pen.y += double_to_d6(text_info->lines[lineno].asc);
pen.y += double_to_d6(render_priv->settings.line_spacing);
lineno++;
}
else if (last_fay != info->fay) {
pen.y -= (last_fay / info->scale_x * info->scale_y) * (pen.x - last_pen_x);
last_pen_x = pen.x;
}
last_fay = info->fay;
if (info->skip) continue;
FT_Vector cluster_pen = pen;
while (info) {
info->pos.x = info->offset.x + cluster_pen.x;
info->pos.y = info->offset.y + cluster_pen.y;
cluster_pen.x += info->advance.x;
cluster_pen.y += info->advance.y;
info = info->next;
}
info = text_info->glyphs + cmap[i];
pen.x += info->cluster_advance.x;
pen.y += info->cluster_advance.y;
}
}
static void align_lines(ASS_Renderer *render_priv, double max_text_width)
{
TextInfo *text_info = &render_priv->text_info;
GlyphInfo *glyphs = text_info->glyphs;
int i, j;
double width = 0;
int last_break = -1;
int halign = render_priv->state.alignment & 3;
if (render_priv->state.evt_type == EVENT_HSCROLL)
return;
for (i = 0; i <= text_info->length; ++i) { // (text_info->length + 1) is the end of the last line
if ((i == text_info->length) || glyphs[i].linebreak) {
double shift = 0;
if (halign == HALIGN_LEFT) { // left aligned, no action
shift = 0;
} else if (halign == HALIGN_RIGHT) { // right aligned
shift = max_text_width - width;
} else if (halign == HALIGN_CENTER) { // centered
shift = (max_text_width - width) / 2.0;
}
for (j = last_break + 1; j < i; ++j) {
GlyphInfo *info = glyphs + j;
while (info) {
info->pos.x += double_to_d6(shift);
info = info->next;
}
}
last_break = i - 1;
width = 0;
}
if (i < text_info->length && !glyphs[i].skip &&
glyphs[i].symbol != '\n' && glyphs[i].symbol != 0) {
width += d6_to_double(glyphs[i].cluster_advance.x);
}
}
}
static void calculate_rotation_params(ASS_Renderer *render_priv, DBBox *bbox,
double device_x, double device_y)
{
TextInfo *text_info = &render_priv->text_info;
DVector center;
int i;
if (render_priv->state.have_origin) {
center.x = x2scr(render_priv, render_priv->state.org_x);
center.y = y2scr(render_priv, render_priv->state.org_y);
} else {
double bx = 0., by = 0.;
get_base_point(bbox, render_priv->state.alignment, &bx, &by);
center.x = device_x + bx;
center.y = device_y + by;
}
for (i = 0; i < text_info->length; ++i) {
GlyphInfo *info = text_info->glyphs + i;
while (info) {
OutlineBitmapHashKey *key = &info->hash_key.u.outline;
if (key->frx || key->fry || key->frz || key->fax || key->fay) {
key->shift_x = info->pos.x + double_to_d6(device_x - center.x);
key->shift_y = -(info->pos.y + double_to_d6(device_y - center.y));
} else {
key->shift_x = 0;
key->shift_y = 0;
}
info = info->next;
}
}
}
static inline void rectangle_reset(Rectangle *rect)
{
rect->x_min = rect->y_min = INT_MAX;
rect->x_max = rect->y_max = INT_MIN;
}
static inline void rectangle_combine(Rectangle *rect, const Bitmap *bm, int x, int y)
{
rect->x_min = FFMIN(rect->x_min, x + bm->left);
rect->y_min = FFMIN(rect->y_min, y + bm->top);
rect->x_max = FFMAX(rect->x_max, x + bm->left + bm->w);
rect->y_max = FFMAX(rect->y_max, y + bm->top + bm->h);
}
// Convert glyphs to bitmaps, combine them, apply blur, generate shadows.
static void render_and_combine_glyphs(ASS_Renderer *render_priv,
double device_x, double device_y)
{
TextInfo *text_info = &render_priv->text_info;
int left = render_priv->settings.left_margin;
device_x = (device_x - left) * render_priv->font_scale_x + left;
unsigned nb_bitmaps = 0;
char linebreak = 0;
CombinedBitmapInfo *combined_info = text_info->combined_bitmaps;
CombinedBitmapInfo *current_info = NULL;
GlyphInfo *last_info = NULL;
for (int i = 0; i < text_info->length; i++) {
GlyphInfo *info = text_info->glyphs + i;
if (info->linebreak) linebreak = 1;
if (info->skip) {
for (; info; info = info->next)
ass_cache_dec_ref(info->hash_key.u.outline.outline);
continue;
}
for (; info; info = info->next) {
OutlineBitmapHashKey *key = &info->hash_key.u.outline;
info->pos.x = double_to_d6(device_x + d6_to_double(info->pos.x) * render_priv->font_scale_x);
info->pos.y = double_to_d6(device_y) + info->pos.y;
key->advance.x = info->pos.x & (SUBPIXEL_MASK & ~SUBPIXEL_ACCURACY);
key->advance.y = info->pos.y & (SUBPIXEL_MASK & ~SUBPIXEL_ACCURACY);
int x = info->pos.x >> 6, y = info->pos.y >> 6;
get_bitmap_glyph(render_priv, info);
if(linebreak || is_new_bm_run(info, last_info)) {
linebreak = 0;
last_info = NULL;
if (nb_bitmaps >= text_info->max_bitmaps) {
size_t new_size = 2 * text_info->max_bitmaps;
if (!ASS_REALLOC_ARRAY(text_info->combined_bitmaps, new_size)) {
ass_cache_dec_ref(info->image);
continue;
}
text_info->max_bitmaps = new_size;
combined_info = text_info->combined_bitmaps;
}
current_info = &combined_info[nb_bitmaps];
memcpy(¤t_info->c, &info->c, sizeof(info->c));
current_info->effect_type = info->effect_type;
current_info->effect_timing = info->effect_timing;
current_info->first_pos_x = info->bbox.xMax >> 6;
current_info->filter.flags = 0;
if (info->border_style == 3)
current_info->filter.flags |= FILTER_BORDER_STYLE_3;
if (info->border_x || info->border_y)
current_info->filter.flags |= FILTER_NONZERO_BORDER;
if (info->shadow_x || info->shadow_y)
current_info->filter.flags |= FILTER_NONZERO_SHADOW;
// VSFilter compatibility: invisible fill and no border?
// In this case no shadow is supposed to be rendered.
if (info->border || (info->c[0] & 0xFF) != 0xFF)
current_info->filter.flags |= FILTER_DRAW_SHADOW;
current_info->filter.be = info->be;
current_info->filter.blur = 2 * info->blur * render_priv->blur_scale;
current_info->filter.shadow.x = double_to_d6(info->shadow_x * render_priv->border_scale);
current_info->filter.shadow.y = double_to_d6(info->shadow_y * render_priv->border_scale);
current_info->x = current_info->y = INT_MAX;
rectangle_reset(¤t_info->rect);
rectangle_reset(¤t_info->rect_o);
current_info->n_bm = current_info->n_bm_o = 0;
current_info->bm = current_info->bm_o = current_info->bm_s = NULL;
current_info->image = NULL;
current_info->bitmap_count = current_info->max_bitmap_count = 0;
current_info->bitmaps = malloc(MAX_SUB_BITMAPS_INITIAL * sizeof(BitmapRef));
if (!current_info->bitmaps) {
ass_cache_dec_ref(info->image);
continue;
}
current_info->max_bitmap_count = MAX_SUB_BITMAPS_INITIAL;
nb_bitmaps++;
}
last_info = info;
if (!info->image || !current_info) {
ass_cache_dec_ref(info->image);
continue;
}
if (current_info->bitmap_count >= current_info->max_bitmap_count) {
size_t new_size = 2 * current_info->max_bitmap_count;
if (!ASS_REALLOC_ARRAY(current_info->bitmaps, new_size)) {
ass_cache_dec_ref(info->image);
continue;
}
current_info->max_bitmap_count = new_size;
}
current_info->bitmaps[current_info->bitmap_count].image = info->image;
current_info->bitmaps[current_info->bitmap_count].x = x;
current_info->bitmaps[current_info->bitmap_count].y = y;
current_info->bitmap_count++;
current_info->x = FFMIN(current_info->x, x);
current_info->y = FFMIN(current_info->y, y);
if (info->image->bm) {
rectangle_combine(¤t_info->rect, info->image->bm, x, y);
current_info->n_bm++;
}
if (info->image->bm_o) {
rectangle_combine(¤t_info->rect_o, info->image->bm_o, x, y);
current_info->n_bm_o++;
}
}
}
for (int i = 0; i < nb_bitmaps; i++) {
CombinedBitmapInfo *info = &combined_info[i];
for (int j = 0; j < info->bitmap_count; j++) {
info->bitmaps[j].x -= info->x;
info->bitmaps[j].y -= info->y;
}
CompositeHashKey hk;
CompositeHashValue *hv;
fill_composite_hash(&hk, info);
if (ass_cache_get(render_priv->cache.composite_cache, &hk, &hv)) {
info->bm = hv->bm;
info->bm_o = hv->bm_o;
info->bm_s = hv->bm_s;
info->image = hv;
continue;
}
if (!hv)
continue;
int bord = be_padding(info->filter.be);
if (!bord && info->n_bm == 1) {
for (int j = 0; j < info->bitmap_count; j++) {
if (!info->bitmaps[j].image->bm)
continue;
info->bm = copy_bitmap(render_priv->engine, info->bitmaps[j].image->bm);
if (info->bm) {
info->bm->left += info->bitmaps[j].x;
info->bm->top += info->bitmaps[j].y;
}
break;
}
} else if (info->n_bm) {
info->bm = alloc_bitmap(render_priv->engine,
info->rect.x_max - info->rect.x_min + 2 * bord,
info->rect.y_max - info->rect.y_min + 2 * bord, true);
Bitmap *dst = info->bm;
if (dst) {
dst->left = info->rect.x_min - info->x - bord;
dst->top = info->rect.y_min - info->y - bord;
for (int j = 0; j < info->bitmap_count; j++) {
Bitmap *src = info->bitmaps[j].image->bm;
if (!src)
continue;
int x = info->bitmaps[j].x + src->left - dst->left;
int y = info->bitmaps[j].y + src->top - dst->top;
assert(x >= 0 && x + src->w <= dst->w);
assert(y >= 0 && y + src->h <= dst->h);
unsigned char *buf = dst->buffer + y * dst->stride + x;
render_priv->engine->add_bitmaps(buf, dst->stride,
src->buffer, src->stride,
src->h, src->w);
}
}
}
if (!bord && info->n_bm_o == 1) {
for (int j = 0; j < info->bitmap_count; j++) {
if (!info->bitmaps[j].image->bm_o)
continue;
info->bm_o = copy_bitmap(render_priv->engine, info->bitmaps[j].image->bm_o);
if (info->bm_o) {
info->bm_o->left += info->bitmaps[j].x;
info->bm_o->top += info->bitmaps[j].y;
}
break;
}
} else if (info->n_bm_o) {
info->bm_o = alloc_bitmap(render_priv->engine,
info->rect_o.x_max - info->rect_o.x_min + 2 * bord,
info->rect_o.y_max - info->rect_o.y_min + 2 * bord,
true);
Bitmap *dst = info->bm_o;
if (dst) {
dst->left = info->rect_o.x_min - info->x - bord;
dst->top = info->rect_o.y_min - info->y - bord;
for (int j = 0; j < info->bitmap_count; j++) {
Bitmap *src = info->bitmaps[j].image->bm_o;
if (!src)
continue;
int x = info->bitmaps[j].x + src->left - dst->left;
int y = info->bitmaps[j].y + src->top - dst->top;
assert(x >= 0 && x + src->w <= dst->w);
assert(y >= 0 && y + src->h <= dst->h);
unsigned char *buf = dst->buffer + y * dst->stride + x;
render_priv->engine->add_bitmaps(buf, dst->stride,
src->buffer, src->stride,
src->h, src->w);
}
}
}
if (info->bm || info->bm_o) {
ass_synth_blur(render_priv->engine, info->filter.flags & FILTER_BORDER_STYLE_3,
info->filter.be, info->filter.blur, info->bm, info->bm_o);
if (info->filter.flags & FILTER_DRAW_SHADOW)
make_shadow_bitmap(info, render_priv);
}
hv->bm = info->bm;
hv->bm_o = info->bm_o;
hv->bm_s = info->bm_s;
ass_cache_commit(hv, bitmap_size(hv->bm) +
bitmap_size(hv->bm_o) + bitmap_size(hv->bm_s) +
sizeof(CompositeHashKey) + sizeof(CompositeHashValue));
info->image = hv;
}
text_info->n_bitmaps = nb_bitmaps;
}
static void add_background(ASS_Renderer *render_priv, EventImages *event_images)
{
void *nbuffer = ass_aligned_alloc(1, event_images->width * event_images->height, false);
if (!nbuffer)
return;
memset(nbuffer, 0xFF, event_images->width * event_images->height);
ASS_Image *img = my_draw_bitmap(nbuffer, event_images->width,
event_images->height,
event_images->width,
event_images->left,
event_images->top,
render_priv->state.c[3], NULL);
if (img) {
img->next = event_images->imgs;
event_images->imgs = img;
}
}
/**
* \brief Main ass rendering function, glues everything together
* \param event event to render
* \param event_images struct containing resulting images, will also be initialized
* Process event, appending resulting ASS_Image's to images_root.
*/
static int
ass_render_event(ASS_Renderer *render_priv, ASS_Event *event,
EventImages *event_images)
{
DBBox bbox;
int MarginL, MarginR, MarginV;
int valign;
double device_x = 0;
double device_y = 0;
TextInfo *text_info = &render_priv->text_info;
if (event->Style >= render_priv->track->n_styles) {
ass_msg(render_priv->library, MSGL_WARN, "No style found");
return 1;
}
if (!event->Text) {
ass_msg(render_priv->library, MSGL_WARN, "Empty event");
return 1;
}
free_render_context(render_priv);
init_render_context(render_priv, event);
if (parse_events(render_priv, event))
return 1;
if (text_info->length == 0) {
// no valid symbols in the event; this can be smth like {comment}
free_render_context(render_priv);
return 1;
}
// Find shape runs and shape text
ass_shaper_set_base_direction(render_priv->shaper,
resolve_base_direction(render_priv->state.font_encoding));
ass_shaper_find_runs(render_priv->shaper, render_priv, text_info->glyphs,
text_info->length);
if (ass_shaper_shape(render_priv->shaper, text_info) < 0) {
ass_msg(render_priv->library, MSGL_ERR, "Failed to shape text");
free_render_context(render_priv);
return 1;
}
retrieve_glyphs(render_priv);
preliminary_layout(render_priv);
// depends on glyph x coordinates being monotonous, so it should be done before line wrap
process_karaoke_effects(render_priv);
valign = render_priv->state.alignment & 12;
MarginL =
(event->MarginL) ? event->MarginL : render_priv->state.style->MarginL;
MarginR =
(event->MarginR) ? event->MarginR : render_priv->state.style->MarginR;
MarginV =
(event->MarginV) ? event->MarginV : render_priv->state.style->MarginV;
// calculate max length of a line
double max_text_width =
x2scr(render_priv, render_priv->track->PlayResX - MarginR) -
x2scr(render_priv, MarginL);
// wrap lines
if (render_priv->state.evt_type != EVENT_HSCROLL) {
// rearrange text in several lines
wrap_lines_smart(render_priv, max_text_width);
} else {
// no breaking or wrapping, everything in a single line
text_info->lines[0].offset = 0;
text_info->lines[0].len = text_info->length;
text_info->n_lines = 1;
measure_text(render_priv);
}
reorder_text(render_priv);
align_lines(render_priv, max_text_width);
// determing text bounding box
compute_string_bbox(text_info, &bbox);
// determine device coordinates for text
// x coordinate for everything except positioned events
if (render_priv->state.evt_type == EVENT_NORMAL ||
render_priv->state.evt_type == EVENT_VSCROLL) {
device_x = x2scr(render_priv, MarginL);
} else if (render_priv->state.evt_type == EVENT_HSCROLL) {
if (render_priv->state.scroll_direction == SCROLL_RL)
device_x =
x2scr(render_priv,
render_priv->track->PlayResX -
render_priv->state.scroll_shift);
else if (render_priv->state.scroll_direction == SCROLL_LR)
device_x =
x2scr(render_priv,
render_priv->state.scroll_shift) - (bbox.xMax -
bbox.xMin);
}
// y coordinate for everything except positioned events
if (render_priv->state.evt_type == EVENT_NORMAL ||
render_priv->state.evt_type == EVENT_HSCROLL) {
if (valign == VALIGN_TOP) { // toptitle
device_y =
y2scr_top(render_priv,
MarginV) + text_info->lines[0].asc;
} else if (valign == VALIGN_CENTER) { // midtitle
double scr_y =
y2scr(render_priv, render_priv->track->PlayResY / 2.0);
device_y = scr_y - (bbox.yMax + bbox.yMin) / 2.0;
} else { // subtitle
double line_pos = render_priv->state.explicit ?
0 : render_priv->settings.line_position;
double scr_top, scr_bottom, scr_y0;
if (valign != VALIGN_SUB)
ass_msg(render_priv->library, MSGL_V,
"Invalid valign, assuming 0 (subtitle)");
scr_bottom =
y2scr_sub(render_priv,
render_priv->track->PlayResY - MarginV);
scr_top = y2scr_top(render_priv, 0); //xxx not always 0?
device_y = scr_bottom + (scr_top - scr_bottom) * line_pos / 100.0;
device_y -= text_info->height;
device_y += text_info->lines[0].asc;
// clip to top to avoid confusion if line_position is very high,
// turning the subtitle into a toptitle
// also, don't change behavior if line_position is not used
scr_y0 = scr_top + text_info->lines[0].asc;
if (device_y < scr_y0 && line_pos > 0) {
device_y = scr_y0;
}
}
} else if (render_priv->state.evt_type == EVENT_VSCROLL) {
if (render_priv->state.scroll_direction == SCROLL_TB)
device_y =
y2scr(render_priv,
render_priv->state.clip_y0 +
render_priv->state.scroll_shift) - (bbox.yMax -
bbox.yMin);
else if (render_priv->state.scroll_direction == SCROLL_BT)
device_y =
y2scr(render_priv,
render_priv->state.clip_y1 -
render_priv->state.scroll_shift);
}
// positioned events are totally different
if (render_priv->state.evt_type == EVENT_POSITIONED) {
double base_x = 0;
double base_y = 0;
get_base_point(&bbox, render_priv->state.alignment, &base_x, &base_y);
device_x =
x2scr_pos(render_priv, render_priv->state.pos_x) - base_x;
device_y =
y2scr_pos(render_priv, render_priv->state.pos_y) - base_y;
}
// fix clip coordinates (they depend on alignment)
if (render_priv->state.evt_type == EVENT_NORMAL ||
render_priv->state.evt_type == EVENT_HSCROLL ||
render_priv->state.evt_type == EVENT_VSCROLL) {
render_priv->state.clip_x0 =
x2scr_scaled(render_priv, render_priv->state.clip_x0);
render_priv->state.clip_x1 =
x2scr_scaled(render_priv, render_priv->state.clip_x1);
if (valign == VALIGN_TOP) {
render_priv->state.clip_y0 =
y2scr_top(render_priv, render_priv->state.clip_y0);
render_priv->state.clip_y1 =
y2scr_top(render_priv, render_priv->state.clip_y1);
} else if (valign == VALIGN_CENTER) {
render_priv->state.clip_y0 =
y2scr(render_priv, render_priv->state.clip_y0);
render_priv->state.clip_y1 =
y2scr(render_priv, render_priv->state.clip_y1);
} else if (valign == VALIGN_SUB) {
render_priv->state.clip_y0 =
y2scr_sub(render_priv, render_priv->state.clip_y0);
render_priv->state.clip_y1 =
y2scr_sub(render_priv, render_priv->state.clip_y1);
}
} else if (render_priv->state.evt_type == EVENT_POSITIONED) {
render_priv->state.clip_x0 =
x2scr_pos_scaled(render_priv, render_priv->state.clip_x0);
render_priv->state.clip_x1 =
x2scr_pos_scaled(render_priv, render_priv->state.clip_x1);
render_priv->state.clip_y0 =
y2scr_pos(render_priv, render_priv->state.clip_y0);
render_priv->state.clip_y1 =
y2scr_pos(render_priv, render_priv->state.clip_y1);
}
if (render_priv->state.explicit) {
// we still need to clip against screen boundaries
double zx = x2scr_pos_scaled(render_priv, 0);
double zy = y2scr_pos(render_priv, 0);
double sx = x2scr_pos_scaled(render_priv, render_priv->track->PlayResX);
double sy = y2scr_pos(render_priv, render_priv->track->PlayResY);
render_priv->state.clip_x0 = render_priv->state.clip_x0 < zx ? zx : render_priv->state.clip_x0;
render_priv->state.clip_y0 = render_priv->state.clip_y0 < zy ? zy : render_priv->state.clip_y0;
render_priv->state.clip_x1 = render_priv->state.clip_x1 > sx ? sx : render_priv->state.clip_x1;
render_priv->state.clip_y1 = render_priv->state.clip_y1 > sy ? sy : render_priv->state.clip_y1;
}
calculate_rotation_params(render_priv, &bbox, device_x, device_y);
render_and_combine_glyphs(render_priv, device_x, device_y);
memset(event_images, 0, sizeof(*event_images));
event_images->top = device_y - text_info->lines[0].asc;
event_images->height = text_info->height;
event_images->left =
(device_x + bbox.xMin * render_priv->font_scale_x) + 0.5;
event_images->width =
(bbox.xMax - bbox.xMin) * render_priv->font_scale_x + 0.5;
event_images->detect_collisions = render_priv->state.detect_collisions;
event_images->shift_direction = (valign == VALIGN_TOP) ? 1 : -1;
event_images->event = event;
event_images->imgs = render_text(render_priv);
if (render_priv->state.border_style == 4)
add_background(render_priv, event_images);
ass_shaper_cleanup(render_priv->shaper, text_info);
free_render_context(render_priv);
return 0;
}
/**
* \brief Check cache limits and reset cache if they are exceeded
*/
static void check_cache_limits(ASS_Renderer *priv, CacheStore *cache)
{
ass_cache_cut(cache->composite_cache, cache->composite_max_size);
ass_cache_cut(cache->bitmap_cache, cache->bitmap_max_size);
ass_cache_cut(cache->outline_cache, cache->glyph_max);
}
/**
* \brief Start a new frame
*/
static int
ass_start_frame(ASS_Renderer *render_priv, ASS_Track *track,
long long now)
{
ASS_Settings *settings_priv = &render_priv->settings;
if (!render_priv->settings.frame_width
&& !render_priv->settings.frame_height)
return 1; // library not initialized
if (!render_priv->fontselect)
return 1;
if (render_priv->library != track->library)
return 1;
if (track->n_events == 0)
return 1; // nothing to do
render_priv->track = track;
render_priv->time = now;
ass_lazy_track_init(render_priv->library, render_priv->track);
ass_shaper_set_kerning(render_priv->shaper, track->Kerning);
ass_shaper_set_language(render_priv->shaper, track->Language);
ass_shaper_set_level(render_priv->shaper, render_priv->settings.shaper);
// PAR correction
double par = render_priv->settings.par;
if (par == 0.) {
if (settings_priv->frame_width && settings_priv->frame_height &&
settings_priv->storage_width && settings_priv->storage_height) {
double dar = ((double) settings_priv->frame_width) /
settings_priv->frame_height;
double sar = ((double) settings_priv->storage_width) /
settings_priv->storage_height;
par = sar / dar;
} else
par = 1.0;
}
render_priv->font_scale_x = par;
render_priv->prev_images_root = render_priv->images_root;
render_priv->images_root = NULL;
check_cache_limits(render_priv, &render_priv->cache);
return 0;
}
static int cmp_event_layer(const void *p1, const void *p2)
{
ASS_Event *e1 = ((EventImages *) p1)->event;
ASS_Event *e2 = ((EventImages *) p2)->event;
if (e1->Layer < e2->Layer)
return -1;
if (e1->Layer > e2->Layer)
return 1;
if (e1->ReadOrder < e2->ReadOrder)
return -1;
if (e1->ReadOrder > e2->ReadOrder)
return 1;
return 0;
}
static ASS_RenderPriv *get_render_priv(ASS_Renderer *render_priv,
ASS_Event *event)
{
if (!event->render_priv) {
event->render_priv = calloc(1, sizeof(ASS_RenderPriv));
if (!event->render_priv)
return NULL;
}
if (render_priv->render_id != event->render_priv->render_id) {
memset(event->render_priv, 0, sizeof(ASS_RenderPriv));
event->render_priv->render_id = render_priv->render_id;
}
return event->render_priv;
}
static int overlap(Segment *s1, Segment *s2)
{
if (s1->a >= s2->b || s2->a >= s1->b ||
s1->ha >= s2->hb || s2->ha >= s1->hb)
return 0;
return 1;
}
static int cmp_segment(const void *p1, const void *p2)
{
return ((Segment *) p1)->a - ((Segment *) p2)->a;
}
static void
shift_event(ASS_Renderer *render_priv, EventImages *ei, int shift)
{
ASS_Image *cur = ei->imgs;
while (cur) {
cur->dst_y += shift;
// clip top and bottom
if (cur->dst_y < 0) {
int clip = -cur->dst_y;
cur->h -= clip;
cur->bitmap += clip * cur->stride;
cur->dst_y = 0;
}
if (cur->dst_y + cur->h >= render_priv->height) {
int clip = cur->dst_y + cur->h - render_priv->height;
cur->h -= clip;
}
if (cur->h <= 0) {
cur->h = 0;
cur->dst_y = 0;
}
cur = cur->next;
}
ei->top += shift;
}
// dir: 1 - move down
// -1 - move up
static int fit_segment(Segment *s, Segment *fixed, int *cnt, int dir)
{
int i;
int shift = 0;
if (dir == 1) // move down
for (i = 0; i < *cnt; ++i) {
if (s->b + shift <= fixed[i].a || s->a + shift >= fixed[i].b ||
s->hb <= fixed[i].ha || s->ha >= fixed[i].hb)
continue;
shift = fixed[i].b - s->a;
} else // dir == -1, move up
for (i = *cnt - 1; i >= 0; --i) {
if (s->b + shift <= fixed[i].a || s->a + shift >= fixed[i].b ||
s->hb <= fixed[i].ha || s->ha >= fixed[i].hb)
continue;
shift = fixed[i].a - s->b;
}
fixed[*cnt].a = s->a + shift;
fixed[*cnt].b = s->b + shift;
fixed[*cnt].ha = s->ha;
fixed[*cnt].hb = s->hb;
(*cnt)++;
qsort(fixed, *cnt, sizeof(Segment), cmp_segment);
return shift;
}
static void
fix_collisions(ASS_Renderer *render_priv, EventImages *imgs, int cnt)
{
Segment *used = ass_realloc_array(NULL, cnt, sizeof(*used));
int cnt_used = 0;
int i, j;
if (!used)
return;
// fill used[] with fixed events
for (i = 0; i < cnt; ++i) {
ASS_RenderPriv *priv;
if (!imgs[i].detect_collisions)
continue;
priv = get_render_priv(render_priv, imgs[i].event);
if (priv && priv->height > 0) { // it's a fixed event
Segment s;
s.a = priv->top;
s.b = priv->top + priv->height;
s.ha = priv->left;
s.hb = priv->left + priv->width;
if (priv->height != imgs[i].height) { // no, it's not
ass_msg(render_priv->library, MSGL_WARN,
"Event height has changed");
priv->top = 0;
priv->height = 0;
priv->left = 0;
priv->width = 0;
}
for (j = 0; j < cnt_used; ++j)
if (overlap(&s, used + j)) { // no, it's not
priv->top = 0;
priv->height = 0;
priv->left = 0;
priv->width = 0;
}
if (priv->height > 0) { // still a fixed event
used[cnt_used].a = priv->top;
used[cnt_used].b = priv->top + priv->height;
used[cnt_used].ha = priv->left;
used[cnt_used].hb = priv->left + priv->width;
cnt_used++;
shift_event(render_priv, imgs + i, priv->top - imgs[i].top);
}
}
}
qsort(used, cnt_used, sizeof(Segment), cmp_segment);
// try to fit other events in free spaces
for (i = 0; i < cnt; ++i) {
ASS_RenderPriv *priv;
if (!imgs[i].detect_collisions)
continue;
priv = get_render_priv(render_priv, imgs[i].event);
if (priv && priv->height == 0) { // not a fixed event
int shift;
Segment s;
s.a = imgs[i].top;
s.b = imgs[i].top + imgs[i].height;
s.ha = imgs[i].left;
s.hb = imgs[i].left + imgs[i].width;
shift = fit_segment(&s, used, &cnt_used, imgs[i].shift_direction);
if (shift)
shift_event(render_priv, imgs + i, shift);
// make it fixed
priv->top = imgs[i].top;
priv->height = imgs[i].height;
priv->left = imgs[i].left;
priv->width = imgs[i].width;
}
}
free(used);
}
/**
* \brief compare two images
* \param i1 first image
* \param i2 second image
* \return 0 if identical, 1 if different positions, 2 if different content
*/
static int ass_image_compare(ASS_Image *i1, ASS_Image *i2)
{
if (i1->w != i2->w)
return 2;
if (i1->h != i2->h)
return 2;
if (i1->stride != i2->stride)
return 2;
if (i1->color != i2->color)
return 2;
if (i1->bitmap != i2->bitmap)
return 2;
if (i1->dst_x != i2->dst_x)
return 1;
if (i1->dst_y != i2->dst_y)
return 1;
return 0;
}
/**
* \brief compare current and previous image list
* \param priv library handle
* \return 0 if identical, 1 if different positions, 2 if different content
*/
static int ass_detect_change(ASS_Renderer *priv)
{
ASS_Image *img, *img2;
int diff;
if (priv->state.has_clips)
return 2;
img = priv->prev_images_root;
img2 = priv->images_root;
diff = 0;
while (img && diff < 2) {
ASS_Image *next, *next2;
next = img->next;
if (img2) {
int d = ass_image_compare(img, img2);
if (d > diff)
diff = d;
next2 = img2->next;
} else {
// previous list is shorter
diff = 2;
break;
}
img = next;
img2 = next2;
}
// is the previous list longer?
if (img2)
diff = 2;
return diff;
}
/**
* \brief render a frame
* \param priv library handle
* \param track track
* \param now current video timestamp (ms)
* \param detect_change a value describing how the new images differ from the previous ones will be written here:
* 0 if identical, 1 if different positions, 2 if different content.
* Can be NULL, in that case no detection is performed.
*/
ASS_Image *ass_render_frame(ASS_Renderer *priv, ASS_Track *track,
long long now, int *detect_change)
{
int i, cnt, rc;
EventImages *last;
ASS_Image **tail;
// init frame
rc = ass_start_frame(priv, track, now);
if (rc != 0) {
if (detect_change) {
*detect_change = 2;
}
return NULL;
}
// render events separately
cnt = 0;
for (i = 0; i < track->n_events; ++i) {
ASS_Event *event = track->events + i;
if ((event->Start <= now)
&& (now < (event->Start + event->Duration))) {
if (cnt >= priv->eimg_size) {
priv->eimg_size += 100;
priv->eimg =
realloc(priv->eimg,
priv->eimg_size * sizeof(EventImages));
}
rc = ass_render_event(priv, event, priv->eimg + cnt);
if (!rc)
++cnt;
}
}
// sort by layer
qsort(priv->eimg, cnt, sizeof(EventImages), cmp_event_layer);
// call fix_collisions for each group of events with the same layer
last = priv->eimg;
for (i = 1; i < cnt; ++i)
if (last->event->Layer != priv->eimg[i].event->Layer) {
fix_collisions(priv, last, priv->eimg + i - last);
last = priv->eimg + i;
}
if (cnt > 0)
fix_collisions(priv, last, priv->eimg + cnt - last);
// concat lists
tail = &priv->images_root;
for (i = 0; i < cnt; ++i) {
ASS_Image *cur = priv->eimg[i].imgs;
while (cur) {
*tail = cur;
tail = &cur->next;
cur = cur->next;
}
}
ass_frame_ref(priv->images_root);
if (detect_change)
*detect_change = ass_detect_change(priv);
// free the previous image list
ass_frame_unref(priv->prev_images_root);
priv->prev_images_root = NULL;
return priv->images_root;
}
/**
* \brief Add reference to a frame image list.
* \param image_list image list returned by ass_render_frame()
*/
void ass_frame_ref(ASS_Image *img)
{
if (!img)
return;
((ASS_ImagePriv *) img)->ref_count++;
}
/**
* \brief Release reference to a frame image list.
* \param image_list image list returned by ass_render_frame()
*/
void ass_frame_unref(ASS_Image *img)
{
if (!img || --((ASS_ImagePriv *) img)->ref_count)
return;
do {
ASS_ImagePriv *priv = (ASS_ImagePriv *) img;
img = img->next;
if (priv->source)
ass_cache_dec_ref(priv->source);
else
ass_aligned_free(priv->result.bitmap);
free(priv);
} while (img);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5341_0 |
crossvul-cpp_data_good_3358_1 | /*
* IPv6 output functions
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
*
* Based on linux/net/ipv4/ip_output.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Changes:
* A.N.Kuznetsov : airthmetics in fragmentation.
* extension headers are implemented.
* route changes now work.
* ip6_forward does not confuse sniffers.
* etc.
*
* H. von Brand : Added missing #include <linux/string.h>
* Imran Patel : frag id should be in NBO
* Kazunori MIYAZAWA @USAGI
* : add ip6_append_data and related functions
* for datagram xmit
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/in6.h>
#include <linux/tcp.h>
#include <linux/route.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/bpf-cgroup.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv6.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/ndisc.h>
#include <net/protocol.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <net/rawv6.h>
#include <net/icmp.h>
#include <net/xfrm.h>
#include <net/checksum.h>
#include <linux/mroute6.h>
#include <net/l3mdev.h>
#include <net/lwtunnel.h>
static int ip6_finish_output2(struct net *net, struct sock *sk, struct sk_buff *skb)
{
struct dst_entry *dst = skb_dst(skb);
struct net_device *dev = dst->dev;
struct neighbour *neigh;
struct in6_addr *nexthop;
int ret;
skb->protocol = htons(ETH_P_IPV6);
skb->dev = dev;
if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr)) {
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
if (!(dev->flags & IFF_LOOPBACK) && sk_mc_loop(sk) &&
((mroute6_socket(net, skb) &&
!(IP6CB(skb)->flags & IP6SKB_FORWARDED)) ||
ipv6_chk_mcast_addr(dev, &ipv6_hdr(skb)->daddr,
&ipv6_hdr(skb)->saddr))) {
struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC);
/* Do not check for IFF_ALLMULTI; multicast routing
is not supported in any case.
*/
if (newskb)
NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING,
net, sk, newskb, NULL, newskb->dev,
dev_loopback_xmit);
if (ipv6_hdr(skb)->hop_limit == 0) {
IP6_INC_STATS(net, idev,
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return 0;
}
}
IP6_UPD_PO_STATS(net, idev, IPSTATS_MIB_OUTMCAST, skb->len);
if (IPV6_ADDR_MC_SCOPE(&ipv6_hdr(skb)->daddr) <=
IPV6_ADDR_SCOPE_NODELOCAL &&
!(dev->flags & IFF_LOOPBACK)) {
kfree_skb(skb);
return 0;
}
}
if (lwtunnel_xmit_redirect(dst->lwtstate)) {
int res = lwtunnel_xmit(skb);
if (res < 0 || res == LWTUNNEL_XMIT_DONE)
return res;
}
rcu_read_lock_bh();
nexthop = rt6_nexthop((struct rt6_info *)dst, &ipv6_hdr(skb)->daddr);
neigh = __ipv6_neigh_lookup_noref(dst->dev, nexthop);
if (unlikely(!neigh))
neigh = __neigh_create(&nd_tbl, nexthop, dst->dev, false);
if (!IS_ERR(neigh)) {
sock_confirm_neigh(skb, neigh);
ret = neigh_output(neigh, skb);
rcu_read_unlock_bh();
return ret;
}
rcu_read_unlock_bh();
IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES);
kfree_skb(skb);
return -EINVAL;
}
static int ip6_finish_output(struct net *net, struct sock *sk, struct sk_buff *skb)
{
int ret;
ret = BPF_CGROUP_RUN_PROG_INET_EGRESS(sk, skb);
if (ret) {
kfree_skb(skb);
return ret;
}
if ((skb->len > ip6_skb_dst_mtu(skb) && !skb_is_gso(skb)) ||
dst_allfrag(skb_dst(skb)) ||
(IP6CB(skb)->frag_max_size && skb->len > IP6CB(skb)->frag_max_size))
return ip6_fragment(net, sk, skb, ip6_finish_output2);
else
return ip6_finish_output2(net, sk, skb);
}
int ip6_output(struct net *net, struct sock *sk, struct sk_buff *skb)
{
struct net_device *dev = skb_dst(skb)->dev;
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
if (unlikely(idev->cnf.disable_ipv6)) {
IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return 0;
}
return NF_HOOK_COND(NFPROTO_IPV6, NF_INET_POST_ROUTING,
net, sk, skb, NULL, dev,
ip6_finish_output,
!(IP6CB(skb)->flags & IP6SKB_REROUTED));
}
/*
* xmit an sk_buff (used by TCP, SCTP and DCCP)
* Note : socket lock is not held for SYNACK packets, but might be modified
* by calls to skb_set_owner_w() and ipv6_local_error(),
* which are using proper atomic operations or spinlocks.
*/
int ip6_xmit(const struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6,
__u32 mark, struct ipv6_txoptions *opt, int tclass)
{
struct net *net = sock_net(sk);
const struct ipv6_pinfo *np = inet6_sk(sk);
struct in6_addr *first_hop = &fl6->daddr;
struct dst_entry *dst = skb_dst(skb);
struct ipv6hdr *hdr;
u8 proto = fl6->flowi6_proto;
int seg_len = skb->len;
int hlimit = -1;
u32 mtu;
if (opt) {
unsigned int head_room;
/* First: exthdrs may take lots of space (~8K for now)
MAX_HEADER is not enough.
*/
head_room = opt->opt_nflen + opt->opt_flen;
seg_len += head_room;
head_room += sizeof(struct ipv6hdr) + LL_RESERVED_SPACE(dst->dev);
if (skb_headroom(skb) < head_room) {
struct sk_buff *skb2 = skb_realloc_headroom(skb, head_room);
if (!skb2) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return -ENOBUFS;
}
consume_skb(skb);
skb = skb2;
/* skb_set_owner_w() changes sk->sk_wmem_alloc atomically,
* it is safe to call in our context (socket lock not held)
*/
skb_set_owner_w(skb, (struct sock *)sk);
}
if (opt->opt_flen)
ipv6_push_frag_opts(skb, opt, &proto);
if (opt->opt_nflen)
ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop,
&fl6->saddr);
}
skb_push(skb, sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
hdr = ipv6_hdr(skb);
/*
* Fill in the IPv6 header
*/
if (np)
hlimit = np->hop_limit;
if (hlimit < 0)
hlimit = ip6_dst_hoplimit(dst);
ip6_flow_hdr(hdr, tclass, ip6_make_flowlabel(net, skb, fl6->flowlabel,
np->autoflowlabel, fl6));
hdr->payload_len = htons(seg_len);
hdr->nexthdr = proto;
hdr->hop_limit = hlimit;
hdr->saddr = fl6->saddr;
hdr->daddr = *first_hop;
skb->protocol = htons(ETH_P_IPV6);
skb->priority = sk->sk_priority;
skb->mark = mark;
mtu = dst_mtu(dst);
if ((skb->len <= mtu) || skb->ignore_df || skb_is_gso(skb)) {
IP6_UPD_PO_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUT, skb->len);
/* if egress device is enslaved to an L3 master device pass the
* skb to its handler for processing
*/
skb = l3mdev_ip6_out((struct sock *)sk, skb);
if (unlikely(!skb))
return 0;
/* hooks should never assume socket lock is held.
* we promote our socket to non const
*/
return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT,
net, (struct sock *)sk, skb, NULL, dst->dev,
dst_output);
}
skb->dev = dst->dev;
/* ipv6_local_error() does not require socket lock,
* we promote our socket to non const
*/
ipv6_local_error((struct sock *)sk, EMSGSIZE, fl6, mtu);
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
EXPORT_SYMBOL(ip6_xmit);
static int ip6_call_ra_chain(struct sk_buff *skb, int sel)
{
struct ip6_ra_chain *ra;
struct sock *last = NULL;
read_lock(&ip6_ra_lock);
for (ra = ip6_ra_chain; ra; ra = ra->next) {
struct sock *sk = ra->sk;
if (sk && ra->sel == sel &&
(!sk->sk_bound_dev_if ||
sk->sk_bound_dev_if == skb->dev->ifindex)) {
if (last) {
struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
if (skb2)
rawv6_rcv(last, skb2);
}
last = sk;
}
}
if (last) {
rawv6_rcv(last, skb);
read_unlock(&ip6_ra_lock);
return 1;
}
read_unlock(&ip6_ra_lock);
return 0;
}
static int ip6_forward_proxy_check(struct sk_buff *skb)
{
struct ipv6hdr *hdr = ipv6_hdr(skb);
u8 nexthdr = hdr->nexthdr;
__be16 frag_off;
int offset;
if (ipv6_ext_hdr(nexthdr)) {
offset = ipv6_skip_exthdr(skb, sizeof(*hdr), &nexthdr, &frag_off);
if (offset < 0)
return 0;
} else
offset = sizeof(struct ipv6hdr);
if (nexthdr == IPPROTO_ICMPV6) {
struct icmp6hdr *icmp6;
if (!pskb_may_pull(skb, (skb_network_header(skb) +
offset + 1 - skb->data)))
return 0;
icmp6 = (struct icmp6hdr *)(skb_network_header(skb) + offset);
switch (icmp6->icmp6_type) {
case NDISC_ROUTER_SOLICITATION:
case NDISC_ROUTER_ADVERTISEMENT:
case NDISC_NEIGHBOUR_SOLICITATION:
case NDISC_NEIGHBOUR_ADVERTISEMENT:
case NDISC_REDIRECT:
/* For reaction involving unicast neighbor discovery
* message destined to the proxied address, pass it to
* input function.
*/
return 1;
default:
break;
}
}
/*
* The proxying router can't forward traffic sent to a link-local
* address, so signal the sender and discard the packet. This
* behavior is clarified by the MIPv6 specification.
*/
if (ipv6_addr_type(&hdr->daddr) & IPV6_ADDR_LINKLOCAL) {
dst_link_failure(skb);
return -1;
}
return 0;
}
static inline int ip6_forward_finish(struct net *net, struct sock *sk,
struct sk_buff *skb)
{
return dst_output(net, sk, skb);
}
static unsigned int ip6_dst_mtu_forward(const struct dst_entry *dst)
{
unsigned int mtu;
struct inet6_dev *idev;
if (dst_metric_locked(dst, RTAX_MTU)) {
mtu = dst_metric_raw(dst, RTAX_MTU);
if (mtu)
return mtu;
}
mtu = IPV6_MIN_MTU;
rcu_read_lock();
idev = __in6_dev_get(dst->dev);
if (idev)
mtu = idev->cnf.mtu6;
rcu_read_unlock();
return mtu;
}
static bool ip6_pkt_too_big(const struct sk_buff *skb, unsigned int mtu)
{
if (skb->len <= mtu)
return false;
/* ipv6 conntrack defrag sets max_frag_size + ignore_df */
if (IP6CB(skb)->frag_max_size && IP6CB(skb)->frag_max_size > mtu)
return true;
if (skb->ignore_df)
return false;
if (skb_is_gso(skb) && skb_gso_validate_mtu(skb, mtu))
return false;
return true;
}
int ip6_forward(struct sk_buff *skb)
{
struct dst_entry *dst = skb_dst(skb);
struct ipv6hdr *hdr = ipv6_hdr(skb);
struct inet6_skb_parm *opt = IP6CB(skb);
struct net *net = dev_net(dst->dev);
u32 mtu;
if (net->ipv6.devconf_all->forwarding == 0)
goto error;
if (skb->pkt_type != PACKET_HOST)
goto drop;
if (unlikely(skb->sk))
goto drop;
if (skb_warn_if_lro(skb))
goto drop;
if (!xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)) {
__IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_INDISCARDS);
goto drop;
}
skb_forward_csum(skb);
/*
* We DO NOT make any processing on
* RA packets, pushing them to user level AS IS
* without ane WARRANTY that application will be able
* to interpret them. The reason is that we
* cannot make anything clever here.
*
* We are not end-node, so that if packet contains
* AH/ESP, we cannot make anything.
* Defragmentation also would be mistake, RA packets
* cannot be fragmented, because there is no warranty
* that different fragments will go along one path. --ANK
*/
if (unlikely(opt->flags & IP6SKB_ROUTERALERT)) {
if (ip6_call_ra_chain(skb, ntohs(opt->ra)))
return 0;
}
/*
* check and decrement ttl
*/
if (hdr->hop_limit <= 1) {
/* Force OUTPUT device used as source address */
skb->dev = dst->dev;
icmpv6_send(skb, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT, 0);
__IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_INHDRERRORS);
kfree_skb(skb);
return -ETIMEDOUT;
}
/* XXX: idev->cnf.proxy_ndp? */
if (net->ipv6.devconf_all->proxy_ndp &&
pneigh_lookup(&nd_tbl, net, &hdr->daddr, skb->dev, 0)) {
int proxied = ip6_forward_proxy_check(skb);
if (proxied > 0)
return ip6_input(skb);
else if (proxied < 0) {
__IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_INDISCARDS);
goto drop;
}
}
if (!xfrm6_route_forward(skb)) {
__IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_INDISCARDS);
goto drop;
}
dst = skb_dst(skb);
/* IPv6 specs say nothing about it, but it is clear that we cannot
send redirects to source routed frames.
We don't send redirects to frames decapsulated from IPsec.
*/
if (skb->dev == dst->dev && opt->srcrt == 0 && !skb_sec_path(skb)) {
struct in6_addr *target = NULL;
struct inet_peer *peer;
struct rt6_info *rt;
/*
* incoming and outgoing devices are the same
* send a redirect.
*/
rt = (struct rt6_info *) dst;
if (rt->rt6i_flags & RTF_GATEWAY)
target = &rt->rt6i_gateway;
else
target = &hdr->daddr;
peer = inet_getpeer_v6(net->ipv6.peers, &hdr->daddr, 1);
/* Limit redirects both by destination (here)
and by source (inside ndisc_send_redirect)
*/
if (inet_peer_xrlim_allow(peer, 1*HZ))
ndisc_send_redirect(skb, target);
if (peer)
inet_putpeer(peer);
} else {
int addrtype = ipv6_addr_type(&hdr->saddr);
/* This check is security critical. */
if (addrtype == IPV6_ADDR_ANY ||
addrtype & (IPV6_ADDR_MULTICAST | IPV6_ADDR_LOOPBACK))
goto error;
if (addrtype & IPV6_ADDR_LINKLOCAL) {
icmpv6_send(skb, ICMPV6_DEST_UNREACH,
ICMPV6_NOT_NEIGHBOUR, 0);
goto error;
}
}
mtu = ip6_dst_mtu_forward(dst);
if (mtu < IPV6_MIN_MTU)
mtu = IPV6_MIN_MTU;
if (ip6_pkt_too_big(skb, mtu)) {
/* Again, force OUTPUT device used as source address */
skb->dev = dst->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
__IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_INTOOBIGERRORS);
__IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
if (skb_cow(skb, dst->dev->hard_header_len)) {
__IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_OUTDISCARDS);
goto drop;
}
hdr = ipv6_hdr(skb);
/* Mangling hops number delayed to point after skb COW */
hdr->hop_limit--;
__IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTFORWDATAGRAMS);
__IP6_ADD_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTOCTETS, skb->len);
return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD,
net, NULL, skb, skb->dev, dst->dev,
ip6_forward_finish);
error:
__IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INADDRERRORS);
drop:
kfree_skb(skb);
return -EINVAL;
}
static void ip6_copy_metadata(struct sk_buff *to, struct sk_buff *from)
{
to->pkt_type = from->pkt_type;
to->priority = from->priority;
to->protocol = from->protocol;
skb_dst_drop(to);
skb_dst_set(to, dst_clone(skb_dst(from)));
to->dev = from->dev;
to->mark = from->mark;
#ifdef CONFIG_NET_SCHED
to->tc_index = from->tc_index;
#endif
nf_copy(to, from);
skb_copy_secmark(to, from);
}
int ip6_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
int (*output)(struct net *, struct sock *, struct sk_buff *))
{
struct sk_buff *frag;
struct rt6_info *rt = (struct rt6_info *)skb_dst(skb);
struct ipv6_pinfo *np = skb->sk && !dev_recursion_level() ?
inet6_sk(skb->sk) : NULL;
struct ipv6hdr *tmp_hdr;
struct frag_hdr *fh;
unsigned int mtu, hlen, left, len;
int hroom, troom;
__be32 frag_id;
int ptr, offset = 0, err = 0;
u8 *prevhdr, nexthdr = 0;
hlen = ip6_find_1stfragopt(skb, &prevhdr);
if (hlen < 0) {
err = hlen;
goto fail;
}
nexthdr = *prevhdr;
mtu = ip6_skb_dst_mtu(skb);
/* We must not fragment if the socket is set to force MTU discovery
* or if the skb it not generated by a local socket.
*/
if (unlikely(!skb->ignore_df && skb->len > mtu))
goto fail_toobig;
if (IP6CB(skb)->frag_max_size) {
if (IP6CB(skb)->frag_max_size > mtu)
goto fail_toobig;
/* don't send fragments larger than what we received */
mtu = IP6CB(skb)->frag_max_size;
if (mtu < IPV6_MIN_MTU)
mtu = IPV6_MIN_MTU;
}
if (np && np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
if (mtu < hlen + sizeof(struct frag_hdr) + 8)
goto fail_toobig;
mtu -= hlen + sizeof(struct frag_hdr);
frag_id = ipv6_select_ident(net, &ipv6_hdr(skb)->daddr,
&ipv6_hdr(skb)->saddr);
if (skb->ip_summed == CHECKSUM_PARTIAL &&
(err = skb_checksum_help(skb)))
goto fail;
hroom = LL_RESERVED_SPACE(rt->dst.dev);
if (skb_has_frag_list(skb)) {
unsigned int first_len = skb_pagelen(skb);
struct sk_buff *frag2;
if (first_len - hlen > mtu ||
((first_len - hlen) & 7) ||
skb_cloned(skb) ||
skb_headroom(skb) < (hroom + sizeof(struct frag_hdr)))
goto slow_path;
skb_walk_frags(skb, frag) {
/* Correct geometry. */
if (frag->len > mtu ||
((frag->len & 7) && frag->next) ||
skb_headroom(frag) < (hlen + hroom + sizeof(struct frag_hdr)))
goto slow_path_clean;
/* Partially cloned skb? */
if (skb_shared(frag))
goto slow_path_clean;
BUG_ON(frag->sk);
if (skb->sk) {
frag->sk = skb->sk;
frag->destructor = sock_wfree;
}
skb->truesize -= frag->truesize;
}
err = 0;
offset = 0;
/* BUILD HEADER */
*prevhdr = NEXTHDR_FRAGMENT;
tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC);
if (!tmp_hdr) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
frag = skb_shinfo(skb)->frag_list;
skb_frag_list_init(skb);
__skb_pull(skb, hlen);
fh = (struct frag_hdr *)__skb_push(skb, sizeof(struct frag_hdr));
__skb_push(skb, hlen);
skb_reset_network_header(skb);
memcpy(skb_network_header(skb), tmp_hdr, hlen);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(IP6_MF);
fh->identification = frag_id;
first_len = skb_pagelen(skb);
skb->data_len = first_len - skb_headlen(skb);
skb->len = first_len;
ipv6_hdr(skb)->payload_len = htons(first_len -
sizeof(struct ipv6hdr));
dst_hold(&rt->dst);
for (;;) {
/* Prepare header of the next frame,
* before previous one went down. */
if (frag) {
frag->ip_summed = CHECKSUM_NONE;
skb_reset_transport_header(frag);
fh = (struct frag_hdr *)__skb_push(frag, sizeof(struct frag_hdr));
__skb_push(frag, hlen);
skb_reset_network_header(frag);
memcpy(skb_network_header(frag), tmp_hdr,
hlen);
offset += skb->len - hlen - sizeof(struct frag_hdr);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(offset);
if (frag->next)
fh->frag_off |= htons(IP6_MF);
fh->identification = frag_id;
ipv6_hdr(frag)->payload_len =
htons(frag->len -
sizeof(struct ipv6hdr));
ip6_copy_metadata(frag, skb);
}
err = output(net, sk, skb);
if (!err)
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGCREATES);
if (err || !frag)
break;
skb = frag;
frag = skb->next;
skb->next = NULL;
}
kfree(tmp_hdr);
if (err == 0) {
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGOKS);
ip6_rt_put(rt);
return 0;
}
kfree_skb_list(frag);
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGFAILS);
ip6_rt_put(rt);
return err;
slow_path_clean:
skb_walk_frags(skb, frag2) {
if (frag2 == frag)
break;
frag2->sk = NULL;
frag2->destructor = NULL;
skb->truesize += frag2->truesize;
}
}
slow_path:
left = skb->len - hlen; /* Space per frame */
ptr = hlen; /* Where to start from */
/*
* Fragment the datagram.
*/
troom = rt->dst.dev->needed_tailroom;
/*
* Keep copying data until we run out.
*/
while (left > 0) {
u8 *fragnexthdr_offset;
len = left;
/* IF: it doesn't fit, use 'mtu' - the data space left */
if (len > mtu)
len = mtu;
/* IF: we are not sending up to and including the packet end
then align the next start on an eight byte boundary */
if (len < left) {
len &= ~7;
}
/* Allocate buffer */
frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) +
hroom + troom, GFP_ATOMIC);
if (!frag) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
/*
* Set up data on packet
*/
ip6_copy_metadata(frag, skb);
skb_reserve(frag, hroom);
skb_put(frag, len + hlen + sizeof(struct frag_hdr));
skb_reset_network_header(frag);
fh = (struct frag_hdr *)(skb_network_header(frag) + hlen);
frag->transport_header = (frag->network_header + hlen +
sizeof(struct frag_hdr));
/*
* Charge the memory for the fragment to any owner
* it might possess
*/
if (skb->sk)
skb_set_owner_w(frag, skb->sk);
/*
* Copy the packet header into the new buffer.
*/
skb_copy_from_linear_data(skb, skb_network_header(frag), hlen);
fragnexthdr_offset = skb_network_header(frag);
fragnexthdr_offset += prevhdr - skb_network_header(skb);
*fragnexthdr_offset = NEXTHDR_FRAGMENT;
/*
* Build fragment header.
*/
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->identification = frag_id;
/*
* Copy a block of the IP datagram.
*/
BUG_ON(skb_copy_bits(skb, ptr, skb_transport_header(frag),
len));
left -= len;
fh->frag_off = htons(offset);
if (left > 0)
fh->frag_off |= htons(IP6_MF);
ipv6_hdr(frag)->payload_len = htons(frag->len -
sizeof(struct ipv6hdr));
ptr += len;
offset += len;
/*
* Put this fragment into the sending queue.
*/
err = output(net, sk, frag);
if (err)
goto fail;
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGCREATES);
}
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGOKS);
consume_skb(skb);
return err;
fail_toobig:
if (skb->sk && dst_allfrag(skb_dst(skb)))
sk_nocaps_add(skb->sk, NETIF_F_GSO_MASK);
skb->dev = skb_dst(skb)->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
err = -EMSGSIZE;
fail:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return err;
}
static inline int ip6_rt_check(const struct rt6key *rt_key,
const struct in6_addr *fl_addr,
const struct in6_addr *addr_cache)
{
return (rt_key->plen != 128 || !ipv6_addr_equal(fl_addr, &rt_key->addr)) &&
(!addr_cache || !ipv6_addr_equal(fl_addr, addr_cache));
}
static struct dst_entry *ip6_sk_dst_check(struct sock *sk,
struct dst_entry *dst,
const struct flowi6 *fl6)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct rt6_info *rt;
if (!dst)
goto out;
if (dst->ops->family != AF_INET6) {
dst_release(dst);
return NULL;
}
rt = (struct rt6_info *)dst;
/* Yes, checking route validity in not connected
* case is not very simple. Take into account,
* that we do not support routing by source, TOS,
* and MSG_DONTROUTE --ANK (980726)
*
* 1. ip6_rt_check(): If route was host route,
* check that cached destination is current.
* If it is network route, we still may
* check its validity using saved pointer
* to the last used address: daddr_cache.
* We do not want to save whole address now,
* (because main consumer of this service
* is tcp, which has not this problem),
* so that the last trick works only on connected
* sockets.
* 2. oif also should be the same.
*/
if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) ||
#ifdef CONFIG_IPV6_SUBTREES
ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) ||
#endif
(!(fl6->flowi6_flags & FLOWI_FLAG_SKIP_NH_OIF) &&
(fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex))) {
dst_release(dst);
dst = NULL;
}
out:
return dst;
}
static int ip6_dst_lookup_tail(struct net *net, const struct sock *sk,
struct dst_entry **dst, struct flowi6 *fl6)
{
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
struct neighbour *n;
struct rt6_info *rt;
#endif
int err;
int flags = 0;
/* The correct way to handle this would be to do
* ip6_route_get_saddr, and then ip6_route_output; however,
* the route-specific preferred source forces the
* ip6_route_output call _before_ ip6_route_get_saddr.
*
* In source specific routing (no src=any default route),
* ip6_route_output will fail given src=any saddr, though, so
* that's why we try it again later.
*/
if (ipv6_addr_any(&fl6->saddr) && (!*dst || !(*dst)->error)) {
struct rt6_info *rt;
bool had_dst = *dst != NULL;
if (!had_dst)
*dst = ip6_route_output(net, sk, fl6);
rt = (*dst)->error ? NULL : (struct rt6_info *)*dst;
err = ip6_route_get_saddr(net, rt, &fl6->daddr,
sk ? inet6_sk(sk)->srcprefs : 0,
&fl6->saddr);
if (err)
goto out_err_release;
/* If we had an erroneous initial result, pretend it
* never existed and let the SA-enabled version take
* over.
*/
if (!had_dst && (*dst)->error) {
dst_release(*dst);
*dst = NULL;
}
if (fl6->flowi6_oif)
flags |= RT6_LOOKUP_F_IFACE;
}
if (!*dst)
*dst = ip6_route_output_flags(net, sk, fl6, flags);
err = (*dst)->error;
if (err)
goto out_err_release;
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
/*
* Here if the dst entry we've looked up
* has a neighbour entry that is in the INCOMPLETE
* state and the src address from the flow is
* marked as OPTIMISTIC, we release the found
* dst entry and replace it instead with the
* dst entry of the nexthop router
*/
rt = (struct rt6_info *) *dst;
rcu_read_lock_bh();
n = __ipv6_neigh_lookup_noref(rt->dst.dev,
rt6_nexthop(rt, &fl6->daddr));
err = n && !(n->nud_state & NUD_VALID) ? -EINVAL : 0;
rcu_read_unlock_bh();
if (err) {
struct inet6_ifaddr *ifp;
struct flowi6 fl_gw6;
int redirect;
ifp = ipv6_get_ifaddr(net, &fl6->saddr,
(*dst)->dev, 1);
redirect = (ifp && ifp->flags & IFA_F_OPTIMISTIC);
if (ifp)
in6_ifa_put(ifp);
if (redirect) {
/*
* We need to get the dst entry for the
* default router instead
*/
dst_release(*dst);
memcpy(&fl_gw6, fl6, sizeof(struct flowi6));
memset(&fl_gw6.daddr, 0, sizeof(struct in6_addr));
*dst = ip6_route_output(net, sk, &fl_gw6);
err = (*dst)->error;
if (err)
goto out_err_release;
}
}
#endif
if (ipv6_addr_v4mapped(&fl6->saddr) &&
!(ipv6_addr_v4mapped(&fl6->daddr) || ipv6_addr_any(&fl6->daddr))) {
err = -EAFNOSUPPORT;
goto out_err_release;
}
return 0;
out_err_release:
dst_release(*dst);
*dst = NULL;
if (err == -ENETUNREACH)
IP6_INC_STATS(net, NULL, IPSTATS_MIB_OUTNOROUTES);
return err;
}
/**
* ip6_dst_lookup - perform route lookup on flow
* @sk: socket which provides route info
* @dst: pointer to dst_entry * for result
* @fl6: flow to lookup
*
* This function performs a route lookup on the given flow.
*
* It returns zero on success, or a standard errno code on error.
*/
int ip6_dst_lookup(struct net *net, struct sock *sk, struct dst_entry **dst,
struct flowi6 *fl6)
{
*dst = NULL;
return ip6_dst_lookup_tail(net, sk, dst, fl6);
}
EXPORT_SYMBOL_GPL(ip6_dst_lookup);
/**
* ip6_dst_lookup_flow - perform route lookup on flow with ipsec
* @sk: socket which provides route info
* @fl6: flow to lookup
* @final_dst: final destination address for ipsec lookup
*
* This function performs a route lookup on the given flow.
*
* It returns a valid dst pointer on success, or a pointer encoded
* error code.
*/
struct dst_entry *ip6_dst_lookup_flow(const struct sock *sk, struct flowi6 *fl6,
const struct in6_addr *final_dst)
{
struct dst_entry *dst = NULL;
int err;
err = ip6_dst_lookup_tail(sock_net(sk), sk, &dst, fl6);
if (err)
return ERR_PTR(err);
if (final_dst)
fl6->daddr = *final_dst;
return xfrm_lookup_route(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0);
}
EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow);
/**
* ip6_sk_dst_lookup_flow - perform socket cached route lookup on flow
* @sk: socket which provides the dst cache and route info
* @fl6: flow to lookup
* @final_dst: final destination address for ipsec lookup
*
* This function performs a route lookup on the given flow with the
* possibility of using the cached route in the socket if it is valid.
* It will take the socket dst lock when operating on the dst cache.
* As a result, this function can only be used in process context.
*
* It returns a valid dst pointer on success, or a pointer encoded
* error code.
*/
struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6,
const struct in6_addr *final_dst)
{
struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie);
dst = ip6_sk_dst_check(sk, dst, fl6);
if (!dst)
dst = ip6_dst_lookup_flow(sk, fl6, final_dst);
return dst;
}
EXPORT_SYMBOL_GPL(ip6_sk_dst_lookup_flow);
static inline int ip6_ufo_append_data(struct sock *sk,
struct sk_buff_head *queue,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int length, int hh_len, int fragheaderlen,
int exthdrlen, int transhdrlen, int mtu,
unsigned int flags, const struct flowi6 *fl6)
{
struct sk_buff *skb;
int err;
/* There is support for UDP large send offload by network
* device, so create one single skb packet containing complete
* udp datagram
*/
skb = skb_peek_tail(queue);
if (!skb) {
skb = sock_alloc_send_skb(sk,
hh_len + fragheaderlen + transhdrlen + 20,
(flags & MSG_DONTWAIT), &err);
if (!skb)
return err;
/* reserve space for Hardware header */
skb_reserve(skb, hh_len);
/* create space for UDP/IP header */
skb_put(skb, fragheaderlen + transhdrlen);
/* initialize network header pointer */
skb_set_network_header(skb, exthdrlen);
/* initialize protocol header pointer */
skb->transport_header = skb->network_header + fragheaderlen;
skb->protocol = htons(ETH_P_IPV6);
skb->csum = 0;
if (flags & MSG_CONFIRM)
skb_set_dst_pending_confirm(skb, 1);
__skb_queue_tail(queue, skb);
} else if (skb_is_gso(skb)) {
goto append;
}
skb->ip_summed = CHECKSUM_PARTIAL;
/* Specify the length of each IPv6 datagram fragment.
* It has to be a multiple of 8.
*/
skb_shinfo(skb)->gso_size = (mtu - fragheaderlen -
sizeof(struct frag_hdr)) & ~7;
skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
skb_shinfo(skb)->ip6_frag_id = ipv6_select_ident(sock_net(sk),
&fl6->daddr,
&fl6->saddr);
append:
return skb_append_datato_frags(sk, skb, getfrag, from,
(length - transhdrlen));
}
static inline struct ipv6_opt_hdr *ip6_opt_dup(struct ipv6_opt_hdr *src,
gfp_t gfp)
{
return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL;
}
static inline struct ipv6_rt_hdr *ip6_rthdr_dup(struct ipv6_rt_hdr *src,
gfp_t gfp)
{
return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL;
}
static void ip6_append_data_mtu(unsigned int *mtu,
int *maxfraglen,
unsigned int fragheaderlen,
struct sk_buff *skb,
struct rt6_info *rt,
unsigned int orig_mtu)
{
if (!(rt->dst.flags & DST_XFRM_TUNNEL)) {
if (!skb) {
/* first fragment, reserve header_len */
*mtu = orig_mtu - rt->dst.header_len;
} else {
/*
* this fragment is not first, the headers
* space is regarded as data space.
*/
*mtu = orig_mtu;
}
*maxfraglen = ((*mtu - fragheaderlen) & ~7)
+ fragheaderlen - sizeof(struct frag_hdr);
}
}
static int ip6_setup_cork(struct sock *sk, struct inet_cork_full *cork,
struct inet6_cork *v6_cork, struct ipcm6_cookie *ipc6,
struct rt6_info *rt, struct flowi6 *fl6)
{
struct ipv6_pinfo *np = inet6_sk(sk);
unsigned int mtu;
struct ipv6_txoptions *opt = ipc6->opt;
/*
* setup for corking
*/
if (opt) {
if (WARN_ON(v6_cork->opt))
return -EINVAL;
v6_cork->opt = kzalloc(opt->tot_len, sk->sk_allocation);
if (unlikely(!v6_cork->opt))
return -ENOBUFS;
v6_cork->opt->tot_len = opt->tot_len;
v6_cork->opt->opt_flen = opt->opt_flen;
v6_cork->opt->opt_nflen = opt->opt_nflen;
v6_cork->opt->dst0opt = ip6_opt_dup(opt->dst0opt,
sk->sk_allocation);
if (opt->dst0opt && !v6_cork->opt->dst0opt)
return -ENOBUFS;
v6_cork->opt->dst1opt = ip6_opt_dup(opt->dst1opt,
sk->sk_allocation);
if (opt->dst1opt && !v6_cork->opt->dst1opt)
return -ENOBUFS;
v6_cork->opt->hopopt = ip6_opt_dup(opt->hopopt,
sk->sk_allocation);
if (opt->hopopt && !v6_cork->opt->hopopt)
return -ENOBUFS;
v6_cork->opt->srcrt = ip6_rthdr_dup(opt->srcrt,
sk->sk_allocation);
if (opt->srcrt && !v6_cork->opt->srcrt)
return -ENOBUFS;
/* need source address above miyazawa*/
}
dst_hold(&rt->dst);
cork->base.dst = &rt->dst;
cork->fl.u.ip6 = *fl6;
v6_cork->hop_limit = ipc6->hlimit;
v6_cork->tclass = ipc6->tclass;
if (rt->dst.flags & DST_XFRM_TUNNEL)
mtu = np->pmtudisc >= IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(&rt->dst);
else
mtu = np->pmtudisc >= IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(rt->dst.path);
if (np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
cork->base.fragsize = mtu;
if (dst_allfrag(rt->dst.path))
cork->base.flags |= IPCORK_ALLFRAG;
cork->base.length = 0;
return 0;
}
static int __ip6_append_data(struct sock *sk,
struct flowi6 *fl6,
struct sk_buff_head *queue,
struct inet_cork *cork,
struct inet6_cork *v6_cork,
struct page_frag *pfrag,
int getfrag(void *from, char *to, int offset,
int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
unsigned int flags, struct ipcm6_cookie *ipc6,
const struct sockcm_cookie *sockc)
{
struct sk_buff *skb, *skb_prev = NULL;
unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu;
int exthdrlen = 0;
int dst_exthdrlen = 0;
int hh_len;
int copy;
int err;
int offset = 0;
__u8 tx_flags = 0;
u32 tskey = 0;
struct rt6_info *rt = (struct rt6_info *)cork->dst;
struct ipv6_txoptions *opt = v6_cork->opt;
int csummode = CHECKSUM_NONE;
unsigned int maxnonfragsize, headersize;
skb = skb_peek_tail(queue);
if (!skb) {
exthdrlen = opt ? opt->opt_flen : 0;
dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
}
mtu = cork->fragsize;
orig_mtu = mtu;
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
(opt ? opt->opt_nflen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen -
sizeof(struct frag_hdr);
headersize = sizeof(struct ipv6hdr) +
(opt ? opt->opt_flen + opt->opt_nflen : 0) +
(dst_allfrag(&rt->dst) ?
sizeof(struct frag_hdr) : 0) +
rt->rt6i_nfheader_len;
if (cork->length + length > mtu - headersize && ipc6->dontfrag &&
(sk->sk_protocol == IPPROTO_UDP ||
sk->sk_protocol == IPPROTO_RAW)) {
ipv6_local_rxpmtu(sk, fl6, mtu - headersize +
sizeof(struct ipv6hdr));
goto emsgsize;
}
if (ip6_sk_ignore_df(sk))
maxnonfragsize = sizeof(struct ipv6hdr) + IPV6_MAXPLEN;
else
maxnonfragsize = mtu;
if (cork->length + length > maxnonfragsize - headersize) {
emsgsize:
ipv6_local_error(sk, EMSGSIZE, fl6,
mtu - headersize +
sizeof(struct ipv6hdr));
return -EMSGSIZE;
}
/* CHECKSUM_PARTIAL only with no extension headers and when
* we are not going to fragment
*/
if (transhdrlen && sk->sk_protocol == IPPROTO_UDP &&
headersize == sizeof(struct ipv6hdr) &&
length <= mtu - headersize &&
!(flags & MSG_MORE) &&
rt->dst.dev->features & (NETIF_F_IPV6_CSUM | NETIF_F_HW_CSUM))
csummode = CHECKSUM_PARTIAL;
if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) {
sock_tx_timestamp(sk, sockc->tsflags, &tx_flags);
if (tx_flags & SKBTX_ANY_SW_TSTAMP &&
sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)
tskey = sk->sk_tskey++;
}
/*
* Let's try using as much space as possible.
* Use MTU if total length of the message fits into the MTU.
* Otherwise, we need to reserve fragment header and
* fragment alignment (= 8-15 octects, in total).
*
* Note that we may need to "move" the data from the tail of
* of the buffer to the new fragment when we split
* the message.
*
* FIXME: It may be fragmented into multiple chunks
* at once if non-fragmentable extension headers
* are too large.
* --yoshfuji
*/
cork->length += length;
if ((((length + fragheaderlen) > mtu) ||
(skb && skb_is_gso(skb))) &&
(sk->sk_protocol == IPPROTO_UDP) &&
(rt->dst.dev->features & NETIF_F_UFO) && !dst_xfrm(&rt->dst) &&
(sk->sk_type == SOCK_DGRAM) && !udp_get_no_check6_tx(sk)) {
err = ip6_ufo_append_data(sk, queue, getfrag, from, length,
hh_len, fragheaderlen, exthdrlen,
transhdrlen, mtu, flags, fl6);
if (err)
goto error;
return 0;
}
if (!skb)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
alloc_new_skb:
/* There's no room in the current skb */
if (skb)
fraggap = skb->len - maxfraglen;
else
fraggap = 0;
/* update mtu and maxfraglen if necessary */
if (!skb || !skb_prev)
ip6_append_data_mtu(&mtu, &maxfraglen,
fragheaderlen, skb, rt,
orig_mtu);
skb_prev = skb;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)
datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = datalen + fragheaderlen;
alloclen += dst_exthdrlen;
if (datalen != length + fraggap) {
/*
* this is not the last fragment, the trailer
* space is regarded as data space.
*/
datalen += rt->dst.trailer_len;
}
alloclen += rt->dst.trailer_len;
fraglen = datalen + fragheaderlen;
/*
* We just reserve space for fragment header.
* Note: this may be overallocation if the message
* (without MSG_MORE) fits into the MTU.
*/
alloclen += sizeof(struct frag_hdr);
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (atomic_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len, 1,
sk->sk_allocation);
if (unlikely(!skb))
err = -ENOBUFS;
}
if (!skb)
goto error;
/*
* Fill in the control structures
*/
skb->protocol = htons(ETH_P_IPV6);
skb->ip_summed = csummode;
skb->csum = 0;
/* reserve for fragmentation and ipsec header */
skb_reserve(skb, hh_len + sizeof(struct frag_hdr) +
dst_exthdrlen);
/* Only the initial fragment is time stamped */
skb_shinfo(skb)->tx_flags = tx_flags;
tx_flags = 0;
skb_shinfo(skb)->tskey = tskey;
tskey = 0;
/*
* Find where to start putting bytes
*/
data = skb_put(skb, fraglen);
skb_set_network_header(skb, exthdrlen);
data += fragheaderlen;
skb->transport_header = (skb->network_header +
fragheaderlen);
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
copy = datalen - transhdrlen - fraggap;
if (copy < 0) {
err = -EINVAL;
kfree_skb(skb);
goto error;
} else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
if ((flags & MSG_CONFIRM) && !skb_prev)
skb_set_dst_pending_confirm(skb, 1);
/*
* Put the packet on the pending queue
*/
__skb_queue_tail(queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
err = -ENOMEM;
if (!sk_page_frag_refill(sk, pfrag))
goto error;
if (!skb_can_coalesce(skb, i, pfrag->page,
pfrag->offset)) {
err = -EMSGSIZE;
if (i == MAX_SKB_FRAGS)
goto error;
__skb_fill_page_desc(skb, i, pfrag->page,
pfrag->offset, 0);
skb_shinfo(skb)->nr_frags = ++i;
get_page(pfrag->page);
}
copy = min_t(int, copy, pfrag->size - pfrag->offset);
if (getfrag(from,
page_address(pfrag->page) + pfrag->offset,
offset, copy, skb->len, skb) < 0)
goto error_efault;
pfrag->offset += copy;
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error_efault:
err = -EFAULT;
error:
cork->length -= length;
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
return err;
}
int ip6_append_data(struct sock *sk,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
struct ipcm6_cookie *ipc6, struct flowi6 *fl6,
struct rt6_info *rt, unsigned int flags,
const struct sockcm_cookie *sockc)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
int exthdrlen;
int err;
if (flags&MSG_PROBE)
return 0;
if (skb_queue_empty(&sk->sk_write_queue)) {
/*
* setup for corking
*/
err = ip6_setup_cork(sk, &inet->cork, &np->cork,
ipc6, rt, fl6);
if (err)
return err;
exthdrlen = (ipc6->opt ? ipc6->opt->opt_flen : 0);
length += exthdrlen;
transhdrlen += exthdrlen;
} else {
fl6 = &inet->cork.fl.u.ip6;
transhdrlen = 0;
}
return __ip6_append_data(sk, fl6, &sk->sk_write_queue, &inet->cork.base,
&np->cork, sk_page_frag(sk), getfrag,
from, length, transhdrlen, flags, ipc6, sockc);
}
EXPORT_SYMBOL_GPL(ip6_append_data);
static void ip6_cork_release(struct inet_cork_full *cork,
struct inet6_cork *v6_cork)
{
if (v6_cork->opt) {
kfree(v6_cork->opt->dst0opt);
kfree(v6_cork->opt->dst1opt);
kfree(v6_cork->opt->hopopt);
kfree(v6_cork->opt->srcrt);
kfree(v6_cork->opt);
v6_cork->opt = NULL;
}
if (cork->base.dst) {
dst_release(cork->base.dst);
cork->base.dst = NULL;
cork->base.flags &= ~IPCORK_ALLFRAG;
}
memset(&cork->fl, 0, sizeof(cork->fl));
}
struct sk_buff *__ip6_make_skb(struct sock *sk,
struct sk_buff_head *queue,
struct inet_cork_full *cork,
struct inet6_cork *v6_cork)
{
struct sk_buff *skb, *tmp_skb;
struct sk_buff **tail_skb;
struct in6_addr final_dst_buf, *final_dst = &final_dst_buf;
struct ipv6_pinfo *np = inet6_sk(sk);
struct net *net = sock_net(sk);
struct ipv6hdr *hdr;
struct ipv6_txoptions *opt = v6_cork->opt;
struct rt6_info *rt = (struct rt6_info *)cork->base.dst;
struct flowi6 *fl6 = &cork->fl.u.ip6;
unsigned char proto = fl6->flowi6_proto;
skb = __skb_dequeue(queue);
if (!skb)
goto out;
tail_skb = &(skb_shinfo(skb)->frag_list);
/* move skb->data to ip header from ext header */
if (skb->data < skb_network_header(skb))
__skb_pull(skb, skb_network_offset(skb));
while ((tmp_skb = __skb_dequeue(queue)) != NULL) {
__skb_pull(tmp_skb, skb_network_header_len(skb));
*tail_skb = tmp_skb;
tail_skb = &(tmp_skb->next);
skb->len += tmp_skb->len;
skb->data_len += tmp_skb->len;
skb->truesize += tmp_skb->truesize;
tmp_skb->destructor = NULL;
tmp_skb->sk = NULL;
}
/* Allow local fragmentation. */
skb->ignore_df = ip6_sk_ignore_df(sk);
*final_dst = fl6->daddr;
__skb_pull(skb, skb_network_header_len(skb));
if (opt && opt->opt_flen)
ipv6_push_frag_opts(skb, opt, &proto);
if (opt && opt->opt_nflen)
ipv6_push_nfrag_opts(skb, opt, &proto, &final_dst, &fl6->saddr);
skb_push(skb, sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
hdr = ipv6_hdr(skb);
ip6_flow_hdr(hdr, v6_cork->tclass,
ip6_make_flowlabel(net, skb, fl6->flowlabel,
np->autoflowlabel, fl6));
hdr->hop_limit = v6_cork->hop_limit;
hdr->nexthdr = proto;
hdr->saddr = fl6->saddr;
hdr->daddr = *final_dst;
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
skb_dst_set(skb, dst_clone(&rt->dst));
IP6_UPD_PO_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUT, skb->len);
if (proto == IPPROTO_ICMPV6) {
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
ICMP6MSGOUT_INC_STATS(net, idev, icmp6_hdr(skb)->icmp6_type);
ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTMSGS);
}
ip6_cork_release(cork, v6_cork);
out:
return skb;
}
int ip6_send_skb(struct sk_buff *skb)
{
struct net *net = sock_net(skb->sk);
struct rt6_info *rt = (struct rt6_info *)skb_dst(skb);
int err;
err = ip6_local_out(net, skb->sk, skb);
if (err) {
if (err > 0)
err = net_xmit_errno(err);
if (err)
IP6_INC_STATS(net, rt->rt6i_idev,
IPSTATS_MIB_OUTDISCARDS);
}
return err;
}
int ip6_push_pending_frames(struct sock *sk)
{
struct sk_buff *skb;
skb = ip6_finish_skb(sk);
if (!skb)
return 0;
return ip6_send_skb(skb);
}
EXPORT_SYMBOL_GPL(ip6_push_pending_frames);
static void __ip6_flush_pending_frames(struct sock *sk,
struct sk_buff_head *queue,
struct inet_cork_full *cork,
struct inet6_cork *v6_cork)
{
struct sk_buff *skb;
while ((skb = __skb_dequeue_tail(queue)) != NULL) {
if (skb_dst(skb))
IP6_INC_STATS(sock_net(sk), ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
}
ip6_cork_release(cork, v6_cork);
}
void ip6_flush_pending_frames(struct sock *sk)
{
__ip6_flush_pending_frames(sk, &sk->sk_write_queue,
&inet_sk(sk)->cork, &inet6_sk(sk)->cork);
}
EXPORT_SYMBOL_GPL(ip6_flush_pending_frames);
struct sk_buff *ip6_make_skb(struct sock *sk,
int getfrag(void *from, char *to, int offset,
int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
struct ipcm6_cookie *ipc6, struct flowi6 *fl6,
struct rt6_info *rt, unsigned int flags,
const struct sockcm_cookie *sockc)
{
struct inet_cork_full cork;
struct inet6_cork v6_cork;
struct sk_buff_head queue;
int exthdrlen = (ipc6->opt ? ipc6->opt->opt_flen : 0);
int err;
if (flags & MSG_PROBE)
return NULL;
__skb_queue_head_init(&queue);
cork.base.flags = 0;
cork.base.addr = 0;
cork.base.opt = NULL;
v6_cork.opt = NULL;
err = ip6_setup_cork(sk, &cork, &v6_cork, ipc6, rt, fl6);
if (err)
return ERR_PTR(err);
if (ipc6->dontfrag < 0)
ipc6->dontfrag = inet6_sk(sk)->dontfrag;
err = __ip6_append_data(sk, fl6, &queue, &cork.base, &v6_cork,
¤t->task_frag, getfrag, from,
length + exthdrlen, transhdrlen + exthdrlen,
flags, ipc6, sockc);
if (err) {
__ip6_flush_pending_frames(sk, &queue, &cork, &v6_cork);
return ERR_PTR(err);
}
return __ip6_make_skb(sk, &queue, &cork, &v6_cork);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3358_1 |
crossvul-cpp_data_good_2673_0 | /*
* Copyright (c) 2009
* Siemens AG, All rights reserved.
* Dmitry Eremin-Solenikov (dbaryshkov@gmail.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IEEE 802.15.4 printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static const char *ftypes[] = {
"Beacon", /* 0 */
"Data", /* 1 */
"ACK", /* 2 */
"Command", /* 3 */
"Reserved (0x4)", /* 4 */
"Reserved (0x5)", /* 5 */
"Reserved (0x6)", /* 6 */
"Reserved (0x7)", /* 7 */
};
/*
* Frame Control subfields.
*/
#define FC_FRAME_TYPE(fc) ((fc) & 0x7)
#define FC_SECURITY_ENABLED 0x0008
#define FC_FRAME_PENDING 0x0010
#define FC_ACK_REQUEST 0x0020
#define FC_PAN_ID_COMPRESSION 0x0040
#define FC_DEST_ADDRESSING_MODE(fc) (((fc) >> 10) & 0x3)
#define FC_FRAME_VERSION(fc) (((fc) >> 12) & 0x3)
#define FC_SRC_ADDRESSING_MODE(fc) (((fc) >> 14) & 0x3)
#define FC_ADDRESSING_MODE_NONE 0x00
#define FC_ADDRESSING_MODE_RESERVED 0x01
#define FC_ADDRESSING_MODE_SHORT 0x02
#define FC_ADDRESSING_MODE_LONG 0x03
u_int
ieee802_15_4_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int hdrlen;
uint16_t fc;
uint8_t seq;
uint16_t panid = 0;
if (caplen < 3) {
ND_PRINT((ndo, "[|802.15.4]"));
return caplen;
}
hdrlen = 3;
fc = EXTRACT_LE_16BITS(p);
seq = EXTRACT_LE_8BITS(p + 2);
p += 3;
caplen -= 3;
ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)]));
if (ndo->ndo_vflag)
ND_PRINT((ndo,"seq %02x ", seq));
/*
* Destination address and PAN ID, if present.
*/
switch (FC_DEST_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (fc & FC_PAN_ID_COMPRESSION) {
/*
* PAN ID compression; this requires that both
* the source and destination addresses be present,
* but the destination address is missing.
*/
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved destination addressing mode"));
return hdrlen;
case FC_ADDRESSING_MODE_SHORT:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"< "));
/*
* Source address and PAN ID, if present.
*/
switch (FC_SRC_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved source addressing mode"));
return 0;
case FC_ADDRESSING_MODE_SHORT:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
return hdrlen;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2673_0 |
crossvul-cpp_data_bad_262_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)
* Support for LMP service discovery extensions (defined by OIF UNI 1.0)
* added by Manu Pathak (mapathak@cisco.com), May 2005
*/
/* \summary: Link Management Protocol (LMP) printer */
/* specification: RFC 4204 */
/* OIF UNI 1.0: http://www.oiforum.com/public/documents/OIF-UNI-01.0.pdf */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "gmpls.h"
/*
* LMP 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
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Vers | (Reserved) | Flags | Msg Type |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | LMP Length | (Reserved) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lmp_common_header {
uint8_t version_res[2];
uint8_t flags;
uint8_t msg_type;
uint8_t length[2];
uint8_t reserved[2];
};
#define LMP_VERSION 1
#define LMP_EXTRACT_VERSION(x) (((x)&0xf0)>>4)
static const struct tok lmp_header_flag_values[] = {
{ 0x01, "Control Channel Down"},
{ 0x02, "LMP restart"},
{ 0, NULL}
};
static const struct tok lmp_obj_te_link_flag_values[] = {
{ 0x01, "Fault Management Supported"},
{ 0x02, "Link Verification Supported"},
{ 0, NULL}
};
static const struct tok lmp_obj_data_link_flag_values[] = {
{ 0x01, "Data Link Port"},
{ 0x02, "Allocated for user traffic"},
{ 0x04, "Failed link"},
{ 0, NULL}
};
static const struct tok lmp_obj_channel_status_values[] = {
{ 1, "Signal Okay"},
{ 2, "Signal Degraded"},
{ 3, "Signal Fail"},
{ 0, NULL}
};
static const struct tok lmp_obj_begin_verify_flag_values[] = {
{ 0x0001, "Verify all links"},
{ 0x0002, "Data link type"},
{ 0, NULL}
};
static const struct tok lmp_obj_begin_verify_error_values[] = {
{ 0x01, "Link Verification Procedure Not supported"},
{ 0x02, "Unwilling to verify"},
{ 0x04, "Unsupported verification transport mechanism"},
{ 0x08, "Link-Id configuration error"},
{ 0x10, "Unknown object c-type"},
{ 0, NULL}
};
static const struct tok lmp_obj_link_summary_error_values[] = {
{ 0x01, "Unacceptable non-negotiable LINK-SUMMARY parameters"},
{ 0x02, "Renegotiate LINK-SUMMARY parameters"},
{ 0x04, "Invalid TE-LINK Object"},
{ 0x08, "Invalid DATA-LINK Object"},
{ 0x10, "Unknown TE-LINK Object c-type"},
{ 0x20, "Unknown DATA-LINK Object c-type"},
{ 0, NULL}
};
/* Service Config Supported Protocols Flags */
static const struct tok lmp_obj_service_config_sp_flag_values[] = {
{ 0x01, "RSVP Supported"},
{ 0x02, "LDP Supported"},
{ 0, NULL}
};
/* Service Config Client Port Service Attribute Transparency Flags */
static const struct tok lmp_obj_service_config_cpsa_tp_flag_values[] = {
{ 0x01, "Path/VC Overhead Transparency Supported"},
{ 0x02, "Line/MS Overhead Transparency Supported"},
{ 0x04, "Section/RS Overhead Transparency Supported"},
{ 0, NULL}
};
/* Service Config Client Port Service Attribute Contiguous Concatenation Types Flags */
static const struct tok lmp_obj_service_config_cpsa_cct_flag_values[] = {
{ 0x01, "Contiguous Concatenation Types Supported"},
{ 0, NULL}
};
/* Service Config Network Service Attributes Transparency Flags */
static const struct tok lmp_obj_service_config_nsa_transparency_flag_values[] = {
{ 0x01, "Standard SOH/RSOH Transparency Supported"},
{ 0x02, "Standard LOH/MSOH Transparency Supported"},
{ 0, NULL}
};
/* Service Config Network Service Attributes TCM Monitoring Flags */
static const struct tok lmp_obj_service_config_nsa_tcm_flag_values[] = {
{ 0x01, "Transparent Tandem Connection Monitoring Supported"},
{ 0, NULL}
};
/* Network Service Attributes Network Diversity Flags */
static const struct tok lmp_obj_service_config_nsa_network_diversity_flag_values[] = {
{ 0x01, "Node Diversity Supported"},
{ 0x02, "Link Diversity Supported"},
{ 0x04, "SRLG Diversity Supported"},
{ 0, NULL}
};
#define LMP_MSGTYPE_CONFIG 1
#define LMP_MSGTYPE_CONFIG_ACK 2
#define LMP_MSGTYPE_CONFIG_NACK 3
#define LMP_MSGTYPE_HELLO 4
#define LMP_MSGTYPE_VERIFY_BEGIN 5
#define LMP_MSGTYPE_VERIFY_BEGIN_ACK 6
#define LMP_MSGTYPE_VERIFY_BEGIN_NACK 7
#define LMP_MSGTYPE_VERIFY_END 8
#define LMP_MSGTYPE_VERIFY_END_ACK 9
#define LMP_MSGTYPE_TEST 10
#define LMP_MSGTYPE_TEST_STATUS_SUCCESS 11
#define LMP_MSGTYPE_TEST_STATUS_FAILURE 12
#define LMP_MSGTYPE_TEST_STATUS_ACK 13
#define LMP_MSGTYPE_LINK_SUMMARY 14
#define LMP_MSGTYPE_LINK_SUMMARY_ACK 15
#define LMP_MSGTYPE_LINK_SUMMARY_NACK 16
#define LMP_MSGTYPE_CHANNEL_STATUS 17
#define LMP_MSGTYPE_CHANNEL_STATUS_ACK 18
#define LMP_MSGTYPE_CHANNEL_STATUS_REQ 19
#define LMP_MSGTYPE_CHANNEL_STATUS_RESP 20
/* LMP Service Discovery message types defined by UNI 1.0 */
#define LMP_MSGTYPE_SERVICE_CONFIG 50
#define LMP_MSGTYPE_SERVICE_CONFIG_ACK 51
#define LMP_MSGTYPE_SERVICE_CONFIG_NACK 52
static const struct tok lmp_msg_type_values[] = {
{ LMP_MSGTYPE_CONFIG, "Config"},
{ LMP_MSGTYPE_CONFIG_ACK, "Config ACK"},
{ LMP_MSGTYPE_CONFIG_NACK, "Config NACK"},
{ LMP_MSGTYPE_HELLO, "Hello"},
{ LMP_MSGTYPE_VERIFY_BEGIN, "Begin Verify"},
{ LMP_MSGTYPE_VERIFY_BEGIN_ACK, "Begin Verify ACK"},
{ LMP_MSGTYPE_VERIFY_BEGIN_NACK, "Begin Verify NACK"},
{ LMP_MSGTYPE_VERIFY_END, "End Verify"},
{ LMP_MSGTYPE_VERIFY_END_ACK, "End Verify ACK"},
{ LMP_MSGTYPE_TEST, "Test"},
{ LMP_MSGTYPE_TEST_STATUS_SUCCESS, "Test Status Success"},
{ LMP_MSGTYPE_TEST_STATUS_FAILURE, "Test Status Failure"},
{ LMP_MSGTYPE_TEST_STATUS_ACK, "Test Status ACK"},
{ LMP_MSGTYPE_LINK_SUMMARY, "Link Summary"},
{ LMP_MSGTYPE_LINK_SUMMARY_ACK, "Link Summary ACK"},
{ LMP_MSGTYPE_LINK_SUMMARY_NACK, "Link Summary NACK"},
{ LMP_MSGTYPE_CHANNEL_STATUS, "Channel Status"},
{ LMP_MSGTYPE_CHANNEL_STATUS_ACK, "Channel Status ACK"},
{ LMP_MSGTYPE_CHANNEL_STATUS_REQ, "Channel Status Request"},
{ LMP_MSGTYPE_CHANNEL_STATUS_RESP, "Channel Status Response"},
{ LMP_MSGTYPE_SERVICE_CONFIG, "Service Config"},
{ LMP_MSGTYPE_SERVICE_CONFIG_ACK, "Service Config ACK"},
{ LMP_MSGTYPE_SERVICE_CONFIG_NACK, "Service Config NACK"},
{ 0, NULL}
};
/*
* LMP object 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
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |N| C-Type | Class | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | |
* // (object contents) //
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lmp_object_header {
uint8_t ctype;
uint8_t class_num;
uint8_t length[2];
};
#define LMP_OBJ_CC_ID 1
#define LMP_OBJ_NODE_ID 2
#define LMP_OBJ_LINK_ID 3
#define LMP_OBJ_INTERFACE_ID 4
#define LMP_OBJ_MESSAGE_ID 5
#define LMP_OBJ_CONFIG 6
#define LMP_OBJ_HELLO 7
#define LMP_OBJ_VERIFY_BEGIN 8
#define LMP_OBJ_VERIFY_BEGIN_ACK 9
#define LMP_OBJ_VERIFY_ID 10
#define LMP_OBJ_TE_LINK 11
#define LMP_OBJ_DATA_LINK 12
#define LMP_OBJ_CHANNEL_STATUS 13
#define LMP_OBJ_CHANNEL_STATUS_REQ 14
#define LMP_OBJ_ERROR_CODE 20
#define LMP_OBJ_SERVICE_CONFIG 51 /* defined in UNI 1.0 */
static const struct tok lmp_obj_values[] = {
{ LMP_OBJ_CC_ID, "Control Channel ID" },
{ LMP_OBJ_NODE_ID, "Node ID" },
{ LMP_OBJ_LINK_ID, "Link ID" },
{ LMP_OBJ_INTERFACE_ID, "Interface ID" },
{ LMP_OBJ_MESSAGE_ID, "Message ID" },
{ LMP_OBJ_CONFIG, "Configuration" },
{ LMP_OBJ_HELLO, "Hello" },
{ LMP_OBJ_VERIFY_BEGIN, "Verify Begin" },
{ LMP_OBJ_VERIFY_BEGIN_ACK, "Verify Begin ACK" },
{ LMP_OBJ_VERIFY_ID, "Verify ID" },
{ LMP_OBJ_TE_LINK, "TE Link" },
{ LMP_OBJ_DATA_LINK, "Data Link" },
{ LMP_OBJ_CHANNEL_STATUS, "Channel Status" },
{ LMP_OBJ_CHANNEL_STATUS_REQ, "Channel Status Request" },
{ LMP_OBJ_ERROR_CODE, "Error Code" },
{ LMP_OBJ_SERVICE_CONFIG, "Service Config" },
{ 0, NULL}
};
#define INT_SWITCHING_TYPE_SUBOBJ 1
#define WAVELENGTH_SUBOBJ 2
static const struct tok lmp_data_link_subobj[] = {
{ INT_SWITCHING_TYPE_SUBOBJ, "Interface Switching Type" },
{ WAVELENGTH_SUBOBJ , "Wavelength" },
{ 0, NULL}
};
#define LMP_CTYPE_IPV4 1
#define LMP_CTYPE_IPV6 2
#define LMP_CTYPE_LOC 1
#define LMP_CTYPE_RMT 2
#define LMP_CTYPE_UNMD 3
#define LMP_CTYPE_IPV4_LOC 1
#define LMP_CTYPE_IPV4_RMT 2
#define LMP_CTYPE_IPV6_LOC 3
#define LMP_CTYPE_IPV6_RMT 4
#define LMP_CTYPE_UNMD_LOC 5
#define LMP_CTYPE_UNMD_RMT 6
#define LMP_CTYPE_1 1
#define LMP_CTYPE_2 2
#define LMP_CTYPE_HELLO_CONFIG 1
#define LMP_CTYPE_HELLO 1
#define LMP_CTYPE_BEGIN_VERIFY_ERROR 1
#define LMP_CTYPE_LINK_SUMMARY_ERROR 2
/* C-Types for Service Config Object */
#define LMP_CTYPE_SERVICE_CONFIG_SP 1
#define LMP_CTYPE_SERVICE_CONFIG_CPSA 2
#define LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM 3
#define LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY 4
/*
* Different link types allowed in the Client Port Service Attributes
* subobject defined for LMP Service Discovery in the UNI 1.0 spec
*/
#define LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SDH 5 /* UNI 1.0 Sec 9.4.2 */
#define LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SONET 6 /* UNI 1.0 Sec 9.4.2 */
/*
* 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 lmp_ctype_values[] = {
{ 256*LMP_OBJ_CC_ID+LMP_CTYPE_LOC, "Local" },
{ 256*LMP_OBJ_CC_ID+LMP_CTYPE_RMT, "Remote" },
{ 256*LMP_OBJ_NODE_ID+LMP_CTYPE_LOC, "Local" },
{ 256*LMP_OBJ_NODE_ID+LMP_CTYPE_RMT, "Remote" },
{ 256*LMP_OBJ_LINK_ID+LMP_CTYPE_IPV4_LOC, "IPv4 Local" },
{ 256*LMP_OBJ_LINK_ID+LMP_CTYPE_IPV4_RMT, "IPv4 Remote" },
{ 256*LMP_OBJ_LINK_ID+LMP_CTYPE_IPV6_LOC, "IPv6 Local" },
{ 256*LMP_OBJ_LINK_ID+LMP_CTYPE_IPV6_RMT, "IPv6 Remote" },
{ 256*LMP_OBJ_LINK_ID+LMP_CTYPE_UNMD_LOC, "Unnumbered Local" },
{ 256*LMP_OBJ_LINK_ID+LMP_CTYPE_UNMD_RMT, "Unnumbered Remote" },
{ 256*LMP_OBJ_INTERFACE_ID+LMP_CTYPE_IPV4_LOC, "IPv4 Local" },
{ 256*LMP_OBJ_INTERFACE_ID+LMP_CTYPE_IPV4_RMT, "IPv4 Remote" },
{ 256*LMP_OBJ_INTERFACE_ID+LMP_CTYPE_IPV6_LOC, "IPv6 Local" },
{ 256*LMP_OBJ_INTERFACE_ID+LMP_CTYPE_IPV6_RMT, "IPv6 Remote" },
{ 256*LMP_OBJ_INTERFACE_ID+LMP_CTYPE_UNMD_LOC, "Unnumbered Local" },
{ 256*LMP_OBJ_INTERFACE_ID+LMP_CTYPE_UNMD_RMT, "Unnumbered Remote" },
{ 256*LMP_OBJ_MESSAGE_ID+LMP_CTYPE_1, "1" },
{ 256*LMP_OBJ_MESSAGE_ID+LMP_CTYPE_2, "2" },
{ 256*LMP_OBJ_CONFIG+LMP_CTYPE_1, "1" },
{ 256*LMP_OBJ_HELLO+LMP_CTYPE_1, "1" },
{ 256*LMP_OBJ_VERIFY_BEGIN+LMP_CTYPE_1, "1" },
{ 256*LMP_OBJ_VERIFY_BEGIN_ACK+LMP_CTYPE_1, "1" },
{ 256*LMP_OBJ_VERIFY_ID+LMP_CTYPE_1, "1" },
{ 256*LMP_OBJ_TE_LINK+LMP_CTYPE_IPV4, "IPv4" },
{ 256*LMP_OBJ_TE_LINK+LMP_CTYPE_IPV6, "IPv6" },
{ 256*LMP_OBJ_TE_LINK+LMP_CTYPE_UNMD, "Unnumbered" },
{ 256*LMP_OBJ_DATA_LINK+LMP_CTYPE_IPV4, "IPv4" },
{ 256*LMP_OBJ_DATA_LINK+LMP_CTYPE_IPV6, "IPv6" },
{ 256*LMP_OBJ_DATA_LINK+LMP_CTYPE_UNMD, "Unnumbered" },
{ 256*LMP_OBJ_CHANNEL_STATUS+LMP_CTYPE_IPV4, "IPv4" },
{ 256*LMP_OBJ_CHANNEL_STATUS+LMP_CTYPE_IPV6, "IPv6" },
{ 256*LMP_OBJ_CHANNEL_STATUS+LMP_CTYPE_UNMD, "Unnumbered" },
{ 256*LMP_OBJ_CHANNEL_STATUS_REQ+LMP_CTYPE_IPV4, "IPv4" },
{ 256*LMP_OBJ_CHANNEL_STATUS_REQ+LMP_CTYPE_IPV6, "IPv6" },
{ 256*LMP_OBJ_CHANNEL_STATUS_REQ+LMP_CTYPE_UNMD, "Unnumbered" },
{ 256*LMP_OBJ_ERROR_CODE+LMP_CTYPE_1, "1" },
{ 256*LMP_OBJ_ERROR_CODE+LMP_CTYPE_2, "2" },
{ 256*LMP_OBJ_SERVICE_CONFIG+LMP_CTYPE_SERVICE_CONFIG_SP, "1" },
{ 256*LMP_OBJ_SERVICE_CONFIG+LMP_CTYPE_SERVICE_CONFIG_CPSA, "2" },
{ 256*LMP_OBJ_SERVICE_CONFIG+LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM, "3" },
{ 256*LMP_OBJ_SERVICE_CONFIG+LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY, "4" },
{ 0, NULL}
};
static int
lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr,
int total_subobj_len, int offset)
{
int hexdump = FALSE;
int subobj_type, subobj_len;
union { /* int to float conversion buffer */
float f;
uint32_t i;
} bw;
while (total_subobj_len > 0 && hexdump == FALSE ) {
subobj_type = EXTRACT_8BITS(obj_tptr + offset);
subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1);
ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u",
tok2str(lmp_data_link_subobj,
"Unknown",
subobj_type),
subobj_type,
subobj_len));
if (subobj_len < 4) {
ND_PRINT((ndo, " (too short)"));
break;
}
if ((subobj_len % 4) != 0) {
ND_PRINT((ndo, " (not a multiple of 4)"));
break;
}
if (total_subobj_len < subobj_len) {
ND_PRINT((ndo, " (goes past the end of the object)"));
break;
}
switch(subobj_type) {
case INT_SWITCHING_TYPE_SUBOBJ:
ND_PRINT((ndo, "\n\t Switching Type: %s (%u)",
tok2str(gmpls_switch_cap_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + offset + 2)),
EXTRACT_8BITS(obj_tptr + offset + 2)));
ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)",
tok2str(gmpls_encoding_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + offset + 3)),
EXTRACT_8BITS(obj_tptr + offset + 3)));
bw.i = EXTRACT_32BITS(obj_tptr+offset+4);
ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
bw.i = EXTRACT_32BITS(obj_tptr+offset+8);
ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case WAVELENGTH_SUBOBJ:
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+offset+4)));
break;
default:
/* Any Unknown Subobject ==> Exit loop */
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
offset+=subobj_len;
}
return (hexdump);
}
void
lmp_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
const struct lmp_common_header *lmp_com_header;
const struct lmp_object_header *lmp_obj_header;
const u_char *tptr,*obj_tptr;
u_int tlen,lmp_obj_len,lmp_obj_ctype,obj_tlen;
int hexdump;
u_int offset;
u_int link_type;
union { /* int to float conversion buffer */
float f;
uint32_t i;
} bw;
tptr=pptr;
lmp_com_header = (const struct lmp_common_header *)pptr;
ND_TCHECK(*lmp_com_header);
/*
* Sanity checking of the header.
*/
if (LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]) != LMP_VERSION) {
ND_PRINT((ndo, "LMP version %u packet not supported",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0])));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "LMPv%u %s Message, length: %u",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),
tok2str(lmp_msg_type_values, "unknown (%u)",lmp_com_header->msg_type),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
tlen=EXTRACT_16BITS(lmp_com_header->length);
ND_PRINT((ndo, "\n\tLMPv%u, msg-type: %s, Flags: [%s], length: %u",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),
tok2str(lmp_msg_type_values, "unknown, type: %u",lmp_com_header->msg_type),
bittok2str(lmp_header_flag_values,"none",lmp_com_header->flags),
tlen));
if (tlen < sizeof(const struct lmp_common_header)) {
ND_PRINT((ndo, " (too short)"));
return;
}
if (tlen > len) {
ND_PRINT((ndo, " (too long)"));
tlen = len;
}
tptr+=sizeof(const struct lmp_common_header);
tlen-=sizeof(const struct lmp_common_header);
while(tlen>0) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct lmp_object_header));
lmp_obj_header = (const struct lmp_object_header *)tptr;
lmp_obj_len=EXTRACT_16BITS(lmp_obj_header->length);
lmp_obj_ctype=(lmp_obj_header->ctype)&0x7f;
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %s (%u) Flags: [%snegotiable], length: %u",
tok2str(lmp_obj_values,
"Unknown",
lmp_obj_header->class_num),
lmp_obj_header->class_num,
tok2str(lmp_ctype_values,
"Unknown",
((lmp_obj_header->class_num)<<8)+lmp_obj_ctype),
lmp_obj_ctype,
(lmp_obj_header->ctype)&0x80 ? "" : "non-",
lmp_obj_len));
if (lmp_obj_len < 4) {
ND_PRINT((ndo, " (too short)"));
return;
}
if ((lmp_obj_len % 4) != 0) {
ND_PRINT((ndo, " (not a multiple of 4)"));
return;
}
obj_tptr=tptr+sizeof(struct lmp_object_header);
obj_tlen=lmp_obj_len-sizeof(struct lmp_object_header);
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, lmp_obj_len);
hexdump=FALSE;
switch(lmp_obj_header->class_num) {
case LMP_OBJ_CC_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_LOC:
case LMP_CTYPE_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Control Channel ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_LINK_ID:
case LMP_OBJ_INTERFACE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4_LOC:
case LMP_CTYPE_IPV4_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t IPv4 Link ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_IPV6_LOC:
case LMP_CTYPE_IPV6_RMT:
if (obj_tlen != 16) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t IPv6 Link ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_UNMD_LOC:
case LMP_CTYPE_UNMD_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Link ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_MESSAGE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Message ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_2:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Message ID Ack: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_NODE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_LOC:
case LMP_CTYPE_RMT:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Node ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CONFIG:
switch(lmp_obj_ctype) {
case LMP_CTYPE_HELLO_CONFIG:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Hello Interval: %u\n\t Hello Dead Interval: %u",
EXTRACT_16BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+2)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_HELLO:
switch(lmp_obj_ctype) {
case LMP_CTYPE_HELLO:
if (obj_tlen != 8) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Tx Seq: %u, Rx Seq: %u",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr+4)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_TE_LINK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
if (obj_tlen != 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)"
"\n\t Remote Link-ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
break;
case LMP_CTYPE_IPV6:
if (obj_tlen != 36) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)"
"\n\t Remote Link-ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_32BITS(obj_tptr+20)));
break;
case LMP_CTYPE_UNMD:
if (obj_tlen != 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Link-ID: %u (0x%08x)"
"\n\t Remote Link-ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_DATA_LINK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
if (obj_tlen < 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)"
"\n\t Remote Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
if (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12))
hexdump=TRUE;
break;
case LMP_CTYPE_IPV6:
if (obj_tlen < 36) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)"
"\n\t Remote Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_32BITS(obj_tptr+20)));
if (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 36, 36))
hexdump=TRUE;
break;
case LMP_CTYPE_UNMD:
if (obj_tlen < 12) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Local Interface ID: %u (0x%08x)"
"\n\t Remote Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
if (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12))
hexdump=TRUE;
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_BEGIN:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 20) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: %s",
bittok2str(lmp_obj_begin_verify_flag_values,
"none",
EXTRACT_16BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Verify Interval: %u",
EXTRACT_16BITS(obj_tptr+2)));
ND_PRINT((ndo, "\n\t Data links: %u",
EXTRACT_32BITS(obj_tptr+4)));
ND_PRINT((ndo, "\n\t Encoding type: %s",
tok2str(gmpls_encoding_values, "Unknown", *(obj_tptr+8))));
ND_PRINT((ndo, "\n\t Verify Transport Mechanism: %u (0x%x)%s",
EXTRACT_16BITS(obj_tptr+10),
EXTRACT_16BITS(obj_tptr+10),
EXTRACT_16BITS(obj_tptr+10)&8000 ? " (Payload test messages capable)" : ""));
bw.i = EXTRACT_32BITS(obj_tptr+12);
ND_PRINT((ndo, "\n\t Transmission Rate: %.3f Mbps",bw.f*8/1000000));
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+16)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_BEGIN_ACK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Verify Dead Interval: %u"
"\n\t Verify Transport Response: %u",
EXTRACT_16BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+2)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Verify ID: %u",
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CHANNEL_STATUS:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
offset = 0;
/* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */
while (offset+8 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF));
offset+=8;
}
break;
case LMP_CTYPE_IPV6:
offset = 0;
/* Decode pairs: <Interface_ID (16 bytes), Channel_status (4 bytes)> */
while (offset+20 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+16)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+16)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF));
offset+=20;
}
break;
case LMP_CTYPE_UNMD:
offset = 0;
/* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */
while (offset+8 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF));
offset+=8;
}
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CHANNEL_STATUS_REQ:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
offset = 0;
while (offset+4 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=4;
}
break;
case LMP_CTYPE_IPV6:
offset = 0;
while (offset+16 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=16;
}
break;
case LMP_CTYPE_UNMD:
offset = 0;
while (offset+4 <= obj_tlen) {
ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=4;
}
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_ERROR_CODE:
switch(lmp_obj_ctype) {
case LMP_CTYPE_BEGIN_VERIFY_ERROR:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Error Code: %s",
bittok2str(lmp_obj_begin_verify_error_values,
"none",
EXTRACT_32BITS(obj_tptr))));
break;
case LMP_CTYPE_LINK_SUMMARY_ERROR:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Error Code: %s",
bittok2str(lmp_obj_link_summary_error_values,
"none",
EXTRACT_32BITS(obj_tptr))));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_SERVICE_CONFIG:
switch (lmp_obj_ctype) {
case LMP_CTYPE_SERVICE_CONFIG_SP:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Flags: %s",
bittok2str(lmp_obj_service_config_sp_flag_values,
"none",
EXTRACT_8BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t UNI Version: %u",
EXTRACT_8BITS(obj_tptr + 1)));
break;
case LMP_CTYPE_SERVICE_CONFIG_CPSA:
if (obj_tlen != 16) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
link_type = EXTRACT_8BITS(obj_tptr);
ND_PRINT((ndo, "\n\t Link Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_link_type_values,
"Unknown", link_type),
link_type));
switch (link_type) {
case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SDH:
ND_PRINT((ndo, "\n\t Signal Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_signal_type_sdh_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + 1)),
EXTRACT_8BITS(obj_tptr + 1)));
break;
case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SONET:
ND_PRINT((ndo, "\n\t Signal Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_signal_type_sonet_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + 1)),
EXTRACT_8BITS(obj_tptr + 1)));
break;
}
ND_PRINT((ndo, "\n\t Transparency: %s",
bittok2str(lmp_obj_service_config_cpsa_tp_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 2))));
ND_PRINT((ndo, "\n\t Contiguous Concatenation Types: %s",
bittok2str(lmp_obj_service_config_cpsa_cct_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 3))));
ND_PRINT((ndo, "\n\t Minimum NCC: %u",
EXTRACT_16BITS(obj_tptr+4)));
ND_PRINT((ndo, "\n\t Maximum NCC: %u",
EXTRACT_16BITS(obj_tptr+6)));
ND_PRINT((ndo, "\n\t Minimum NVC:%u",
EXTRACT_16BITS(obj_tptr+8)));
ND_PRINT((ndo, "\n\t Maximum NVC:%u",
EXTRACT_16BITS(obj_tptr+10)));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+12),
EXTRACT_32BITS(obj_tptr+12)));
break;
case LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM:
if (obj_tlen != 8) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Transparency Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_transparency_flag_values,
"none",
EXTRACT_32BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t TCM Monitoring Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_tcm_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 7))));
break;
case LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY:
if (obj_tlen != 4) {
ND_PRINT((ndo, " (not correct for object)"));
break;
}
ND_PRINT((ndo, "\n\t Diversity: Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_network_diversity_flag_values,
"none",
EXTRACT_8BITS(obj_tptr + 3))));
break;
default:
hexdump = TRUE;
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,obj_tptr,"\n\t ",obj_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1 || hexdump==TRUE)
print_unknown_data(ndo,tptr+sizeof(struct lmp_object_header),"\n\t ",
lmp_obj_len-sizeof(struct lmp_object_header));
tptr+=lmp_obj_len;
tlen-=lmp_obj_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_262_0 |
crossvul-cpp_data_bad_1984_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__
*/
/*
* JP2 Library
*
* $Id$
*/
/******************************************************************************\
* Includes.
\******************************************************************************/
#include "jp2_dec.h"
#include "jp2_cod.h"
#include "jasper/jas_image.h"
#include "jasper/jas_stream.h"
#include "jasper/jas_math.h"
#include "jasper/jas_debug.h"
#include "jasper/jas_malloc.h"
#include "jasper/jas_types.h"
#include <assert.h>
#include <stdio.h>
#define JP2_VALIDATELEN (JAS_MIN(JP2_JP_LEN + 16, JAS_STREAM_MAXPUTBACK))
static jp2_dec_t *jp2_dec_create(void);
static void jp2_dec_destroy(jp2_dec_t *dec);
static int jp2_getcs(jp2_colr_t *colr);
static int fromiccpcs(int cs);
static int jp2_getct(int colorspace, int type, int assoc);
/******************************************************************************\
* Functions.
\******************************************************************************/
jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr)
{
jp2_box_t *box;
int found;
jas_image_t *image;
jp2_dec_t *dec;
bool samedtype;
int dtype;
unsigned int i;
jp2_cmap_t *cmapd;
jp2_pclr_t *pclrd;
jp2_cdef_t *cdefd;
unsigned int channo;
int newcmptno;
int_fast32_t *lutents;
#if 0
jp2_cdefchan_t *cdefent;
int cmptno;
#endif
jp2_cmapent_t *cmapent;
jas_icchdr_t icchdr;
jas_iccprof_t *iccprof;
dec = 0;
box = 0;
image = 0;
JAS_DBGLOG(100, ("jp2_decode(%p, \"%s\")\n", in, optstr));
if (!(dec = jp2_dec_create())) {
goto error;
}
/* Get the first box. This should be a JP box. */
if (!(box = jp2_box_get(in))) {
jas_eprintf("error: cannot get box\n");
goto error;
}
if (box->type != JP2_BOX_JP) {
jas_eprintf("error: expecting signature box\n");
goto error;
}
if (box->data.jp.magic != JP2_JP_MAGIC) {
jas_eprintf("incorrect magic number\n");
goto error;
}
jp2_box_destroy(box);
box = 0;
/* Get the second box. This should be a FTYP box. */
if (!(box = jp2_box_get(in))) {
goto error;
}
if (box->type != JP2_BOX_FTYP) {
jas_eprintf("expecting file type box\n");
goto error;
}
jp2_box_destroy(box);
box = 0;
/* Get more boxes... */
found = 0;
while ((box = jp2_box_get(in))) {
if (jas_getdbglevel() >= 1) {
jas_eprintf("got box type %s\n", box->info->name);
}
switch (box->type) {
case JP2_BOX_JP2C:
found = 1;
break;
case JP2_BOX_IHDR:
if (!dec->ihdr) {
dec->ihdr = box;
box = 0;
}
break;
case JP2_BOX_BPCC:
if (!dec->bpcc) {
dec->bpcc = box;
box = 0;
}
break;
case JP2_BOX_CDEF:
if (!dec->cdef) {
dec->cdef = box;
box = 0;
}
break;
case JP2_BOX_PCLR:
if (!dec->pclr) {
dec->pclr = box;
box = 0;
}
break;
case JP2_BOX_CMAP:
if (!dec->cmap) {
dec->cmap = box;
box = 0;
}
break;
case JP2_BOX_COLR:
if (!dec->colr) {
dec->colr = box;
box = 0;
}
break;
}
if (box) {
jp2_box_destroy(box);
box = 0;
}
if (found) {
break;
}
}
if (!found) {
jas_eprintf("error: no code stream found\n");
goto error;
}
if (!(dec->image = jpc_decode(in, optstr))) {
jas_eprintf("error: cannot decode code stream\n");
goto error;
}
/* An IHDR box must be present. */
if (!dec->ihdr) {
jas_eprintf("error: missing IHDR box\n");
goto error;
}
/* Does the number of components indicated in the IHDR box match
the value specified in the code stream? */
if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(jas_uint,
jas_image_numcmpts(dec->image))) {
jas_eprintf("warning: number of components mismatch\n");
}
/* At least one component must be present. */
if (!jas_image_numcmpts(dec->image)) {
jas_eprintf("error: no components\n");
goto error;
}
/* Determine if all components have the same data type. */
samedtype = true;
dtype = jas_image_cmptdtype(dec->image, 0);
for (i = 1; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {
if (jas_image_cmptdtype(dec->image, i) != dtype) {
samedtype = false;
break;
}
}
/* Is the component data type indicated in the IHDR box consistent
with the data in the code stream? */
if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) ||
(!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) {
jas_eprintf("warning: component data type mismatch (IHDR)\n");
}
/* Is the compression type supported? */
if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {
jas_eprintf("error: unsupported compression type\n");
goto error;
}
if (dec->bpcc) {
/* Is the number of components indicated in the BPCC box
consistent with the code stream data? */
if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts(
dec->image))) {
jas_eprintf("warning: number of components mismatch\n");
}
/* Is the component data type information indicated in the BPCC
box consistent with the code stream data? */
if (!samedtype) {
for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image));
++i) {
if (jas_image_cmptdtype(dec->image, i) !=
JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) {
jas_eprintf("warning: component data type mismatch (BPCC)\n");
}
}
} else {
jas_eprintf("warning: superfluous BPCC box\n");
}
}
/* A COLR box must be present. */
if (!dec->colr) {
jas_eprintf("error: no COLR box\n");
goto error;
}
switch (dec->colr->data.colr.method) {
case JP2_COLR_ENUM:
jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr));
break;
case JP2_COLR_ICC:
iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp,
dec->colr->data.colr.iccplen);
if (!iccprof) {
jas_eprintf("error: failed to parse ICC profile\n");
goto error;
}
jas_iccprof_gethdr(iccprof, &icchdr);
jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc);
jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc));
dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof);
if (!dec->image->cmprof_) {
jas_iccprof_destroy(iccprof);
goto error;
}
jas_iccprof_destroy(iccprof);
break;
}
/* If a CMAP box is present, a PCLR box must also be present. */
if (dec->cmap && !dec->pclr) {
jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n");
jp2_box_destroy(dec->cmap);
dec->cmap = 0;
}
/* If a CMAP box is not present, a PCLR box must not be present. */
if (!dec->cmap && dec->pclr) {
jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n");
jp2_box_destroy(dec->pclr);
dec->pclr = 0;
}
/* Determine the number of channels (which is essentially the number
of components after any palette mappings have been applied). */
dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans :
JAS_CAST(jas_uint, jas_image_numcmpts(dec->image));
/* Perform a basic sanity check on the CMAP box if present. */
if (dec->cmap) {
for (i = 0; i < dec->numchans; ++i) {
/* Is the component number reasonable? */
if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(jas_uint,
jas_image_numcmpts(dec->image))) {
jas_eprintf("error: invalid component number in CMAP box\n");
goto error;
}
/* Is the LUT index reasonable? */
if (dec->cmap->data.cmap.ents[i].pcol >=
dec->pclr->data.pclr.numchans) {
jas_eprintf("error: invalid CMAP LUT index\n");
goto error;
}
}
}
/* Allocate space for the channel-number to component-number LUT. */
if (!(dec->chantocmptlut = jas_alloc2(dec->numchans,
sizeof(uint_fast16_t)))) {
jas_eprintf("error: no memory\n");
goto error;
}
if (!dec->cmap) {
for (i = 0; i < dec->numchans; ++i) {
dec->chantocmptlut[i] = i;
}
} else {
cmapd = &dec->cmap->data.cmap;
pclrd = &dec->pclr->data.pclr;
cdefd = &dec->cdef->data.cdef;
for (channo = 0; channo < cmapd->numchans; ++channo) {
cmapent = &cmapd->ents[channo];
if (cmapent->map == JP2_CMAP_DIRECT) {
dec->chantocmptlut[channo] = channo;
} else if (cmapent->map == JP2_CMAP_PALETTE) {
if (!pclrd->numlutents) {
goto error;
}
lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t));
if (!lutents) {
goto error;
}
for (i = 0; i < pclrd->numlutents; ++i) {
lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans];
}
newcmptno = jas_image_numcmpts(dec->image);
jas_image_depalettize(dec->image, cmapent->cmptno,
pclrd->numlutents, lutents,
JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno);
dec->chantocmptlut[channo] = newcmptno;
jas_free(lutents);
#if 0
if (dec->cdef) {
cdefent = jp2_cdef_lookup(cdefd, channo);
if (!cdefent) {
abort();
}
jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc));
} else {
jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1));
}
#else
/* suppress -Wunused-but-set-variable */
(void)cdefd;
#endif
} else {
jas_eprintf("error: invalid MTYP in CMAP box\n");
goto error;
}
}
}
/* Ensure that the number of channels being used by the decoder
matches the number of image components. */
if (dec->numchans != jas_image_numcmpts(dec->image)) {
jas_eprintf("error: mismatch in number of components (%d != %d)\n",
dec->numchans, jas_image_numcmpts(dec->image));
goto error;
}
/* Mark all components as being of unknown type. */
for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {
jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN);
}
/* Determine the type of each component. */
if (dec->cdef) {
for (i = 0; i < dec->cdef->data.cdef.numchans; ++i) {
/* Is the channel number reasonable? */
if (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) {
jas_eprintf("error: invalid channel number in CDEF box\n");
goto error;
}
jas_image_setcmpttype(dec->image,
dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo],
jp2_getct(jas_image_clrspc(dec->image),
dec->cdef->data.cdef.ents[i].type,
dec->cdef->data.cdef.ents[i].assoc));
}
} else {
for (i = 0; i < dec->numchans; ++i) {
jas_image_setcmpttype(dec->image, dec->chantocmptlut[i],
jp2_getct(jas_image_clrspc(dec->image), 0, i + 1));
}
}
/* Delete any components that are not of interest. */
for (i = jas_image_numcmpts(dec->image); i > 0; --i) {
if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) {
jas_image_delcmpt(dec->image, i - 1);
}
}
/* Ensure that some components survived. */
if (!jas_image_numcmpts(dec->image)) {
jas_eprintf("error: no components\n");
goto error;
}
#if 0
jas_eprintf("no of components is %d\n", jas_image_numcmpts(dec->image));
#endif
/* Prevent the image from being destroyed later. */
image = dec->image;
dec->image = 0;
jp2_dec_destroy(dec);
return image;
error:
if (box) {
jp2_box_destroy(box);
}
if (dec) {
jp2_dec_destroy(dec);
}
return 0;
}
int jp2_validate(jas_stream_t *in)
{
unsigned char buf[JP2_VALIDATELEN];
#if 0
jas_stream_t *tmpstream;
jp2_box_t *box;
#endif
assert(JAS_STREAM_MAXPUTBACK >= JP2_VALIDATELEN);
/* Read the validation data (i.e., the data used for detecting
the format). */
if (jas_stream_peek(in, buf, sizeof(buf)) != sizeof(buf))
return -1;
/* Is the box type correct? */
if ((((uint_least32_t)buf[4] << 24) | ((uint_least32_t)buf[5] << 16) | ((uint_least32_t)buf[6] << 8) | (uint_least32_t)buf[7]) !=
JP2_BOX_JP)
{
return -1;
}
return 0;
}
static jp2_dec_t *jp2_dec_create(void)
{
jp2_dec_t *dec;
if (!(dec = jas_malloc(sizeof(jp2_dec_t)))) {
return 0;
}
dec->ihdr = 0;
dec->bpcc = 0;
dec->cdef = 0;
dec->pclr = 0;
dec->image = 0;
dec->chantocmptlut = 0;
dec->cmap = 0;
dec->colr = 0;
return dec;
}
static void jp2_dec_destroy(jp2_dec_t *dec)
{
if (dec->ihdr) {
jp2_box_destroy(dec->ihdr);
}
if (dec->bpcc) {
jp2_box_destroy(dec->bpcc);
}
if (dec->cdef) {
jp2_box_destroy(dec->cdef);
}
if (dec->pclr) {
jp2_box_destroy(dec->pclr);
}
if (dec->image) {
jas_image_destroy(dec->image);
}
if (dec->cmap) {
jp2_box_destroy(dec->cmap);
}
if (dec->colr) {
jp2_box_destroy(dec->colr);
}
if (dec->chantocmptlut) {
jas_free(dec->chantocmptlut);
}
jas_free(dec);
}
static int jp2_getct(int colorspace, int type, int assoc)
{
if (type == 1 && assoc == 0) {
return JAS_IMAGE_CT_OPACITY;
}
if (type == 0 && assoc >= 1 && assoc <= 65534) {
switch (colorspace) {
case JAS_CLRSPC_FAM_RGB:
switch (assoc) {
case JP2_CDEF_RGB_R:
return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R);
case JP2_CDEF_RGB_G:
return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G);
case JP2_CDEF_RGB_B:
return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B);
}
break;
case JAS_CLRSPC_FAM_YCBCR:
switch (assoc) {
case JP2_CDEF_YCBCR_Y:
return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y);
case JP2_CDEF_YCBCR_CB:
return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB);
case JP2_CDEF_YCBCR_CR:
return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR);
}
break;
case JAS_CLRSPC_FAM_GRAY:
switch (assoc) {
case JP2_CDEF_GRAY_Y:
return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y);
}
break;
default:
return JAS_IMAGE_CT_COLOR(assoc - 1);
}
}
return JAS_IMAGE_CT_UNKNOWN;
}
static int jp2_getcs(jp2_colr_t *colr)
{
if (colr->method == JP2_COLR_ENUM) {
switch (colr->csid) {
case JP2_COLR_SRGB:
return JAS_CLRSPC_SRGB;
case JP2_COLR_SYCC:
return JAS_CLRSPC_SYCBCR;
case JP2_COLR_SGRAY:
return JAS_CLRSPC_SGRAY;
}
}
return JAS_CLRSPC_UNKNOWN;
}
static int fromiccpcs(int cs)
{
switch (cs) {
case ICC_CS_RGB:
return JAS_CLRSPC_GENRGB;
case ICC_CS_YCBCR:
return JAS_CLRSPC_GENYCBCR;
case ICC_CS_GRAY:
return JAS_CLRSPC_GENGRAY;
}
return JAS_CLRSPC_UNKNOWN;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1984_1 |
crossvul-cpp_data_good_4687_0 |
#include <config.h>
#include "ftpd.h"
#include "utils.h"
#ifdef WITH_DMALLOC
# include <dmalloc.h>
#endif
#ifdef HAVE_LIBSODIUM
# if !defined(pure_memzero) || !defined(pure_memcmp)
# error pure_memzero/pure_memcmp not defined
# endif
#else
void pure_memzero(void * const pnt, const size_t len)
{
# ifdef HAVE_EXPLICIT_BZERO
explicit_bzero(pnt, len);
# else
volatile unsigned char *pnt_ = (volatile unsigned char *) pnt;
size_t i = (size_t) 0U;
while (i < len) {
pnt_[i++] = 0U;
}
# endif
}
int pure_memcmp(const void * const b1_, const void * const b2_, size_t len)
{
const unsigned char *b1 = (const unsigned char *) b1_;
const unsigned char *b2 = (const unsigned char *) b2_;
size_t i;
unsigned char d = (unsigned char) 0U;
for (i = 0U; i < len; i++) {
d |= b1[i] ^ b2[i];
}
return (int) ((1 & ((d - 1) >> 8)) - 1);
}
#endif
int pure_strcmp(const char * const s1, const char * const s2)
{
const size_t s1_len = strlen(s1);
const size_t s2_len = strlen(s2);
const size_t len = (s1_len < s2_len) ? s1_len : s2_len;
return pure_memcmp(s1, s2, len + 1);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4687_0 |
crossvul-cpp_data_bad_2687_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994, 1995, 1996
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: Internet Control Message Protocol (ICMP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip.h"
#include "udp.h"
#include "ipproto.h"
#include "mpls.h"
/*
* Interface Control Message Protocol Definitions.
* Per RFC 792, September 1981.
*/
/*
* Structure of an icmp header.
*/
struct icmp {
uint8_t icmp_type; /* type of message, see below */
uint8_t icmp_code; /* type sub code */
uint16_t icmp_cksum; /* ones complement cksum of struct */
union {
uint8_t ih_pptr; /* ICMP_PARAMPROB */
struct in_addr ih_gwaddr; /* ICMP_REDIRECT */
struct ih_idseq {
uint16_t icd_id;
uint16_t icd_seq;
} ih_idseq;
uint32_t ih_void;
} icmp_hun;
#define icmp_pptr icmp_hun.ih_pptr
#define icmp_gwaddr icmp_hun.ih_gwaddr
#define icmp_id icmp_hun.ih_idseq.icd_id
#define icmp_seq icmp_hun.ih_idseq.icd_seq
#define icmp_void icmp_hun.ih_void
union {
struct id_ts {
uint32_t its_otime;
uint32_t its_rtime;
uint32_t its_ttime;
} id_ts;
struct id_ip {
struct ip idi_ip;
/* options and then 64 bits of data */
} id_ip;
uint32_t id_mask;
uint8_t id_data[1];
} icmp_dun;
#define icmp_otime icmp_dun.id_ts.its_otime
#define icmp_rtime icmp_dun.id_ts.its_rtime
#define icmp_ttime icmp_dun.id_ts.its_ttime
#define icmp_ip icmp_dun.id_ip.idi_ip
#define icmp_mask icmp_dun.id_mask
#define icmp_data icmp_dun.id_data
};
#define ICMP_MPLS_EXT_EXTRACT_VERSION(x) (((x)&0xf0)>>4)
#define ICMP_MPLS_EXT_VERSION 2
/*
* Lower bounds on packet lengths for various types.
* For the error advice packets must first insure that the
* packet is large enought to contain the returned ip header.
* Only then can we do the check to see if 64 bits of packet
* data have been returned, since we need to check the returned
* ip header length.
*/
#define ICMP_MINLEN 8 /* abs minimum */
#define ICMP_EXTD_MINLEN (156 - sizeof (struct ip)) /* draft-bonica-internet-icmp-08 */
#define ICMP_TSLEN (8 + 3 * sizeof (uint32_t)) /* timestamp */
#define ICMP_MASKLEN 12 /* address mask */
#define ICMP_ADVLENMIN (8 + sizeof (struct ip) + 8) /* min */
#define ICMP_ADVLEN(p) (8 + (IP_HL(&(p)->icmp_ip) << 2) + 8)
/* N.B.: must separately check that ip_hl >= 5 */
/*
* Definition of type and code field values.
*/
#define ICMP_ECHOREPLY 0 /* echo reply */
#define ICMP_UNREACH 3 /* dest unreachable, codes: */
#define ICMP_UNREACH_NET 0 /* bad net */
#define ICMP_UNREACH_HOST 1 /* bad host */
#define ICMP_UNREACH_PROTOCOL 2 /* bad protocol */
#define ICMP_UNREACH_PORT 3 /* bad port */
#define ICMP_UNREACH_NEEDFRAG 4 /* IP_DF caused drop */
#define ICMP_UNREACH_SRCFAIL 5 /* src route failed */
#define ICMP_UNREACH_NET_UNKNOWN 6 /* unknown net */
#define ICMP_UNREACH_HOST_UNKNOWN 7 /* unknown host */
#define ICMP_UNREACH_ISOLATED 8 /* src host isolated */
#define ICMP_UNREACH_NET_PROHIB 9 /* prohibited access */
#define ICMP_UNREACH_HOST_PROHIB 10 /* ditto */
#define ICMP_UNREACH_TOSNET 11 /* bad tos for net */
#define ICMP_UNREACH_TOSHOST 12 /* bad tos for host */
#define ICMP_SOURCEQUENCH 4 /* packet lost, slow down */
#define ICMP_REDIRECT 5 /* shorter route, codes: */
#define ICMP_REDIRECT_NET 0 /* for network */
#define ICMP_REDIRECT_HOST 1 /* for host */
#define ICMP_REDIRECT_TOSNET 2 /* for tos and net */
#define ICMP_REDIRECT_TOSHOST 3 /* for tos and host */
#define ICMP_ECHO 8 /* echo service */
#define ICMP_ROUTERADVERT 9 /* router advertisement */
#define ICMP_ROUTERSOLICIT 10 /* router solicitation */
#define ICMP_TIMXCEED 11 /* time exceeded, code: */
#define ICMP_TIMXCEED_INTRANS 0 /* ttl==0 in transit */
#define ICMP_TIMXCEED_REASS 1 /* ttl==0 in reass */
#define ICMP_PARAMPROB 12 /* ip header bad */
#define ICMP_PARAMPROB_OPTABSENT 1 /* req. opt. absent */
#define ICMP_TSTAMP 13 /* timestamp request */
#define ICMP_TSTAMPREPLY 14 /* timestamp reply */
#define ICMP_IREQ 15 /* information request */
#define ICMP_IREQREPLY 16 /* information reply */
#define ICMP_MASKREQ 17 /* address mask request */
#define ICMP_MASKREPLY 18 /* address mask reply */
#define ICMP_MAXTYPE 18
#define ICMP_ERRTYPE(type) \
((type) == ICMP_UNREACH || (type) == ICMP_SOURCEQUENCH || \
(type) == ICMP_REDIRECT || (type) == ICMP_TIMXCEED || \
(type) == ICMP_PARAMPROB)
#define ICMP_MPLS_EXT_TYPE(type) \
((type) == ICMP_UNREACH || \
(type) == ICMP_TIMXCEED || \
(type) == ICMP_PARAMPROB)
/* rfc1700 */
#ifndef ICMP_UNREACH_NET_UNKNOWN
#define ICMP_UNREACH_NET_UNKNOWN 6 /* destination net unknown */
#endif
#ifndef ICMP_UNREACH_HOST_UNKNOWN
#define ICMP_UNREACH_HOST_UNKNOWN 7 /* destination host unknown */
#endif
#ifndef ICMP_UNREACH_ISOLATED
#define ICMP_UNREACH_ISOLATED 8 /* source host isolated */
#endif
#ifndef ICMP_UNREACH_NET_PROHIB
#define ICMP_UNREACH_NET_PROHIB 9 /* admin prohibited net */
#endif
#ifndef ICMP_UNREACH_HOST_PROHIB
#define ICMP_UNREACH_HOST_PROHIB 10 /* admin prohibited host */
#endif
#ifndef ICMP_UNREACH_TOSNET
#define ICMP_UNREACH_TOSNET 11 /* tos prohibited net */
#endif
#ifndef ICMP_UNREACH_TOSHOST
#define ICMP_UNREACH_TOSHOST 12 /* tos prohibited host */
#endif
/* rfc1716 */
#ifndef ICMP_UNREACH_FILTER_PROHIB
#define ICMP_UNREACH_FILTER_PROHIB 13 /* admin prohibited filter */
#endif
#ifndef ICMP_UNREACH_HOST_PRECEDENCE
#define ICMP_UNREACH_HOST_PRECEDENCE 14 /* host precedence violation */
#endif
#ifndef ICMP_UNREACH_PRECEDENCE_CUTOFF
#define ICMP_UNREACH_PRECEDENCE_CUTOFF 15 /* precedence cutoff */
#endif
/* Most of the icmp types */
static const struct tok icmp2str[] = {
{ ICMP_ECHOREPLY, "echo reply" },
{ ICMP_SOURCEQUENCH, "source quench" },
{ ICMP_ECHO, "echo request" },
{ ICMP_ROUTERSOLICIT, "router solicitation" },
{ ICMP_TSTAMP, "time stamp request" },
{ ICMP_TSTAMPREPLY, "time stamp reply" },
{ ICMP_IREQ, "information request" },
{ ICMP_IREQREPLY, "information reply" },
{ ICMP_MASKREQ, "address mask request" },
{ 0, NULL }
};
/* Formats for most of the ICMP_UNREACH codes */
static const struct tok unreach2str[] = {
{ ICMP_UNREACH_NET, "net %s unreachable" },
{ ICMP_UNREACH_HOST, "host %s unreachable" },
{ ICMP_UNREACH_SRCFAIL,
"%s unreachable - source route failed" },
{ ICMP_UNREACH_NET_UNKNOWN, "net %s unreachable - unknown" },
{ ICMP_UNREACH_HOST_UNKNOWN, "host %s unreachable - unknown" },
{ ICMP_UNREACH_ISOLATED,
"%s unreachable - source host isolated" },
{ ICMP_UNREACH_NET_PROHIB,
"net %s unreachable - admin prohibited" },
{ ICMP_UNREACH_HOST_PROHIB,
"host %s unreachable - admin prohibited" },
{ ICMP_UNREACH_TOSNET,
"net %s unreachable - tos prohibited" },
{ ICMP_UNREACH_TOSHOST,
"host %s unreachable - tos prohibited" },
{ ICMP_UNREACH_FILTER_PROHIB,
"host %s unreachable - admin prohibited filter" },
{ ICMP_UNREACH_HOST_PRECEDENCE,
"host %s unreachable - host precedence violation" },
{ ICMP_UNREACH_PRECEDENCE_CUTOFF,
"host %s unreachable - precedence cutoff" },
{ 0, NULL }
};
/* Formats for the ICMP_REDIRECT codes */
static const struct tok type2str[] = {
{ ICMP_REDIRECT_NET, "redirect %s to net %s" },
{ ICMP_REDIRECT_HOST, "redirect %s to host %s" },
{ ICMP_REDIRECT_TOSNET, "redirect-tos %s to net %s" },
{ ICMP_REDIRECT_TOSHOST, "redirect-tos %s to host %s" },
{ 0, NULL }
};
/* rfc1191 */
struct mtu_discovery {
uint16_t unused;
uint16_t nexthopmtu;
};
/* rfc1256 */
struct ih_rdiscovery {
uint8_t ird_addrnum;
uint8_t ird_addrsiz;
uint16_t ird_lifetime;
};
struct id_rdiscovery {
uint32_t ird_addr;
uint32_t ird_pref;
};
/*
* draft-bonica-internet-icmp-08
*
* The Destination Unreachable, Time Exceeded
* and Parameter Problem messages are slighly changed as per
* the above draft. A new Length field gets added to give
* the caller an idea about the length of the piggypacked
* IP packet before the MPLS extension header starts.
*
* The Length field represents length of the padded "original datagram"
* field measured in 32-bit words.
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type | Code | Checksum |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | unused | Length | unused |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Internet Header + leading octets of original datagram |
* | |
* | // |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct icmp_ext_t {
uint8_t icmp_type;
uint8_t icmp_code;
uint8_t icmp_checksum[2];
uint8_t icmp_reserved;
uint8_t icmp_length;
uint8_t icmp_reserved2[2];
uint8_t icmp_ext_legacy_header[128]; /* extension header starts 128 bytes after ICMP header */
uint8_t icmp_ext_version_res[2];
uint8_t icmp_ext_checksum[2];
uint8_t icmp_ext_data[1];
};
struct icmp_mpls_ext_object_header_t {
uint8_t length[2];
uint8_t class_num;
uint8_t ctype;
};
static const struct tok icmp_mpls_ext_obj_values[] = {
{ 1, "MPLS Stack Entry" },
{ 2, "Extended Payload" },
{ 0, NULL}
};
/* prototypes */
const char *icmp_tstamp_print(u_int);
/* print the milliseconds since midnight UTC */
const char *
icmp_tstamp_print(u_int tstamp)
{
u_int msec,sec,min,hrs;
static char buf[64];
msec = tstamp % 1000;
sec = tstamp / 1000;
min = sec / 60; sec -= min * 60;
hrs = min / 60; min -= hrs * 60;
snprintf(buf, sizeof(buf), "%02u:%02u:%02u.%03u",hrs,min,sec,msec);
return buf;
}
void
icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2,
int fragmented)
{
char *cp;
const struct icmp *dp;
const struct icmp_ext_t *ext_dp;
const struct ip *ip;
const char *str, *fmt;
const struct ip *oip;
const struct udphdr *ouh;
const uint8_t *obj_tptr;
uint32_t raw_label;
const u_char *snapend_save;
const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header;
u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype;
char buf[MAXHOSTNAMELEN + 100];
struct cksum_vec vec[1];
dp = (const struct icmp *)bp;
ext_dp = (const struct icmp_ext_t *)bp;
ip = (const struct ip *)bp2;
str = buf;
ND_TCHECK(dp->icmp_code);
switch (dp->icmp_type) {
case ICMP_ECHO:
case ICMP_ECHOREPLY:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf), "echo %s, id %u, seq %u",
dp->icmp_type == ICMP_ECHO ?
"request" : "reply",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_UNREACH:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_UNREACH_PROTOCOL:
ND_TCHECK(dp->icmp_ip.ip_p);
(void)snprintf(buf, sizeof(buf),
"%s protocol %d unreachable",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
dp->icmp_ip.ip_p);
break;
case ICMP_UNREACH_PORT:
ND_TCHECK(dp->icmp_ip.ip_p);
oip = &dp->icmp_ip;
hlen = IP_HL(oip) * 4;
ouh = (const struct udphdr *)(((const u_char *)oip) + hlen);
ND_TCHECK(ouh->uh_dport);
dport = EXTRACT_16BITS(&ouh->uh_dport);
switch (oip->ip_p) {
case IPPROTO_TCP:
(void)snprintf(buf, sizeof(buf),
"%s tcp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
tcpport_string(ndo, dport));
break;
case IPPROTO_UDP:
(void)snprintf(buf, sizeof(buf),
"%s udp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
udpport_string(ndo, dport));
break;
default:
(void)snprintf(buf, sizeof(buf),
"%s protocol %d port %d unreachable",
ipaddr_string(ndo, &oip->ip_dst),
oip->ip_p, dport);
break;
}
break;
case ICMP_UNREACH_NEEDFRAG:
{
register const struct mtu_discovery *mp;
mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void;
mtu = EXTRACT_16BITS(&mp->nexthopmtu);
if (mtu) {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag (mtu %d)",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu);
} else {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
}
}
break;
default:
fmt = tok2str(unreach2str, "#%d %%s unreachable",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
break;
}
break;
case ICMP_REDIRECT:
ND_TCHECK(dp->icmp_ip.ip_dst);
fmt = tok2str(type2str, "redirect-#%d %%s to net %%s",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
ipaddr_string(ndo, &dp->icmp_gwaddr));
break;
case ICMP_ROUTERADVERT:
{
register const struct ih_rdiscovery *ihp;
register const struct id_rdiscovery *idp;
u_int lifetime, num, size;
(void)snprintf(buf, sizeof(buf), "router advertisement");
cp = buf + strlen(buf);
ihp = (const struct ih_rdiscovery *)&dp->icmp_void;
ND_TCHECK(*ihp);
(void)strncpy(cp, " lifetime ", sizeof(buf) - (cp - buf));
cp = buf + strlen(buf);
lifetime = EXTRACT_16BITS(&ihp->ird_lifetime);
if (lifetime < 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u",
lifetime);
} else if (lifetime < 60 * 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u",
lifetime / 60, lifetime % 60);
} else {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
"%u:%02u:%02u",
lifetime / 3600,
(lifetime % 3600) / 60,
lifetime % 60);
}
cp = buf + strlen(buf);
num = ihp->ird_addrnum;
(void)snprintf(cp, sizeof(buf) - (cp - buf), " %d:", num);
cp = buf + strlen(buf);
size = ihp->ird_addrsiz;
if (size != 2) {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
" [size %d]", size);
break;
}
idp = (const struct id_rdiscovery *)&dp->icmp_data;
while (num-- > 0) {
ND_TCHECK(*idp);
(void)snprintf(cp, sizeof(buf) - (cp - buf), " {%s %u}",
ipaddr_string(ndo, &idp->ird_addr),
EXTRACT_32BITS(&idp->ird_pref));
cp = buf + strlen(buf);
++idp;
}
}
break;
case ICMP_TIMXCEED:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_TIMXCEED_INTRANS:
str = "time exceeded in-transit";
break;
case ICMP_TIMXCEED_REASS:
str = "ip reassembly time exceeded";
break;
default:
(void)snprintf(buf, sizeof(buf), "time exceeded-#%d",
dp->icmp_code);
break;
}
break;
case ICMP_PARAMPROB:
if (dp->icmp_code)
(void)snprintf(buf, sizeof(buf),
"parameter problem - code %d", dp->icmp_code);
else {
ND_TCHECK(dp->icmp_pptr);
(void)snprintf(buf, sizeof(buf),
"parameter problem - octet %d", dp->icmp_pptr);
}
break;
case ICMP_MASKREPLY:
ND_TCHECK(dp->icmp_mask);
(void)snprintf(buf, sizeof(buf), "address mask is 0x%08x",
EXTRACT_32BITS(&dp->icmp_mask));
break;
case ICMP_TSTAMP:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf),
"time stamp query id %u seq %u",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_TSTAMPREPLY:
ND_TCHECK(dp->icmp_ttime);
(void)snprintf(buf, sizeof(buf),
"time stamp reply id %u seq %u: org %s",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq),
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", recv %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", xmit %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime)));
break;
default:
str = tok2str(icmp2str, "type-#%d", dp->icmp_type);
break;
}
ND_PRINT((ndo, "ICMP %s, length %u", str, plen));
if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */
uint16_t sum, icmp_sum;
if (ND_TTEST2(*bp, plen)) {
vec[0].ptr = (const uint8_t *)(const void *)dp;
vec[0].len = plen;
sum = in_cksum(vec, 1);
if (sum != 0) {
icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum);
ND_PRINT((ndo, " (wrong icmp cksum %x (->%x)!)",
icmp_sum,
in_cksum_shouldbe(icmp_sum, sum)));
}
}
}
/*
* print the remnants of the IP packet.
* save the snaplength as this may get overidden in the IP printer.
*/
if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) {
bp += 8;
ND_PRINT((ndo, "\n\t"));
ip = (const struct ip *)bp;
snapend_save = ndo->ndo_snapend;
ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len));
ndo->ndo_snapend = snapend_save;
}
/*
* Attempt to decode the MPLS extensions only for some ICMP types.
*/
if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) {
ND_TCHECK(*ext_dp);
/*
* Check first if the mpls extension header shows a non-zero length.
* If the length field is not set then silently verify the checksum
* to check if an extension header is present. This is expedient,
* however not all implementations set the length field proper.
*/
if (!ext_dp->icmp_length &&
ND_TTEST2(ext_dp->icmp_ext_version_res, plen - ICMP_EXTD_MINLEN)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = plen - ICMP_EXTD_MINLEN;
if (in_cksum(vec, 1)) {
return;
}
}
ND_PRINT((ndo, "\n\tMPLS extension v%u",
ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res))));
/*
* Sanity checking of the header.
*/
if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) !=
ICMP_MPLS_EXT_VERSION) {
ND_PRINT((ndo, " packet not supported"));
return;
}
hlen = plen - ICMP_EXTD_MINLEN;
if (ND_TTEST2(ext_dp->icmp_ext_version_res, hlen)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = hlen;
ND_PRINT((ndo, ", checksum 0x%04x (%scorrect), length %u",
EXTRACT_16BITS(ext_dp->icmp_ext_checksum),
in_cksum(vec, 1) ? "in" : "",
hlen));
}
hlen -= 4; /* subtract common header size */
obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data;
while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) {
icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr;
ND_TCHECK(*icmp_mpls_ext_object_header);
obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length);
obj_class_num = icmp_mpls_ext_object_header->class_num;
obj_ctype = icmp_mpls_ext_object_header->ctype;
obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t);
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %u, length %u",
tok2str(icmp_mpls_ext_obj_values,"unknown",obj_class_num),
obj_class_num,
obj_ctype,
obj_tlen));
hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */
/* infinite loop protection */
if ((obj_class_num == 0) ||
(obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) {
return;
}
obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t);
switch (obj_class_num) {
case 1:
switch(obj_ctype) {
case 1:
ND_TCHECK2(*obj_tptr, 4);
raw_label = EXTRACT_32BITS(obj_tptr);
ND_PRINT((ndo, "\n\t label %u, exp %u", MPLS_LABEL(raw_label), MPLS_EXP(raw_label)));
if (MPLS_STACK(raw_label))
ND_PRINT((ndo, ", [S]"));
ND_PRINT((ndo, ", ttl %u", MPLS_TTL(raw_label)));
break;
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case 2:
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
break;
}
if (hlen < obj_tlen)
break;
hlen -= obj_tlen;
obj_tptr += obj_tlen;
}
}
return;
trunc:
ND_PRINT((ndo, "[|icmp]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2687_0 |
crossvul-cpp_data_bad_501_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-125/c/bad_501_0 |
crossvul-cpp_data_good_1282_2 | #include "Python.h"
#include "Python-ast.h"
#include "compile-ast3.h"
#include "node.h"
#include "grammar.h"
#include "token.h"
#include "ast.h"
#include "parsetok.h"
#include "errcode.h"
extern grammar _Ta3Parser_Grammar; /* from graminit.c */
// from Python/bltinmodule.c
static const char *
source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
{
const char *str;
Py_ssize_t size;
Py_buffer view;
*cmd_copy = NULL;
if (PyUnicode_Check(cmd)) {
cf->cf_flags |= PyCF_IGNORE_COOKIE;
str = PyUnicode_AsUTF8AndSize(cmd, &size);
if (str == NULL)
return NULL;
}
else if (PyBytes_Check(cmd)) {
str = PyBytes_AS_STRING(cmd);
size = PyBytes_GET_SIZE(cmd);
}
else if (PyByteArray_Check(cmd)) {
str = PyByteArray_AS_STRING(cmd);
size = PyByteArray_GET_SIZE(cmd);
}
else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
/* Copy to NUL-terminated buffer. */
*cmd_copy = PyBytes_FromStringAndSize(
(const char *)view.buf, view.len);
PyBuffer_Release(&view);
if (*cmd_copy == NULL) {
return NULL;
}
str = PyBytes_AS_STRING(*cmd_copy);
size = PyBytes_GET_SIZE(*cmd_copy);
}
else {
PyErr_Format(PyExc_TypeError,
"%s() arg 1 must be a %s object",
funcname, what);
return NULL;
}
if (strlen(str) != (size_t)size) {
PyErr_SetString(PyExc_ValueError,
"source code string cannot contain null bytes");
Py_CLEAR(*cmd_copy);
return NULL;
}
return str;
}
// from Python/pythonrun.c
/* compute parser flags based on compiler flags */
static int PARSER_FLAGS(PyCompilerFlags *flags)
{
int parser_flags = 0;
if (!flags)
return 0;
if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
if (flags->cf_flags & PyCF_IGNORE_COOKIE)
parser_flags |= PyPARSE_IGNORE_COOKIE;
if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
parser_flags |= PyPARSE_BARRY_AS_BDFL;
return parser_flags;
}
// from Python/pythonrun.c
/* Set the error appropriate to the given input error code (see errcode.h) */
static void
err_input(perrdetail *err)
{
PyObject *v, *w, *errtype, *errtext;
PyObject *msg_obj = NULL;
char *msg = NULL;
int offset = err->offset;
errtype = PyExc_SyntaxError;
switch (err->error) {
case E_ERROR:
return;
case E_SYNTAX:
errtype = PyExc_IndentationError;
if (err->expected == INDENT)
msg = "expected an indented block";
else if (err->token == INDENT)
msg = "unexpected indent";
else if (err->token == DEDENT)
msg = "unexpected unindent";
else {
errtype = PyExc_SyntaxError;
if (err->token == TYPE_COMMENT)
msg = "misplaced type annotation";
else
msg = "invalid syntax";
}
break;
case E_TOKEN:
msg = "invalid token";
break;
case E_EOFS:
msg = "EOF while scanning triple-quoted string literal";
break;
case E_EOLS:
msg = "EOL while scanning string literal";
break;
case E_INTR:
if (!PyErr_Occurred())
PyErr_SetNone(PyExc_KeyboardInterrupt);
goto cleanup;
case E_NOMEM:
PyErr_NoMemory();
goto cleanup;
case E_EOF:
msg = "unexpected EOF while parsing";
break;
case E_TABSPACE:
errtype = PyExc_TabError;
msg = "inconsistent use of tabs and spaces in indentation";
break;
case E_OVERFLOW:
msg = "expression too long";
break;
case E_DEDENT:
errtype = PyExc_IndentationError;
msg = "unindent does not match any outer indentation level";
break;
case E_TOODEEP:
errtype = PyExc_IndentationError;
msg = "too many levels of indentation";
break;
case E_DECODE: {
PyObject *type, *value, *tb;
PyErr_Fetch(&type, &value, &tb);
msg = "unknown decode error";
if (value != NULL)
msg_obj = PyObject_Str(value);
Py_XDECREF(type);
Py_XDECREF(value);
Py_XDECREF(tb);
break;
}
case E_LINECONT:
msg = "unexpected character after line continuation character";
break;
case E_IDENTIFIER:
msg = "invalid character in identifier";
break;
case E_BADSINGLE:
msg = "multiple statements found while compiling a single statement";
break;
default:
fprintf(stderr, "error=%d\n", err->error);
msg = "unknown parsing error";
break;
}
/* err->text may not be UTF-8 in case of decoding errors.
Explicitly convert to an object. */
if (!err->text) {
errtext = Py_None;
Py_INCREF(Py_None);
} else {
errtext = PyUnicode_DecodeUTF8(err->text, err->offset,
"replace");
if (errtext != NULL) {
Py_ssize_t len = strlen(err->text);
offset = (int)PyUnicode_GET_LENGTH(errtext);
if (len != err->offset) {
Py_DECREF(errtext);
errtext = PyUnicode_DecodeUTF8(err->text, len,
"replace");
}
}
}
v = Py_BuildValue("(OiiN)", err->filename,
err->lineno, offset, errtext);
if (v != NULL) {
if (msg_obj)
w = Py_BuildValue("(OO)", msg_obj, v);
else
w = Py_BuildValue("(sO)", msg, v);
} else
w = NULL;
Py_XDECREF(v);
PyErr_SetObject(errtype, w);
Py_XDECREF(w);
cleanup:
Py_XDECREF(msg_obj);
if (err->text != NULL) {
PyObject_FREE(err->text);
err->text = NULL;
}
}
// from Python/pythonrun.c
static void
err_free(perrdetail *err)
{
Py_CLEAR(err->filename);
}
// copy of PyParser_ASTFromStringObject in Python/pythonrun.c
/* Preferred access to parser is through AST. */
mod_ty
string_object_to_c_ast(const char *s, PyObject *filename, int start,
PyCompilerFlags *flags, int feature_version,
PyArena *arena)
{
mod_ty mod;
PyCompilerFlags localflags;
perrdetail err;
int iflags = PARSER_FLAGS(flags);
node *n;
if (feature_version >= 7)
iflags |= PyPARSE_ASYNC_ALWAYS;
n = Ta3Parser_ParseStringObject(s, filename,
&_Ta3Parser_Grammar, start, &err,
&iflags);
if (flags == NULL) {
localflags.cf_flags = 0;
flags = &localflags;
}
if (n) {
flags->cf_flags |= iflags & PyCF_MASK;
mod = Ta3AST_FromNodeObject(n, flags, filename, feature_version, arena);
Ta3Node_Free(n);
}
else {
err_input(&err);
mod = NULL;
}
err_free(&err);
return mod;
}
// adapted from Py_CompileStringObject in Python/pythonrun.c
static PyObject *
string_object_to_py_ast(const char *str, PyObject *filename, int start,
PyCompilerFlags *flags, int feature_version)
{
mod_ty mod;
PyObject *result;
PyArena *arena = PyArena_New();
if (arena == NULL)
return NULL;
mod = string_object_to_c_ast(str, filename, start, flags, feature_version, arena);
if (mod == NULL) {
PyArena_Free(arena);
return NULL;
}
result = Ta3AST_mod2obj(mod);
PyArena_Free(arena);
return result;
}
// adapted from builtin_compile_impl in Python/bltinmodule.c
static PyObject *
ast3_parse_impl(PyObject *source,
PyObject *filename,
const char *mode,
int feature_version)
{
PyObject *source_copy;
const char *str;
int compile_mode = -1;
PyCompilerFlags cf;
int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
PyObject *result;
cf.cf_flags = PyCF_ONLY_AST | PyCF_SOURCE_IS_UTF8;
if (strcmp(mode, "exec") == 0)
compile_mode = 0;
else if (strcmp(mode, "eval") == 0)
compile_mode = 1;
else if (strcmp(mode, "single") == 0)
compile_mode = 2;
else if (strcmp(mode, "func_type") == 0)
compile_mode = 3;
else {
PyErr_SetString(PyExc_ValueError,
"parse() mode must be 'exec', 'eval', 'single', for 'func_type'");
goto error;
}
str = source_as_string(source, "parse", "string or bytes", &cf, &source_copy);
if (str == NULL)
goto error;
result = string_object_to_py_ast(str, filename, start[compile_mode], &cf, feature_version);
Py_XDECREF(source_copy);
goto finally;
error:
result = NULL;
finally:
Py_DECREF(filename);
return result;
}
// adapted from builtin_compile in Python/clinic/bltinmodule.c.h
PyObject *
ast3_parse(PyObject *self, PyObject *args)
{
PyObject *return_value = NULL;
PyObject *source;
PyObject *filename;
const char *mode;
int feature_version;
if (PyArg_ParseTuple(args, "OO&si:parse", &source, PyUnicode_FSDecoder, &filename, &mode, &feature_version))
return_value = ast3_parse_impl(source, filename, mode, feature_version);
return return_value;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1282_2 |
crossvul-cpp_data_good_3197_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-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/memory-private.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteSUNImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% 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 extent)
{
register const unsigned char
*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;
while (((size_t) (p-compressed_pixels) < length) &&
((size_t) (q-pixels) < extent))
{
byte=(*p++);
if (byte != 128U)
*q++=byte;
else
{
/*
Runlength-encoded packet: <count><byte>.
*/
if (((size_t) (p-compressed_pixels) >= length))
break;
count=(*p++);
if (count > 0)
{
if (((size_t) (p-compressed_pixels) >= length))
break;
byte=(*p++);
}
while ((count >= 0) && ((size_t) (q-pixels) < extent))
{
*q++=byte;
count--;
}
}
}
return(((size_t) (q-pixels) == extent) ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% 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 IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bytes_per_line,
extent,
height,
pixels_length,
quantum;
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);
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 != 1) && (sun_info.depth != 8) &&
(sun_info.depth != 24) && (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) == 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=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=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=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:
break;
}
image->matte=sun_info.depth == 32 ? MagickTrue : MagickFalse;
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);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (sun_info.length == 0)
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
number_pixels=(MagickSizeType) (image->columns*image->rows);
if ((sun_info.type != RT_ENCODED) &&
((number_pixels*sun_info.depth) > (8UL*sun_info.length)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (HeapOverflowSanityCheck(sun_info.width,sun_info.depth) != MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bytes_per_line=sun_info.width*sun_info.depth;
sun_data=(unsigned char *) AcquireQuantumMemory(sun_info.length,
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)
{
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
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))
{
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
}
quantum=sun_info.depth == 1 ? 15 : 7;
bytes_per_line+=quantum;
bytes_per_line<<=1;
if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+quantum))
{
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
}
bytes_per_line>>=4;
if (HeapOverflowSanityCheck(height,bytes_per_line) != MagickFalse)
{
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
}
pixels_length=height*bytes_per_line;
sun_pixels=(unsigned char *) AcquireQuantumMemory(pixels_length+image->rows,
sizeof(*sun_pixels));
if (sun_pixels == (unsigned char *) NULL)
{
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
ResetMagickMemory(sun_pixels,0,pixels_length*sizeof(*sun_pixels));
if (sun_info.type == RT_ENCODED)
{
status=DecodeImage(sun_data,sun_info.length,sun_pixels,pixels_length);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
else
{
if (sun_info.length > pixels_length)
{
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);
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 == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=7; bit >= 0; bit--)
SetPixelIndex(indexes+x+7-bit,((*p) & (0x01 << bit) ? 0x00 : 0x01));
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--)
SetPixelIndex(indexes+x+7-bit,(*p) & (0x01 << bit) ? 0x00 : 0x01);
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 == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(indexes+x,ConstrainColormapIndex(image,*p));
p++;
}
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->matte != MagickFalse)
bytes_per_pixel++;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
if (sun_info.type == RT_STANDARD)
{
SetPixelBlue(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelRed(q,ScaleCharToQuantum(*p++));
}
else
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
}
if (image->colors != 0)
{
SetPixelRed(q,image->colormap[(ssize_t)
GetPixelRed(q)].red);
SetPixelGreen(q,image->colormap[(ssize_t)
GetPixelGreen(q)].green);
SetPixelBlue(q,image->colormap[(ssize_t)
GetPixelBlue(q)].blue);
}
q++;
}
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);
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);
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)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteSUNImage(const ImageInfo *image_info,Image *image)
{
#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 IndexPacket
*indexes;
register const PixelPacket
*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);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
/*
Initialize SUN raster file header.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
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->matte ? 32U : 24U;
sun_info.length=(unsigned int) ((image->matte ? 4 : 3)*number_pixels);
sun_info.length+=sun_info.length & 0x01 ? (unsigned int) image->rows :
0;
}
else
if (SetImageMonochrome(image,&image->exception))
{
/*
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->matte != MagickFalse)
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,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->matte != MagickFalse)
*q++=ScaleQuantumToChar(GetPixelAlpha(p));
*q++=ScaleQuantumToChar(GetPixelRed(p));
*q++=ScaleQuantumToChar(GetPixelGreen(p));
*q++=ScaleQuantumToChar(GetPixelBlue(p));
p++;
}
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 (SetImageMonochrome(image,&image->exception))
{
register unsigned char
bit,
byte;
/*
Convert PseudoClass image to a SUN monochrome image.
*/
(void) SetImageType(image,BilevelType);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=1;
if (GetPixelLuma(image,p) < (QuantumRange/2.0))
byte|=0x01;
bit++;
if (bit == 8)
{
(void) WriteBlobByte(image,byte);
bit=0;
byte=0;
}
p++;
}
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(
image->colormap[i].red));
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
image->colormap[i].green));
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
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,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) WriteBlobByte(image,(unsigned char)
GetPixelIndex(indexes+x));
p++;
}
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_3197_0 |
crossvul-cpp_data_bad_1370_1 | /*-
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved.
* Copyright (c) 2008-2012, by Randall Stewart. All rights reserved.
* Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* a) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* b) Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* c) Neither the name of Cisco Systems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef __FreeBSD__
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: head/sys/netinet/sctp_pcb.c 353477 2019-10-13 16:14:04Z markj $");
#endif
#include <netinet/sctp_os.h>
#ifdef __FreeBSD__
#include <sys/proc.h>
#endif
#include <netinet/sctp_var.h>
#include <netinet/sctp_sysctl.h>
#include <netinet/sctp_pcb.h>
#include <netinet/sctputil.h>
#include <netinet/sctp.h>
#include <netinet/sctp_header.h>
#include <netinet/sctp_asconf.h>
#include <netinet/sctp_output.h>
#include <netinet/sctp_timer.h>
#include <netinet/sctp_bsd_addr.h>
#if defined(INET) || defined(INET6)
#if !defined(__Userspace_os_Windows)
#include <netinet/udp.h>
#endif
#endif
#ifdef INET6
#if defined(__Userspace__)
#include "user_ip6_var.h"
#else
#include <netinet6/ip6_var.h>
#endif
#endif
#if defined(__FreeBSD__)
#include <sys/sched.h>
#include <sys/smp.h>
#include <sys/unistd.h>
#endif
#if defined(__Userspace__)
#include <user_socketvar.h>
#include <user_atomic.h>
#if !defined(__Userspace_os_Windows)
#include <netdb.h>
#endif
#endif
#if defined(__APPLE__)
#define APPLE_FILE_NO 4
#endif
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
VNET_DEFINE(struct sctp_base_info, system_base_info);
#else
struct sctp_base_info system_base_info;
#endif
/* FIX: we don't handle multiple link local scopes */
/* "scopeless" replacement IN6_ARE_ADDR_EQUAL */
#ifdef INET6
int
SCTP6_ARE_ADDR_EQUAL(struct sockaddr_in6 *a, struct sockaddr_in6 *b)
{
#ifdef SCTP_EMBEDDED_V6_SCOPE
#if defined(__APPLE__)
struct in6_addr tmp_a, tmp_b;
tmp_a = a->sin6_addr;
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
if (in6_embedscope(&tmp_a, a, NULL, NULL) != 0) {
#else
if (in6_embedscope(&tmp_a, a, NULL, NULL, NULL) != 0) {
#endif
return (0);
}
tmp_b = b->sin6_addr;
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
if (in6_embedscope(&tmp_b, b, NULL, NULL) != 0) {
#else
if (in6_embedscope(&tmp_b, b, NULL, NULL, NULL) != 0) {
#endif
return (0);
}
return (IN6_ARE_ADDR_EQUAL(&tmp_a, &tmp_b));
#elif defined(SCTP_KAME)
struct sockaddr_in6 tmp_a, tmp_b;
memcpy(&tmp_a, a, sizeof(struct sockaddr_in6));
if (sa6_embedscope(&tmp_a, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
return (0);
}
memcpy(&tmp_b, b, sizeof(struct sockaddr_in6));
if (sa6_embedscope(&tmp_b, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
return (0);
}
return (IN6_ARE_ADDR_EQUAL(&tmp_a.sin6_addr, &tmp_b.sin6_addr));
#else
struct in6_addr tmp_a, tmp_b;
tmp_a = a->sin6_addr;
if (in6_embedscope(&tmp_a, a) != 0) {
return (0);
}
tmp_b = b->sin6_addr;
if (in6_embedscope(&tmp_b, b) != 0) {
return (0);
}
return (IN6_ARE_ADDR_EQUAL(&tmp_a, &tmp_b));
#endif
#else
return (IN6_ARE_ADDR_EQUAL(&(a->sin6_addr), &(b->sin6_addr)));
#endif /* SCTP_EMBEDDED_V6_SCOPE */
}
#endif
void
sctp_fill_pcbinfo(struct sctp_pcbinfo *spcb)
{
/*
* We really don't need to lock this, but I will just because it
* does not hurt.
*/
SCTP_INP_INFO_RLOCK();
spcb->ep_count = SCTP_BASE_INFO(ipi_count_ep);
spcb->asoc_count = SCTP_BASE_INFO(ipi_count_asoc);
spcb->laddr_count = SCTP_BASE_INFO(ipi_count_laddr);
spcb->raddr_count = SCTP_BASE_INFO(ipi_count_raddr);
spcb->chk_count = SCTP_BASE_INFO(ipi_count_chunk);
spcb->readq_count = SCTP_BASE_INFO(ipi_count_readq);
spcb->stream_oque = SCTP_BASE_INFO(ipi_count_strmoq);
spcb->free_chunks = SCTP_BASE_INFO(ipi_free_chunks);
SCTP_INP_INFO_RUNLOCK();
}
/*-
* Addresses are added to VRF's (Virtual Router's). For BSD we
* have only the default VRF 0. We maintain a hash list of
* VRF's. Each VRF has its own list of sctp_ifn's. Each of
* these has a list of addresses. When we add a new address
* to a VRF we lookup the ifn/ifn_index, if the ifn does
* not exist we create it and add it to the list of IFN's
* within the VRF. Once we have the sctp_ifn, we add the
* address to the list. So we look something like:
*
* hash-vrf-table
* vrf-> ifn-> ifn -> ifn
* vrf |
* ... +--ifa-> ifa -> ifa
* vrf
*
* We keep these separate lists since the SCTP subsystem will
* point to these from its source address selection nets structure.
* When an address is deleted it does not happen right away on
* the SCTP side, it gets scheduled. What we do when a
* delete happens is immediately remove the address from
* the master list and decrement the refcount. As our
* addip iterator works through and frees the src address
* selection pointing to the sctp_ifa, eventually the refcount
* will reach 0 and we will delete it. Note that it is assumed
* that any locking on system level ifn/ifa is done at the
* caller of these functions and these routines will only
* lock the SCTP structures as they add or delete things.
*
* Other notes on VRF concepts.
* - An endpoint can be in multiple VRF's
* - An association lives within a VRF and only one VRF.
* - Any incoming packet we can deduce the VRF for by
* looking at the mbuf/pak inbound (for BSD its VRF=0 :D)
* - Any downward send call or connect call must supply the
* VRF via ancillary data or via some sort of set default
* VRF socket option call (again for BSD no brainer since
* the VRF is always 0).
* - An endpoint may add multiple VRF's to it.
* - Listening sockets can accept associations in any
* of the VRF's they are in but the assoc will end up
* in only one VRF (gotten from the packet or connect/send).
*
*/
struct sctp_vrf *
sctp_allocate_vrf(int vrf_id)
{
struct sctp_vrf *vrf = NULL;
struct sctp_vrflist *bucket;
/* First allocate the VRF structure */
vrf = sctp_find_vrf(vrf_id);
if (vrf) {
/* Already allocated */
return (vrf);
}
SCTP_MALLOC(vrf, struct sctp_vrf *, sizeof(struct sctp_vrf),
SCTP_M_VRF);
if (vrf == NULL) {
/* No memory */
#ifdef INVARIANTS
panic("No memory for VRF:%d", vrf_id);
#endif
return (NULL);
}
/* setup the VRF */
memset(vrf, 0, sizeof(struct sctp_vrf));
vrf->vrf_id = vrf_id;
LIST_INIT(&vrf->ifnlist);
vrf->total_ifa_count = 0;
vrf->refcount = 0;
/* now also setup table ids */
SCTP_INIT_VRF_TABLEID(vrf);
/* Init the HASH of addresses */
vrf->vrf_addr_hash = SCTP_HASH_INIT(SCTP_VRF_ADDR_HASH_SIZE,
&vrf->vrf_addr_hashmark);
if (vrf->vrf_addr_hash == NULL) {
/* No memory */
#ifdef INVARIANTS
panic("No memory for VRF:%d", vrf_id);
#endif
SCTP_FREE(vrf, SCTP_M_VRF);
return (NULL);
}
/* Add it to the hash table */
bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(vrf_id & SCTP_BASE_INFO(hashvrfmark))];
LIST_INSERT_HEAD(bucket, vrf, next_vrf);
atomic_add_int(&SCTP_BASE_INFO(ipi_count_vrfs), 1);
return (vrf);
}
struct sctp_ifn *
sctp_find_ifn(void *ifn, uint32_t ifn_index)
{
struct sctp_ifn *sctp_ifnp;
struct sctp_ifnlist *hash_ifn_head;
/* We assume the lock is held for the addresses
* if that's wrong problems could occur :-)
*/
hash_ifn_head = &SCTP_BASE_INFO(vrf_ifn_hash)[(ifn_index & SCTP_BASE_INFO(vrf_ifn_hashmark))];
LIST_FOREACH(sctp_ifnp, hash_ifn_head, next_bucket) {
if (sctp_ifnp->ifn_index == ifn_index) {
return (sctp_ifnp);
}
if (sctp_ifnp->ifn_p && ifn && (sctp_ifnp->ifn_p == ifn)) {
return (sctp_ifnp);
}
}
return (NULL);
}
struct sctp_vrf *
sctp_find_vrf(uint32_t vrf_id)
{
struct sctp_vrflist *bucket;
struct sctp_vrf *liste;
bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(vrf_id & SCTP_BASE_INFO(hashvrfmark))];
LIST_FOREACH(liste, bucket, next_vrf) {
if (vrf_id == liste->vrf_id) {
return (liste);
}
}
return (NULL);
}
void
sctp_free_vrf(struct sctp_vrf *vrf)
{
if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&vrf->refcount)) {
if (vrf->vrf_addr_hash) {
SCTP_HASH_FREE(vrf->vrf_addr_hash, vrf->vrf_addr_hashmark);
vrf->vrf_addr_hash = NULL;
}
/* We zero'd the count */
LIST_REMOVE(vrf, next_vrf);
SCTP_FREE(vrf, SCTP_M_VRF);
atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_vrfs), 1);
}
}
void
sctp_free_ifn(struct sctp_ifn *sctp_ifnp)
{
if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&sctp_ifnp->refcount)) {
/* We zero'd the count */
if (sctp_ifnp->vrf) {
sctp_free_vrf(sctp_ifnp->vrf);
}
SCTP_FREE(sctp_ifnp, SCTP_M_IFN);
atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_ifns), 1);
}
}
void
sctp_update_ifn_mtu(uint32_t ifn_index, uint32_t mtu)
{
struct sctp_ifn *sctp_ifnp;
sctp_ifnp = sctp_find_ifn((void *)NULL, ifn_index);
if (sctp_ifnp != NULL) {
sctp_ifnp->ifn_mtu = mtu;
}
}
void
sctp_free_ifa(struct sctp_ifa *sctp_ifap)
{
if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&sctp_ifap->refcount)) {
/* We zero'd the count */
if (sctp_ifap->ifn_p) {
sctp_free_ifn(sctp_ifap->ifn_p);
}
SCTP_FREE(sctp_ifap, SCTP_M_IFA);
atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_ifas), 1);
}
}
static void
sctp_delete_ifn(struct sctp_ifn *sctp_ifnp, int hold_addr_lock)
{
struct sctp_ifn *found;
found = sctp_find_ifn(sctp_ifnp->ifn_p, sctp_ifnp->ifn_index);
if (found == NULL) {
/* Not in the list.. sorry */
return;
}
if (hold_addr_lock == 0)
SCTP_IPI_ADDR_WLOCK();
LIST_REMOVE(sctp_ifnp, next_bucket);
LIST_REMOVE(sctp_ifnp, next_ifn);
SCTP_DEREGISTER_INTERFACE(sctp_ifnp->ifn_index,
sctp_ifnp->registered_af);
if (hold_addr_lock == 0)
SCTP_IPI_ADDR_WUNLOCK();
/* Take away the reference, and possibly free it */
sctp_free_ifn(sctp_ifnp);
}
void
sctp_mark_ifa_addr_down(uint32_t vrf_id, struct sockaddr *addr,
const char *if_name, uint32_t ifn_index)
{
struct sctp_vrf *vrf;
struct sctp_ifa *sctp_ifap;
SCTP_IPI_ADDR_RLOCK();
vrf = sctp_find_vrf(vrf_id);
if (vrf == NULL) {
SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
goto out;
}
sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
if (sctp_ifap == NULL) {
SCTPDBG(SCTP_DEBUG_PCB4, "Can't find sctp_ifap for address\n");
goto out;
}
if (sctp_ifap->ifn_p == NULL) {
SCTPDBG(SCTP_DEBUG_PCB4, "IFA has no IFN - can't mark unusable\n");
goto out;
}
if (if_name) {
if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) != 0) {
SCTPDBG(SCTP_DEBUG_PCB4, "IFN %s of IFA not the same as %s\n",
sctp_ifap->ifn_p->ifn_name, if_name);
goto out;
}
} else {
if (sctp_ifap->ifn_p->ifn_index != ifn_index) {
SCTPDBG(SCTP_DEBUG_PCB4, "IFA owned by ifn_index:%d down command for ifn_index:%d - ignored\n",
sctp_ifap->ifn_p->ifn_index, ifn_index);
goto out;
}
}
sctp_ifap->localifa_flags &= (~SCTP_ADDR_VALID);
sctp_ifap->localifa_flags |= SCTP_ADDR_IFA_UNUSEABLE;
out:
SCTP_IPI_ADDR_RUNLOCK();
}
void
sctp_mark_ifa_addr_up(uint32_t vrf_id, struct sockaddr *addr,
const char *if_name, uint32_t ifn_index)
{
struct sctp_vrf *vrf;
struct sctp_ifa *sctp_ifap;
SCTP_IPI_ADDR_RLOCK();
vrf = sctp_find_vrf(vrf_id);
if (vrf == NULL) {
SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
goto out;
}
sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
if (sctp_ifap == NULL) {
SCTPDBG(SCTP_DEBUG_PCB4, "Can't find sctp_ifap for address\n");
goto out;
}
if (sctp_ifap->ifn_p == NULL) {
SCTPDBG(SCTP_DEBUG_PCB4, "IFA has no IFN - can't mark unusable\n");
goto out;
}
if (if_name) {
if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) != 0) {
SCTPDBG(SCTP_DEBUG_PCB4, "IFN %s of IFA not the same as %s\n",
sctp_ifap->ifn_p->ifn_name, if_name);
goto out;
}
} else {
if (sctp_ifap->ifn_p->ifn_index != ifn_index) {
SCTPDBG(SCTP_DEBUG_PCB4, "IFA owned by ifn_index:%d down command for ifn_index:%d - ignored\n",
sctp_ifap->ifn_p->ifn_index, ifn_index);
goto out;
}
}
sctp_ifap->localifa_flags &= (~SCTP_ADDR_IFA_UNUSEABLE);
sctp_ifap->localifa_flags |= SCTP_ADDR_VALID;
out:
SCTP_IPI_ADDR_RUNLOCK();
}
/*-
* Add an ifa to an ifn.
* Register the interface as necessary.
* NOTE: ADDR write lock MUST be held.
*/
static void
sctp_add_ifa_to_ifn(struct sctp_ifn *sctp_ifnp, struct sctp_ifa *sctp_ifap)
{
int ifa_af;
LIST_INSERT_HEAD(&sctp_ifnp->ifalist, sctp_ifap, next_ifa);
sctp_ifap->ifn_p = sctp_ifnp;
atomic_add_int(&sctp_ifap->ifn_p->refcount, 1);
/* update address counts */
sctp_ifnp->ifa_count++;
ifa_af = sctp_ifap->address.sa.sa_family;
switch (ifa_af) {
#ifdef INET
case AF_INET:
sctp_ifnp->num_v4++;
break;
#endif
#ifdef INET6
case AF_INET6:
sctp_ifnp->num_v6++;
break;
#endif
default:
break;
}
if (sctp_ifnp->ifa_count == 1) {
/* register the new interface */
SCTP_REGISTER_INTERFACE(sctp_ifnp->ifn_index, ifa_af);
sctp_ifnp->registered_af = ifa_af;
}
}
/*-
* Remove an ifa from its ifn.
* If no more addresses exist, remove the ifn too. Otherwise, re-register
* the interface based on the remaining address families left.
* NOTE: ADDR write lock MUST be held.
*/
static void
sctp_remove_ifa_from_ifn(struct sctp_ifa *sctp_ifap)
{
LIST_REMOVE(sctp_ifap, next_ifa);
if (sctp_ifap->ifn_p) {
/* update address counts */
sctp_ifap->ifn_p->ifa_count--;
switch (sctp_ifap->address.sa.sa_family) {
#ifdef INET
case AF_INET:
sctp_ifap->ifn_p->num_v4--;
break;
#endif
#ifdef INET6
case AF_INET6:
sctp_ifap->ifn_p->num_v6--;
break;
#endif
default:
break;
}
if (LIST_EMPTY(&sctp_ifap->ifn_p->ifalist)) {
/* remove the ifn, possibly freeing it */
sctp_delete_ifn(sctp_ifap->ifn_p, SCTP_ADDR_LOCKED);
} else {
/* re-register address family type, if needed */
if ((sctp_ifap->ifn_p->num_v6 == 0) &&
(sctp_ifap->ifn_p->registered_af == AF_INET6)) {
SCTP_DEREGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET6);
SCTP_REGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET);
sctp_ifap->ifn_p->registered_af = AF_INET;
} else if ((sctp_ifap->ifn_p->num_v4 == 0) &&
(sctp_ifap->ifn_p->registered_af == AF_INET)) {
SCTP_DEREGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET);
SCTP_REGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET6);
sctp_ifap->ifn_p->registered_af = AF_INET6;
}
/* free the ifn refcount */
sctp_free_ifn(sctp_ifap->ifn_p);
}
sctp_ifap->ifn_p = NULL;
}
}
struct sctp_ifa *
sctp_add_addr_to_vrf(uint32_t vrf_id, void *ifn, uint32_t ifn_index,
uint32_t ifn_type, const char *if_name, void *ifa,
struct sockaddr *addr, uint32_t ifa_flags,
int dynamic_add)
{
struct sctp_vrf *vrf;
struct sctp_ifn *sctp_ifnp = NULL;
struct sctp_ifa *sctp_ifap = NULL;
struct sctp_ifalist *hash_addr_head;
struct sctp_ifnlist *hash_ifn_head;
uint32_t hash_of_addr;
int new_ifn_af = 0;
#ifdef SCTP_DEBUG
SCTPDBG(SCTP_DEBUG_PCB4, "vrf_id 0x%x: adding address: ", vrf_id);
SCTPDBG_ADDR(SCTP_DEBUG_PCB4, addr);
#endif
SCTP_IPI_ADDR_WLOCK();
sctp_ifnp = sctp_find_ifn(ifn, ifn_index);
if (sctp_ifnp) {
vrf = sctp_ifnp->vrf;
} else {
vrf = sctp_find_vrf(vrf_id);
if (vrf == NULL) {
vrf = sctp_allocate_vrf(vrf_id);
if (vrf == NULL) {
SCTP_IPI_ADDR_WUNLOCK();
return (NULL);
}
}
}
if (sctp_ifnp == NULL) {
/* build one and add it, can't hold lock
* until after malloc done though.
*/
SCTP_IPI_ADDR_WUNLOCK();
SCTP_MALLOC(sctp_ifnp, struct sctp_ifn *,
sizeof(struct sctp_ifn), SCTP_M_IFN);
if (sctp_ifnp == NULL) {
#ifdef INVARIANTS
panic("No memory for IFN");
#endif
return (NULL);
}
memset(sctp_ifnp, 0, sizeof(struct sctp_ifn));
sctp_ifnp->ifn_index = ifn_index;
sctp_ifnp->ifn_p = ifn;
sctp_ifnp->ifn_type = ifn_type;
sctp_ifnp->refcount = 0;
sctp_ifnp->vrf = vrf;
atomic_add_int(&vrf->refcount, 1);
sctp_ifnp->ifn_mtu = SCTP_GATHER_MTU_FROM_IFN_INFO(ifn, ifn_index, addr->sa_family);
if (if_name != NULL) {
snprintf(sctp_ifnp->ifn_name, SCTP_IFNAMSIZ, "%s", if_name);
} else {
snprintf(sctp_ifnp->ifn_name, SCTP_IFNAMSIZ, "%s", "unknown");
}
hash_ifn_head = &SCTP_BASE_INFO(vrf_ifn_hash)[(ifn_index & SCTP_BASE_INFO(vrf_ifn_hashmark))];
LIST_INIT(&sctp_ifnp->ifalist);
SCTP_IPI_ADDR_WLOCK();
LIST_INSERT_HEAD(hash_ifn_head, sctp_ifnp, next_bucket);
LIST_INSERT_HEAD(&vrf->ifnlist, sctp_ifnp, next_ifn);
atomic_add_int(&SCTP_BASE_INFO(ipi_count_ifns), 1);
new_ifn_af = 1;
}
sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
if (sctp_ifap) {
/* Hmm, it already exists? */
if ((sctp_ifap->ifn_p) &&
(sctp_ifap->ifn_p->ifn_index == ifn_index)) {
SCTPDBG(SCTP_DEBUG_PCB4, "Using existing ifn %s (0x%x) for ifa %p\n",
sctp_ifap->ifn_p->ifn_name, ifn_index,
(void *)sctp_ifap);
if (new_ifn_af) {
/* Remove the created one that we don't want */
sctp_delete_ifn(sctp_ifnp, SCTP_ADDR_LOCKED);
}
if (sctp_ifap->localifa_flags & SCTP_BEING_DELETED) {
/* easy to solve, just switch back to active */
SCTPDBG(SCTP_DEBUG_PCB4, "Clearing deleted ifa flag\n");
sctp_ifap->localifa_flags = SCTP_ADDR_VALID;
sctp_ifap->ifn_p = sctp_ifnp;
atomic_add_int(&sctp_ifap->ifn_p->refcount, 1);
}
exit_stage_left:
SCTP_IPI_ADDR_WUNLOCK();
return (sctp_ifap);
} else {
if (sctp_ifap->ifn_p) {
/*
* The last IFN gets the address, remove the
* old one
*/
SCTPDBG(SCTP_DEBUG_PCB4, "Moving ifa %p from %s (0x%x) to %s (0x%x)\n",
(void *)sctp_ifap, sctp_ifap->ifn_p->ifn_name,
sctp_ifap->ifn_p->ifn_index, if_name,
ifn_index);
/* remove the address from the old ifn */
sctp_remove_ifa_from_ifn(sctp_ifap);
/* move the address over to the new ifn */
sctp_add_ifa_to_ifn(sctp_ifnp, sctp_ifap);
goto exit_stage_left;
} else {
/* repair ifnp which was NULL ? */
sctp_ifap->localifa_flags = SCTP_ADDR_VALID;
SCTPDBG(SCTP_DEBUG_PCB4, "Repairing ifn %p for ifa %p\n",
(void *)sctp_ifnp, (void *)sctp_ifap);
sctp_add_ifa_to_ifn(sctp_ifnp, sctp_ifap);
}
goto exit_stage_left;
}
}
SCTP_IPI_ADDR_WUNLOCK();
SCTP_MALLOC(sctp_ifap, struct sctp_ifa *, sizeof(struct sctp_ifa), SCTP_M_IFA);
if (sctp_ifap == NULL) {
#ifdef INVARIANTS
panic("No memory for IFA");
#endif
return (NULL);
}
memset(sctp_ifap, 0, sizeof(struct sctp_ifa));
sctp_ifap->ifn_p = sctp_ifnp;
atomic_add_int(&sctp_ifnp->refcount, 1);
sctp_ifap->vrf_id = vrf_id;
sctp_ifap->ifa = ifa;
#ifdef HAVE_SA_LEN
memcpy(&sctp_ifap->address, addr, addr->sa_len);
#else
switch (addr->sa_family) {
#ifdef INET
case AF_INET:
memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_in));
break;
#endif
#ifdef INET6
case AF_INET6:
memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_in6));
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_conn));
break;
#endif
default:
/* TSNH */
break;
}
#endif
sctp_ifap->localifa_flags = SCTP_ADDR_VALID | SCTP_ADDR_DEFER_USE;
sctp_ifap->flags = ifa_flags;
/* Set scope */
switch (sctp_ifap->address.sa.sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin;
sin = &sctp_ifap->address.sin;
if (SCTP_IFN_IS_IFT_LOOP(sctp_ifap->ifn_p) ||
(IN4_ISLOOPBACK_ADDRESS(&sin->sin_addr))) {
sctp_ifap->src_is_loop = 1;
}
if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
sctp_ifap->src_is_priv = 1;
}
sctp_ifnp->num_v4++;
if (new_ifn_af)
new_ifn_af = AF_INET;
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
/* ok to use deprecated addresses? */
struct sockaddr_in6 *sin6;
sin6 = &sctp_ifap->address.sin6;
if (SCTP_IFN_IS_IFT_LOOP(sctp_ifap->ifn_p) ||
(IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))) {
sctp_ifap->src_is_loop = 1;
}
if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
sctp_ifap->src_is_priv = 1;
}
sctp_ifnp->num_v6++;
if (new_ifn_af)
new_ifn_af = AF_INET6;
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
if (new_ifn_af)
new_ifn_af = AF_CONN;
break;
#endif
default:
new_ifn_af = 0;
break;
}
hash_of_addr = sctp_get_ifa_hash_val(&sctp_ifap->address.sa);
if ((sctp_ifap->src_is_priv == 0) &&
(sctp_ifap->src_is_loop == 0)) {
sctp_ifap->src_is_glob = 1;
}
SCTP_IPI_ADDR_WLOCK();
hash_addr_head = &vrf->vrf_addr_hash[(hash_of_addr & vrf->vrf_addr_hashmark)];
LIST_INSERT_HEAD(hash_addr_head, sctp_ifap, next_bucket);
sctp_ifap->refcount = 1;
LIST_INSERT_HEAD(&sctp_ifnp->ifalist, sctp_ifap, next_ifa);
sctp_ifnp->ifa_count++;
vrf->total_ifa_count++;
atomic_add_int(&SCTP_BASE_INFO(ipi_count_ifas), 1);
if (new_ifn_af) {
SCTP_REGISTER_INTERFACE(ifn_index, new_ifn_af);
sctp_ifnp->registered_af = new_ifn_af;
}
SCTP_IPI_ADDR_WUNLOCK();
if (dynamic_add) {
/* Bump up the refcount so that when the timer
* completes it will drop back down.
*/
struct sctp_laddr *wi;
atomic_add_int(&sctp_ifap->refcount, 1);
wi = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
if (wi == NULL) {
/*
* Gak, what can we do? We have lost an address
* change can you say HOSED?
*/
SCTPDBG(SCTP_DEBUG_PCB4, "Lost an address change?\n");
/* Opps, must decrement the count */
sctp_del_addr_from_vrf(vrf_id, addr, ifn_index,
if_name);
return (NULL);
}
SCTP_INCR_LADDR_COUNT();
memset(wi, 0, sizeof(*wi));
(void)SCTP_GETTIME_TIMEVAL(&wi->start_time);
wi->ifa = sctp_ifap;
wi->action = SCTP_ADD_IP_ADDRESS;
SCTP_WQ_ADDR_LOCK();
LIST_INSERT_HEAD(&SCTP_BASE_INFO(addr_wq), wi, sctp_nxt_addr);
sctp_timer_start(SCTP_TIMER_TYPE_ADDR_WQ,
(struct sctp_inpcb *)NULL,
(struct sctp_tcb *)NULL,
(struct sctp_nets *)NULL);
SCTP_WQ_ADDR_UNLOCK();
} else {
/* it's ready for use */
sctp_ifap->localifa_flags &= ~SCTP_ADDR_DEFER_USE;
}
return (sctp_ifap);
}
void
sctp_del_addr_from_vrf(uint32_t vrf_id, struct sockaddr *addr,
uint32_t ifn_index, const char *if_name)
{
struct sctp_vrf *vrf;
struct sctp_ifa *sctp_ifap = NULL;
SCTP_IPI_ADDR_WLOCK();
vrf = sctp_find_vrf(vrf_id);
if (vrf == NULL) {
SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
goto out_now;
}
#ifdef SCTP_DEBUG
SCTPDBG(SCTP_DEBUG_PCB4, "vrf_id 0x%x: deleting address:", vrf_id);
SCTPDBG_ADDR(SCTP_DEBUG_PCB4, addr);
#endif
sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
if (sctp_ifap) {
/* Validate the delete */
if (sctp_ifap->ifn_p) {
int valid = 0;
/*-
* The name has priority over the ifn_index
* if its given. We do this especially for
* panda who might recycle indexes fast.
*/
if (if_name) {
if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) == 0) {
/* They match its a correct delete */
valid = 1;
}
}
if (!valid) {
/* last ditch check ifn_index */
if (ifn_index == sctp_ifap->ifn_p->ifn_index) {
valid = 1;
}
}
if (!valid) {
SCTPDBG(SCTP_DEBUG_PCB4, "ifn:%d ifname:%s does not match addresses\n",
ifn_index, ((if_name == NULL) ? "NULL" : if_name));
SCTPDBG(SCTP_DEBUG_PCB4, "ifn:%d ifname:%s - ignoring delete\n",
sctp_ifap->ifn_p->ifn_index, sctp_ifap->ifn_p->ifn_name);
SCTP_IPI_ADDR_WUNLOCK();
return;
}
}
SCTPDBG(SCTP_DEBUG_PCB4, "Deleting ifa %p\n", (void *)sctp_ifap);
sctp_ifap->localifa_flags &= SCTP_ADDR_VALID;
/*
* We don't set the flag. This means that the structure will
* hang around in EP's that have bound specific to it until
* they close. This gives us TCP like behavior if someone
* removes an address (or for that matter adds it right back).
*/
/* sctp_ifap->localifa_flags |= SCTP_BEING_DELETED; */
vrf->total_ifa_count--;
LIST_REMOVE(sctp_ifap, next_bucket);
sctp_remove_ifa_from_ifn(sctp_ifap);
}
#ifdef SCTP_DEBUG
else {
SCTPDBG(SCTP_DEBUG_PCB4, "Del Addr-ifn:%d Could not find address:",
ifn_index);
SCTPDBG_ADDR(SCTP_DEBUG_PCB1, addr);
}
#endif
out_now:
SCTP_IPI_ADDR_WUNLOCK();
if (sctp_ifap) {
struct sctp_laddr *wi;
wi = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
if (wi == NULL) {
/*
* Gak, what can we do? We have lost an address
* change can you say HOSED?
*/
SCTPDBG(SCTP_DEBUG_PCB4, "Lost an address change?\n");
/* Oops, must decrement the count */
sctp_free_ifa(sctp_ifap);
return;
}
SCTP_INCR_LADDR_COUNT();
memset(wi, 0, sizeof(*wi));
(void)SCTP_GETTIME_TIMEVAL(&wi->start_time);
wi->ifa = sctp_ifap;
wi->action = SCTP_DEL_IP_ADDRESS;
SCTP_WQ_ADDR_LOCK();
/*
* Should this really be a tailq? As it is we will process the
* newest first :-0
*/
LIST_INSERT_HEAD(&SCTP_BASE_INFO(addr_wq), wi, sctp_nxt_addr);
sctp_timer_start(SCTP_TIMER_TYPE_ADDR_WQ,
(struct sctp_inpcb *)NULL,
(struct sctp_tcb *)NULL,
(struct sctp_nets *)NULL);
SCTP_WQ_ADDR_UNLOCK();
}
return;
}
static int
sctp_does_stcb_own_this_addr(struct sctp_tcb *stcb, struct sockaddr *to)
{
int loopback_scope;
#if defined(INET)
int ipv4_local_scope, ipv4_addr_legal;
#endif
#if defined(INET6)
int local_scope, site_scope, ipv6_addr_legal;
#endif
#if defined(__Userspace__)
int conn_addr_legal;
#endif
struct sctp_vrf *vrf;
struct sctp_ifn *sctp_ifn;
struct sctp_ifa *sctp_ifa;
loopback_scope = stcb->asoc.scope.loopback_scope;
#if defined(INET)
ipv4_local_scope = stcb->asoc.scope.ipv4_local_scope;
ipv4_addr_legal = stcb->asoc.scope.ipv4_addr_legal;
#endif
#if defined(INET6)
local_scope = stcb->asoc.scope.local_scope;
site_scope = stcb->asoc.scope.site_scope;
ipv6_addr_legal = stcb->asoc.scope.ipv6_addr_legal;
#endif
#if defined(__Userspace__)
conn_addr_legal = stcb->asoc.scope.conn_addr_legal;
#endif
SCTP_IPI_ADDR_RLOCK();
vrf = sctp_find_vrf(stcb->asoc.vrf_id);
if (vrf == NULL) {
/* no vrf, no addresses */
SCTP_IPI_ADDR_RUNLOCK();
return (0);
}
if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
if ((loopback_scope == 0) &&
SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
continue;
}
LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
if (sctp_is_addr_restricted(stcb, sctp_ifa) &&
(!sctp_is_addr_pending(stcb, sctp_ifa))) {
/* We allow pending addresses, where we
* have sent an asconf-add to be considered
* valid.
*/
continue;
}
if (sctp_ifa->address.sa.sa_family != to->sa_family) {
continue;
}
switch (sctp_ifa->address.sa.sa_family) {
#ifdef INET
case AF_INET:
if (ipv4_addr_legal) {
struct sockaddr_in *sin, *rsin;
sin = &sctp_ifa->address.sin;
rsin = (struct sockaddr_in *)to;
if ((ipv4_local_scope == 0) &&
IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
continue;
}
#if defined(__FreeBSD__)
if (prison_check_ip4(stcb->sctp_ep->ip_inp.inp.inp_cred,
&sin->sin_addr) != 0) {
continue;
}
#endif
if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) {
SCTP_IPI_ADDR_RUNLOCK();
return (1);
}
}
break;
#endif
#ifdef INET6
case AF_INET6:
if (ipv6_addr_legal) {
struct sockaddr_in6 *sin6, *rsin6;
#if defined(SCTP_EMBEDDED_V6_SCOPE) && !defined(SCTP_KAME)
struct sockaddr_in6 lsa6;
#endif
sin6 = &sctp_ifa->address.sin6;
rsin6 = (struct sockaddr_in6 *)to;
#if defined(__FreeBSD__)
if (prison_check_ip6(stcb->sctp_ep->ip_inp.inp.inp_cred,
&sin6->sin6_addr) != 0) {
continue;
}
#endif
if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
if (local_scope == 0)
continue;
#if defined(SCTP_EMBEDDED_V6_SCOPE)
if (sin6->sin6_scope_id == 0) {
#ifdef SCTP_KAME
if (sa6_recoverscope(sin6) != 0)
continue;
#else
lsa6 = *sin6;
if (in6_recoverscope(&lsa6,
&lsa6.sin6_addr,
NULL))
continue;
sin6 = &lsa6;
#endif /* SCTP_KAME */
}
#endif /* SCTP_EMBEDDED_V6_SCOPE */
}
if ((site_scope == 0) &&
(IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))) {
continue;
}
if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) {
SCTP_IPI_ADDR_RUNLOCK();
return (1);
}
}
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
if (conn_addr_legal) {
struct sockaddr_conn *sconn, *rsconn;
sconn = &sctp_ifa->address.sconn;
rsconn = (struct sockaddr_conn *)to;
if (sconn->sconn_addr == rsconn->sconn_addr) {
SCTP_IPI_ADDR_RUNLOCK();
return (1);
}
}
break;
#endif
default:
/* TSNH */
break;
}
}
}
} else {
struct sctp_laddr *laddr;
LIST_FOREACH(laddr, &stcb->sctp_ep->sctp_addr_list, sctp_nxt_addr) {
if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
SCTPDBG(SCTP_DEBUG_PCB1, "ifa being deleted\n");
continue;
}
if (sctp_is_addr_restricted(stcb, laddr->ifa) &&
(!sctp_is_addr_pending(stcb, laddr->ifa))) {
/* We allow pending addresses, where we
* have sent an asconf-add to be considered
* valid.
*/
continue;
}
if (laddr->ifa->address.sa.sa_family != to->sa_family) {
continue;
}
switch (to->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin, *rsin;
sin = &laddr->ifa->address.sin;
rsin = (struct sockaddr_in *)to;
if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) {
SCTP_IPI_ADDR_RUNLOCK();
return (1);
}
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
struct sockaddr_in6 *sin6, *rsin6;
sin6 = &laddr->ifa->address.sin6;
rsin6 = (struct sockaddr_in6 *)to;
if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) {
SCTP_IPI_ADDR_RUNLOCK();
return (1);
}
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
{
struct sockaddr_conn *sconn, *rsconn;
sconn = &laddr->ifa->address.sconn;
rsconn = (struct sockaddr_conn *)to;
if (sconn->sconn_addr == rsconn->sconn_addr) {
SCTP_IPI_ADDR_RUNLOCK();
return (1);
}
break;
}
#endif
default:
/* TSNH */
break;
}
}
}
SCTP_IPI_ADDR_RUNLOCK();
return (0);
}
static struct sctp_tcb *
sctp_tcb_special_locate(struct sctp_inpcb **inp_p, struct sockaddr *from,
struct sockaddr *to, struct sctp_nets **netp, uint32_t vrf_id)
{
/**** ASSUMES THE CALLER holds the INP_INFO_RLOCK */
/*
* If we support the TCP model, then we must now dig through to see
* if we can find our endpoint in the list of tcp ep's.
*/
uint16_t lport, rport;
struct sctppcbhead *ephead;
struct sctp_inpcb *inp;
struct sctp_laddr *laddr;
struct sctp_tcb *stcb;
struct sctp_nets *net;
#ifdef SCTP_MVRF
int fnd, i;
#endif
if ((to == NULL) || (from == NULL)) {
return (NULL);
}
switch (to->sa_family) {
#ifdef INET
case AF_INET:
if (from->sa_family == AF_INET) {
lport = ((struct sockaddr_in *)to)->sin_port;
rport = ((struct sockaddr_in *)from)->sin_port;
} else {
return (NULL);
}
break;
#endif
#ifdef INET6
case AF_INET6:
if (from->sa_family == AF_INET6) {
lport = ((struct sockaddr_in6 *)to)->sin6_port;
rport = ((struct sockaddr_in6 *)from)->sin6_port;
} else {
return (NULL);
}
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
if (from->sa_family == AF_CONN) {
lport = ((struct sockaddr_conn *)to)->sconn_port;
rport = ((struct sockaddr_conn *)from)->sconn_port;
} else {
return (NULL);
}
break;
#endif
default:
return (NULL);
}
ephead = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR((lport | rport), SCTP_BASE_INFO(hashtcpmark))];
/*
* Ok now for each of the guys in this bucket we must look and see:
* - Does the remote port match. - Does there single association's
* addresses match this address (to). If so we update p_ep to point
* to this ep and return the tcb from it.
*/
LIST_FOREACH(inp, ephead, sctp_hash) {
SCTP_INP_RLOCK(inp);
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
SCTP_INP_RUNLOCK(inp);
continue;
}
if (lport != inp->sctp_lport) {
SCTP_INP_RUNLOCK(inp);
continue;
}
#if defined(__FreeBSD__)
switch (to->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin;
sin = (struct sockaddr_in *)to;
if (prison_check_ip4(inp->ip_inp.inp.inp_cred,
&sin->sin_addr) != 0) {
SCTP_INP_RUNLOCK(inp);
continue;
}
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)to;
if (prison_check_ip6(inp->ip_inp.inp.inp_cred,
&sin6->sin6_addr) != 0) {
SCTP_INP_RUNLOCK(inp);
continue;
}
break;
}
#endif
default:
SCTP_INP_RUNLOCK(inp);
continue;
}
#endif
#ifdef SCTP_MVRF
fnd = 0;
for (i = 0; i < inp->num_vrfs; i++) {
if (inp->m_vrf_ids[i] == vrf_id) {
fnd = 1;
break;
}
}
if (fnd == 0) {
SCTP_INP_RUNLOCK(inp);
continue;
}
#else
if (inp->def_vrf_id != vrf_id) {
SCTP_INP_RUNLOCK(inp);
continue;
}
#endif
/* check to see if the ep has one of the addresses */
if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
/* We are NOT bound all, so look further */
int match = 0;
LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
if (laddr->ifa == NULL) {
SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n", __func__);
continue;
}
if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
SCTPDBG(SCTP_DEBUG_PCB1, "ifa being deleted\n");
continue;
}
if (laddr->ifa->address.sa.sa_family ==
to->sa_family) {
/* see if it matches */
#ifdef INET
if (from->sa_family == AF_INET) {
struct sockaddr_in *intf_addr, *sin;
intf_addr = &laddr->ifa->address.sin;
sin = (struct sockaddr_in *)to;
if (sin->sin_addr.s_addr ==
intf_addr->sin_addr.s_addr) {
match = 1;
break;
}
}
#endif
#ifdef INET6
if (from->sa_family == AF_INET6) {
struct sockaddr_in6 *intf_addr6;
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)
to;
intf_addr6 = &laddr->ifa->address.sin6;
if (SCTP6_ARE_ADDR_EQUAL(sin6,
intf_addr6)) {
match = 1;
break;
}
}
#endif
#if defined(__Userspace__)
if (from->sa_family == AF_CONN) {
struct sockaddr_conn *intf_addr, *sconn;
intf_addr = &laddr->ifa->address.sconn;
sconn = (struct sockaddr_conn *)to;
if (sconn->sconn_addr ==
intf_addr->sconn_addr) {
match = 1;
break;
}
}
#endif
}
}
if (match == 0) {
/* This endpoint does not have this address */
SCTP_INP_RUNLOCK(inp);
continue;
}
}
/*
* Ok if we hit here the ep has the address, does it hold
* the tcb?
*/
/* XXX: Why don't we TAILQ_FOREACH through sctp_asoc_list? */
stcb = LIST_FIRST(&inp->sctp_asoc_list);
if (stcb == NULL) {
SCTP_INP_RUNLOCK(inp);
continue;
}
SCTP_TCB_LOCK(stcb);
if (!sctp_does_stcb_own_this_addr(stcb, to)) {
SCTP_TCB_UNLOCK(stcb);
SCTP_INP_RUNLOCK(inp);
continue;
}
if (stcb->rport != rport) {
/* remote port does not match. */
SCTP_TCB_UNLOCK(stcb);
SCTP_INP_RUNLOCK(inp);
continue;
}
if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
SCTP_TCB_UNLOCK(stcb);
SCTP_INP_RUNLOCK(inp);
continue;
}
if (!sctp_does_stcb_own_this_addr(stcb, to)) {
SCTP_TCB_UNLOCK(stcb);
SCTP_INP_RUNLOCK(inp);
continue;
}
/* Does this TCB have a matching address? */
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
if (net->ro._l_addr.sa.sa_family != from->sa_family) {
/* not the same family, can't be a match */
continue;
}
switch (from->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin, *rsin;
sin = (struct sockaddr_in *)&net->ro._l_addr;
rsin = (struct sockaddr_in *)from;
if (sin->sin_addr.s_addr ==
rsin->sin_addr.s_addr) {
/* found it */
if (netp != NULL) {
*netp = net;
}
/* Update the endpoint pointer */
*inp_p = inp;
SCTP_INP_RUNLOCK(inp);
return (stcb);
}
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
struct sockaddr_in6 *sin6, *rsin6;
sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
rsin6 = (struct sockaddr_in6 *)from;
if (SCTP6_ARE_ADDR_EQUAL(sin6,
rsin6)) {
/* found it */
if (netp != NULL) {
*netp = net;
}
/* Update the endpoint pointer */
*inp_p = inp;
SCTP_INP_RUNLOCK(inp);
return (stcb);
}
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
{
struct sockaddr_conn *sconn, *rsconn;
sconn = (struct sockaddr_conn *)&net->ro._l_addr;
rsconn = (struct sockaddr_conn *)from;
if (sconn->sconn_addr == rsconn->sconn_addr) {
/* found it */
if (netp != NULL) {
*netp = net;
}
/* Update the endpoint pointer */
*inp_p = inp;
SCTP_INP_RUNLOCK(inp);
return (stcb);
}
break;
}
#endif
default:
/* TSNH */
break;
}
}
SCTP_TCB_UNLOCK(stcb);
SCTP_INP_RUNLOCK(inp);
}
return (NULL);
}
/*
* rules for use
*
* 1) If I return a NULL you must decrement any INP ref cnt. 2) If I find an
* stcb, both will be locked (locked_tcb and stcb) but decrement will be done
* (if locked == NULL). 3) Decrement happens on return ONLY if locked ==
* NULL.
*/
struct sctp_tcb *
sctp_findassociation_ep_addr(struct sctp_inpcb **inp_p, struct sockaddr *remote,
struct sctp_nets **netp, struct sockaddr *local, struct sctp_tcb *locked_tcb)
{
struct sctpasochead *head;
struct sctp_inpcb *inp;
struct sctp_tcb *stcb = NULL;
struct sctp_nets *net;
uint16_t rport;
inp = *inp_p;
switch (remote->sa_family) {
#ifdef INET
case AF_INET:
rport = (((struct sockaddr_in *)remote)->sin_port);
break;
#endif
#ifdef INET6
case AF_INET6:
rport = (((struct sockaddr_in6 *)remote)->sin6_port);
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
rport = (((struct sockaddr_conn *)remote)->sconn_port);
break;
#endif
default:
return (NULL);
}
if (locked_tcb) {
/*
* UN-lock so we can do proper locking here this occurs when
* called from load_addresses_from_init.
*/
atomic_add_int(&locked_tcb->asoc.refcnt, 1);
SCTP_TCB_UNLOCK(locked_tcb);
}
SCTP_INP_INFO_RLOCK();
if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
/*-
* Now either this guy is our listener or it's the
* connector. If it is the one that issued the connect, then
* it's only chance is to be the first TCB in the list. If
* it is the acceptor, then do the special_lookup to hash
* and find the real inp.
*/
if ((inp->sctp_socket) && SCTP_IS_LISTENING(inp)) {
/* to is peer addr, from is my addr */
#ifndef SCTP_MVRF
stcb = sctp_tcb_special_locate(inp_p, remote, local,
netp, inp->def_vrf_id);
if ((stcb != NULL) && (locked_tcb == NULL)) {
/* we have a locked tcb, lower refcount */
SCTP_INP_DECR_REF(inp);
}
if ((locked_tcb != NULL) && (locked_tcb != stcb)) {
SCTP_INP_RLOCK(locked_tcb->sctp_ep);
SCTP_TCB_LOCK(locked_tcb);
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
SCTP_INP_RUNLOCK(locked_tcb->sctp_ep);
}
#else
/*-
* MVRF is tricky, we must look in every VRF
* the endpoint has.
*/
int i;
for (i = 0; i < inp->num_vrfs; i++) {
stcb = sctp_tcb_special_locate(inp_p, remote, local,
netp, inp->m_vrf_ids[i]);
if ((stcb != NULL) && (locked_tcb == NULL)) {
/* we have a locked tcb, lower refcount */
SCTP_INP_DECR_REF(inp);
break;
}
if ((locked_tcb != NULL) && (locked_tcb != stcb)) {
SCTP_INP_RLOCK(locked_tcb->sctp_ep);
SCTP_TCB_LOCK(locked_tcb);
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
SCTP_INP_RUNLOCK(locked_tcb->sctp_ep);
break;
}
}
#endif
SCTP_INP_INFO_RUNLOCK();
return (stcb);
} else {
SCTP_INP_WLOCK(inp);
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
goto null_return;
}
stcb = LIST_FIRST(&inp->sctp_asoc_list);
if (stcb == NULL) {
goto null_return;
}
SCTP_TCB_LOCK(stcb);
if (stcb->rport != rport) {
/* remote port does not match. */
SCTP_TCB_UNLOCK(stcb);
goto null_return;
}
if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
SCTP_TCB_UNLOCK(stcb);
goto null_return;
}
if (local && !sctp_does_stcb_own_this_addr(stcb, local)) {
SCTP_TCB_UNLOCK(stcb);
goto null_return;
}
/* now look at the list of remote addresses */
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
#ifdef INVARIANTS
if (net == (TAILQ_NEXT(net, sctp_next))) {
panic("Corrupt net list");
}
#endif
if (net->ro._l_addr.sa.sa_family !=
remote->sa_family) {
/* not the same family */
continue;
}
switch (remote->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin, *rsin;
sin = (struct sockaddr_in *)
&net->ro._l_addr;
rsin = (struct sockaddr_in *)remote;
if (sin->sin_addr.s_addr ==
rsin->sin_addr.s_addr) {
/* found it */
if (netp != NULL) {
*netp = net;
}
if (locked_tcb == NULL) {
SCTP_INP_DECR_REF(inp);
} else if (locked_tcb != stcb) {
SCTP_TCB_LOCK(locked_tcb);
}
if (locked_tcb) {
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
}
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
struct sockaddr_in6 *sin6, *rsin6;
sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
rsin6 = (struct sockaddr_in6 *)remote;
if (SCTP6_ARE_ADDR_EQUAL(sin6,
rsin6)) {
/* found it */
if (netp != NULL) {
*netp = net;
}
if (locked_tcb == NULL) {
SCTP_INP_DECR_REF(inp);
} else if (locked_tcb != stcb) {
SCTP_TCB_LOCK(locked_tcb);
}
if (locked_tcb) {
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
}
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
{
struct sockaddr_conn *sconn, *rsconn;
sconn = (struct sockaddr_conn *)&net->ro._l_addr;
rsconn = (struct sockaddr_conn *)remote;
if (sconn->sconn_addr == rsconn->sconn_addr) {
/* found it */
if (netp != NULL) {
*netp = net;
}
if (locked_tcb == NULL) {
SCTP_INP_DECR_REF(inp);
} else if (locked_tcb != stcb) {
SCTP_TCB_LOCK(locked_tcb);
}
if (locked_tcb) {
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
}
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
break;
}
#endif
default:
/* TSNH */
break;
}
}
SCTP_TCB_UNLOCK(stcb);
}
} else {
SCTP_INP_WLOCK(inp);
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
goto null_return;
}
head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(rport,
inp->sctp_hashmark)];
LIST_FOREACH(stcb, head, sctp_tcbhash) {
if (stcb->rport != rport) {
/* remote port does not match */
continue;
}
SCTP_TCB_LOCK(stcb);
if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
SCTP_TCB_UNLOCK(stcb);
continue;
}
if (local && !sctp_does_stcb_own_this_addr(stcb, local)) {
SCTP_TCB_UNLOCK(stcb);
continue;
}
/* now look at the list of remote addresses */
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
#ifdef INVARIANTS
if (net == (TAILQ_NEXT(net, sctp_next))) {
panic("Corrupt net list");
}
#endif
if (net->ro._l_addr.sa.sa_family !=
remote->sa_family) {
/* not the same family */
continue;
}
switch (remote->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin, *rsin;
sin = (struct sockaddr_in *)
&net->ro._l_addr;
rsin = (struct sockaddr_in *)remote;
if (sin->sin_addr.s_addr ==
rsin->sin_addr.s_addr) {
/* found it */
if (netp != NULL) {
*netp = net;
}
if (locked_tcb == NULL) {
SCTP_INP_DECR_REF(inp);
} else if (locked_tcb != stcb) {
SCTP_TCB_LOCK(locked_tcb);
}
if (locked_tcb) {
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
}
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
struct sockaddr_in6 *sin6, *rsin6;
sin6 = (struct sockaddr_in6 *)
&net->ro._l_addr;
rsin6 = (struct sockaddr_in6 *)remote;
if (SCTP6_ARE_ADDR_EQUAL(sin6,
rsin6)) {
/* found it */
if (netp != NULL) {
*netp = net;
}
if (locked_tcb == NULL) {
SCTP_INP_DECR_REF(inp);
} else if (locked_tcb != stcb) {
SCTP_TCB_LOCK(locked_tcb);
}
if (locked_tcb) {
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
}
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
{
struct sockaddr_conn *sconn, *rsconn;
sconn = (struct sockaddr_conn *)&net->ro._l_addr;
rsconn = (struct sockaddr_conn *)remote;
if (sconn->sconn_addr == rsconn->sconn_addr) {
/* found it */
if (netp != NULL) {
*netp = net;
}
if (locked_tcb == NULL) {
SCTP_INP_DECR_REF(inp);
} else if (locked_tcb != stcb) {
SCTP_TCB_LOCK(locked_tcb);
}
if (locked_tcb) {
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
}
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
break;
}
#endif
default:
/* TSNH */
break;
}
}
SCTP_TCB_UNLOCK(stcb);
}
}
null_return:
/* clean up for returning null */
if (locked_tcb) {
SCTP_TCB_LOCK(locked_tcb);
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
}
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_RUNLOCK();
/* not found */
return (NULL);
}
/*
* Find an association for a specific endpoint using the association id given
* out in the COMM_UP notification
*/
struct sctp_tcb *
sctp_findasoc_ep_asocid_locked(struct sctp_inpcb *inp, sctp_assoc_t asoc_id, int want_lock)
{
/*
* Use my the assoc_id to find a endpoint
*/
struct sctpasochead *head;
struct sctp_tcb *stcb;
uint32_t id;
if (inp == NULL) {
SCTP_PRINTF("TSNH ep_associd\n");
return (NULL);
}
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
SCTP_PRINTF("TSNH ep_associd0\n");
return (NULL);
}
id = (uint32_t)asoc_id;
head = &inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(id, inp->hashasocidmark)];
if (head == NULL) {
/* invalid id TSNH */
SCTP_PRINTF("TSNH ep_associd1\n");
return (NULL);
}
LIST_FOREACH(stcb, head, sctp_tcbasocidhash) {
if (stcb->asoc.assoc_id == id) {
if (inp != stcb->sctp_ep) {
/*
* some other guy has the same id active (id
* collision ??).
*/
SCTP_PRINTF("TSNH ep_associd2\n");
continue;
}
if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
continue;
}
if (want_lock) {
SCTP_TCB_LOCK(stcb);
}
return (stcb);
}
}
return (NULL);
}
struct sctp_tcb *
sctp_findassociation_ep_asocid(struct sctp_inpcb *inp, sctp_assoc_t asoc_id, int want_lock)
{
struct sctp_tcb *stcb;
SCTP_INP_RLOCK(inp);
stcb = sctp_findasoc_ep_asocid_locked(inp, asoc_id, want_lock);
SCTP_INP_RUNLOCK(inp);
return (stcb);
}
/*
* Endpoint probe expects that the INP_INFO is locked.
*/
static struct sctp_inpcb *
sctp_endpoint_probe(struct sockaddr *nam, struct sctppcbhead *head,
uint16_t lport, uint32_t vrf_id)
{
struct sctp_inpcb *inp;
struct sctp_laddr *laddr;
#ifdef INET
struct sockaddr_in *sin;
#endif
#ifdef INET6
struct sockaddr_in6 *sin6;
struct sockaddr_in6 *intf_addr6;
#endif
#if defined(__Userspace__)
struct sockaddr_conn *sconn;
#endif
#ifdef SCTP_MVRF
int i;
#endif
int fnd;
#ifdef INET
sin = NULL;
#endif
#ifdef INET6
sin6 = NULL;
#endif
#if defined(__Userspace__)
sconn = NULL;
#endif
switch (nam->sa_family) {
#ifdef INET
case AF_INET:
sin = (struct sockaddr_in *)nam;
break;
#endif
#ifdef INET6
case AF_INET6:
sin6 = (struct sockaddr_in6 *)nam;
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
sconn = (struct sockaddr_conn *)nam;
break;
#endif
default:
/* unsupported family */
return (NULL);
}
if (head == NULL)
return (NULL);
LIST_FOREACH(inp, head, sctp_hash) {
SCTP_INP_RLOCK(inp);
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
SCTP_INP_RUNLOCK(inp);
continue;
}
if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) &&
(inp->sctp_lport == lport)) {
/* got it */
switch (nam->sa_family) {
#ifdef INET
case AF_INET:
if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
SCTP_IPV6_V6ONLY(inp)) {
/* IPv4 on a IPv6 socket with ONLY IPv6 set */
SCTP_INP_RUNLOCK(inp);
continue;
}
#if defined(__FreeBSD__)
if (prison_check_ip4(inp->ip_inp.inp.inp_cred,
&sin->sin_addr) != 0) {
SCTP_INP_RUNLOCK(inp);
continue;
}
#endif
break;
#endif
#ifdef INET6
case AF_INET6:
/* A V6 address and the endpoint is NOT bound V6 */
if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) {
SCTP_INP_RUNLOCK(inp);
continue;
}
#if defined(__FreeBSD__)
if (prison_check_ip6(inp->ip_inp.inp.inp_cred,
&sin6->sin6_addr) != 0) {
SCTP_INP_RUNLOCK(inp);
continue;
}
#endif
break;
#endif
default:
break;
}
/* does a VRF id match? */
fnd = 0;
#ifdef SCTP_MVRF
for (i = 0; i < inp->num_vrfs; i++) {
if (inp->m_vrf_ids[i] == vrf_id) {
fnd = 1;
break;
}
}
#else
if (inp->def_vrf_id == vrf_id)
fnd = 1;
#endif
SCTP_INP_RUNLOCK(inp);
if (!fnd)
continue;
return (inp);
}
SCTP_INP_RUNLOCK(inp);
}
switch (nam->sa_family) {
#ifdef INET
case AF_INET:
if (sin->sin_addr.s_addr == INADDR_ANY) {
/* Can't hunt for one that has no address specified */
return (NULL);
}
break;
#endif
#ifdef INET6
case AF_INET6:
if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
/* Can't hunt for one that has no address specified */
return (NULL);
}
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
if (sconn->sconn_addr == NULL) {
return (NULL);
}
break;
#endif
default:
break;
}
/*
* ok, not bound to all so see if we can find a EP bound to this
* address.
*/
LIST_FOREACH(inp, head, sctp_hash) {
SCTP_INP_RLOCK(inp);
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
SCTP_INP_RUNLOCK(inp);
continue;
}
if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL)) {
SCTP_INP_RUNLOCK(inp);
continue;
}
/*
* Ok this could be a likely candidate, look at all of its
* addresses
*/
if (inp->sctp_lport != lport) {
SCTP_INP_RUNLOCK(inp);
continue;
}
/* does a VRF id match? */
fnd = 0;
#ifdef SCTP_MVRF
for (i = 0; i < inp->num_vrfs; i++) {
if (inp->m_vrf_ids[i] == vrf_id) {
fnd = 1;
break;
}
}
#else
if (inp->def_vrf_id == vrf_id)
fnd = 1;
#endif
if (!fnd) {
SCTP_INP_RUNLOCK(inp);
continue;
}
LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
if (laddr->ifa == NULL) {
SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n",
__func__);
continue;
}
SCTPDBG(SCTP_DEBUG_PCB1, "Ok laddr->ifa:%p is possible, ",
(void *)laddr->ifa);
if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
SCTPDBG(SCTP_DEBUG_PCB1, "Huh IFA being deleted\n");
continue;
}
if (laddr->ifa->address.sa.sa_family == nam->sa_family) {
/* possible, see if it matches */
switch (nam->sa_family) {
#ifdef INET
case AF_INET:
#if defined(__APPLE__)
if (sin == NULL) {
/* TSNH */
break;
}
#endif
if (sin->sin_addr.s_addr ==
laddr->ifa->address.sin.sin_addr.s_addr) {
SCTP_INP_RUNLOCK(inp);
return (inp);
}
break;
#endif
#ifdef INET6
case AF_INET6:
intf_addr6 = &laddr->ifa->address.sin6;
if (SCTP6_ARE_ADDR_EQUAL(sin6,
intf_addr6)) {
SCTP_INP_RUNLOCK(inp);
return (inp);
}
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
if (sconn->sconn_addr == laddr->ifa->address.sconn.sconn_addr) {
SCTP_INP_RUNLOCK(inp);
return (inp);
}
break;
#endif
}
}
}
SCTP_INP_RUNLOCK(inp);
}
return (NULL);
}
static struct sctp_inpcb *
sctp_isport_inuse(struct sctp_inpcb *inp, uint16_t lport, uint32_t vrf_id)
{
struct sctppcbhead *head;
struct sctp_inpcb *t_inp;
#ifdef SCTP_MVRF
int i;
#endif
int fnd;
head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport,
SCTP_BASE_INFO(hashmark))];
LIST_FOREACH(t_inp, head, sctp_hash) {
if (t_inp->sctp_lport != lport) {
continue;
}
/* is it in the VRF in question */
fnd = 0;
#ifdef SCTP_MVRF
for (i = 0; i < inp->num_vrfs; i++) {
if (t_inp->m_vrf_ids[i] == vrf_id) {
fnd = 1;
break;
}
}
#else
if (t_inp->def_vrf_id == vrf_id)
fnd = 1;
#endif
if (!fnd)
continue;
/* This one is in use. */
/* check the v6/v4 binding issue */
if ((t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
SCTP_IPV6_V6ONLY(t_inp)) {
if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
/* collision in V6 space */
return (t_inp);
} else {
/* inp is BOUND_V4 no conflict */
continue;
}
} else if (t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
/* t_inp is bound v4 and v6, conflict always */
return (t_inp);
} else {
/* t_inp is bound only V4 */
if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
SCTP_IPV6_V6ONLY(inp)) {
/* no conflict */
continue;
}
/* else fall through to conflict */
}
return (t_inp);
}
return (NULL);
}
int
sctp_swap_inpcb_for_listen(struct sctp_inpcb *inp)
{
/* For 1-2-1 with port reuse */
struct sctppcbhead *head;
struct sctp_inpcb *tinp, *ninp;
if (sctp_is_feature_off(inp, SCTP_PCB_FLAGS_PORTREUSE)) {
/* only works with port reuse on */
return (-1);
}
if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) == 0) {
return (0);
}
SCTP_INP_RUNLOCK(inp);
SCTP_INP_INFO_WLOCK();
head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(inp->sctp_lport,
SCTP_BASE_INFO(hashmark))];
/* Kick out all non-listeners to the TCP hash */
LIST_FOREACH_SAFE(tinp, head, sctp_hash, ninp) {
if (tinp->sctp_lport != inp->sctp_lport) {
continue;
}
if (tinp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
continue;
}
if (tinp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
continue;
}
if (SCTP_IS_LISTENING(tinp)) {
continue;
}
SCTP_INP_WLOCK(tinp);
LIST_REMOVE(tinp, sctp_hash);
head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR(tinp->sctp_lport, SCTP_BASE_INFO(hashtcpmark))];
tinp->sctp_flags |= SCTP_PCB_FLAGS_IN_TCPPOOL;
LIST_INSERT_HEAD(head, tinp, sctp_hash);
SCTP_INP_WUNLOCK(tinp);
}
SCTP_INP_WLOCK(inp);
/* Pull from where he was */
LIST_REMOVE(inp, sctp_hash);
inp->sctp_flags &= ~SCTP_PCB_FLAGS_IN_TCPPOOL;
head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(inp->sctp_lport, SCTP_BASE_INFO(hashmark))];
LIST_INSERT_HEAD(head, inp, sctp_hash);
SCTP_INP_WUNLOCK(inp);
SCTP_INP_RLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
return (0);
}
struct sctp_inpcb *
sctp_pcb_findep(struct sockaddr *nam, int find_tcp_pool, int have_lock,
uint32_t vrf_id)
{
/*
* First we check the hash table to see if someone has this port
* bound with just the port.
*/
struct sctp_inpcb *inp;
struct sctppcbhead *head;
int lport;
unsigned int i;
#ifdef INET
struct sockaddr_in *sin;
#endif
#ifdef INET6
struct sockaddr_in6 *sin6;
#endif
#if defined(__Userspace__)
struct sockaddr_conn *sconn;
#endif
switch (nam->sa_family) {
#ifdef INET
case AF_INET:
sin = (struct sockaddr_in *)nam;
lport = sin->sin_port;
break;
#endif
#ifdef INET6
case AF_INET6:
sin6 = (struct sockaddr_in6 *)nam;
lport = sin6->sin6_port;
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
sconn = (struct sockaddr_conn *)nam;
lport = sconn->sconn_port;
break;
#endif
default:
return (NULL);
}
/*
* I could cheat here and just cast to one of the types but we will
* do it right. It also provides the check against an Unsupported
* type too.
*/
/* Find the head of the ALLADDR chain */
if (have_lock == 0) {
SCTP_INP_INFO_RLOCK();
}
head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport,
SCTP_BASE_INFO(hashmark))];
inp = sctp_endpoint_probe(nam, head, lport, vrf_id);
/*
* If the TCP model exists it could be that the main listening
* endpoint is gone but there still exists a connected socket for this
* guy. If so we can return the first one that we find. This may NOT
* be the correct one so the caller should be wary on the returned INP.
* Currently the only caller that sets find_tcp_pool is in bindx where
* we are verifying that a user CAN bind the address. He either
* has bound it already, or someone else has, or its open to bind,
* so this is good enough.
*/
if (inp == NULL && find_tcp_pool) {
for (i = 0; i < SCTP_BASE_INFO(hashtcpmark) + 1; i++) {
head = &SCTP_BASE_INFO(sctp_tcpephash)[i];
inp = sctp_endpoint_probe(nam, head, lport, vrf_id);
if (inp) {
break;
}
}
}
if (inp) {
SCTP_INP_INCR_REF(inp);
}
if (have_lock == 0) {
SCTP_INP_INFO_RUNLOCK();
}
return (inp);
}
/*
* Find an association for an endpoint with the pointer to whom you want to
* send to and the endpoint pointer. The address can be IPv4 or IPv6. We may
* need to change the *to to some other struct like a mbuf...
*/
struct sctp_tcb *
sctp_findassociation_addr_sa(struct sockaddr *from, struct sockaddr *to,
struct sctp_inpcb **inp_p, struct sctp_nets **netp, int find_tcp_pool,
uint32_t vrf_id)
{
struct sctp_inpcb *inp = NULL;
struct sctp_tcb *stcb;
SCTP_INP_INFO_RLOCK();
if (find_tcp_pool) {
if (inp_p != NULL) {
stcb = sctp_tcb_special_locate(inp_p, from, to, netp,
vrf_id);
} else {
stcb = sctp_tcb_special_locate(&inp, from, to, netp,
vrf_id);
}
if (stcb != NULL) {
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
}
inp = sctp_pcb_findep(to, 0, 1, vrf_id);
if (inp_p != NULL) {
*inp_p = inp;
}
SCTP_INP_INFO_RUNLOCK();
if (inp == NULL) {
return (NULL);
}
/*
* ok, we have an endpoint, now lets find the assoc for it (if any)
* we now place the source address or from in the to of the find
* endpoint call. Since in reality this chain is used from the
* inbound packet side.
*/
if (inp_p != NULL) {
stcb = sctp_findassociation_ep_addr(inp_p, from, netp, to,
NULL);
} else {
stcb = sctp_findassociation_ep_addr(&inp, from, netp, to,
NULL);
}
return (stcb);
}
/*
* This routine will grub through the mbuf that is a INIT or INIT-ACK and
* find all addresses that the sender has specified in any address list. Each
* address will be used to lookup the TCB and see if one exits.
*/
static struct sctp_tcb *
sctp_findassociation_special_addr(struct mbuf *m, int offset,
struct sctphdr *sh, struct sctp_inpcb **inp_p, struct sctp_nets **netp,
struct sockaddr *dst)
{
struct sctp_paramhdr *phdr, param_buf;
#if defined(INET) || defined(INET6)
struct sctp_tcb *stcb;
uint16_t ptype;
#endif
uint16_t plen;
#ifdef INET
struct sockaddr_in sin4;
#endif
#ifdef INET6
struct sockaddr_in6 sin6;
#endif
#ifdef INET
memset(&sin4, 0, sizeof(sin4));
#ifdef HAVE_SIN_LEN
sin4.sin_len = sizeof(sin4);
#endif
sin4.sin_family = AF_INET;
sin4.sin_port = sh->src_port;
#endif
#ifdef INET6
memset(&sin6, 0, sizeof(sin6));
#ifdef HAVE_SIN6_LEN
sin6.sin6_len = sizeof(sin6);
#endif
sin6.sin6_family = AF_INET6;
sin6.sin6_port = sh->src_port;
#endif
offset += sizeof(struct sctp_init_chunk);
phdr = sctp_get_next_param(m, offset, ¶m_buf, sizeof(param_buf));
while (phdr != NULL) {
/* now we must see if we want the parameter */
#if defined(INET) || defined(INET6)
ptype = ntohs(phdr->param_type);
#endif
plen = ntohs(phdr->param_length);
if (plen == 0) {
break;
}
#ifdef INET
if (ptype == SCTP_IPV4_ADDRESS &&
plen == sizeof(struct sctp_ipv4addr_param)) {
/* Get the rest of the address */
struct sctp_ipv4addr_param ip4_param, *p4;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&ip4_param, sizeof(ip4_param));
if (phdr == NULL) {
return (NULL);
}
p4 = (struct sctp_ipv4addr_param *)phdr;
memcpy(&sin4.sin_addr, &p4->addr, sizeof(p4->addr));
/* look it up */
stcb = sctp_findassociation_ep_addr(inp_p,
(struct sockaddr *)&sin4, netp, dst, NULL);
if (stcb != NULL) {
return (stcb);
}
}
#endif
#ifdef INET6
if (ptype == SCTP_IPV6_ADDRESS &&
plen == sizeof(struct sctp_ipv6addr_param)) {
/* Get the rest of the address */
struct sctp_ipv6addr_param ip6_param, *p6;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&ip6_param, sizeof(ip6_param));
if (phdr == NULL) {
return (NULL);
}
p6 = (struct sctp_ipv6addr_param *)phdr;
memcpy(&sin6.sin6_addr, &p6->addr, sizeof(p6->addr));
/* look it up */
stcb = sctp_findassociation_ep_addr(inp_p,
(struct sockaddr *)&sin6, netp, dst, NULL);
if (stcb != NULL) {
return (stcb);
}
}
#endif
offset += SCTP_SIZE32(plen);
phdr = sctp_get_next_param(m, offset, ¶m_buf,
sizeof(param_buf));
}
return (NULL);
}
static struct sctp_tcb *
sctp_findassoc_by_vtag(struct sockaddr *from, struct sockaddr *to, uint32_t vtag,
struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint16_t rport,
uint16_t lport, int skip_src_check, uint32_t vrf_id, uint32_t remote_tag)
{
/*
* Use my vtag to hash. If we find it we then verify the source addr
* is in the assoc. If all goes well we save a bit on rec of a
* packet.
*/
struct sctpasochead *head;
struct sctp_nets *net;
struct sctp_tcb *stcb;
#ifdef SCTP_MVRF
unsigned int i;
#endif
SCTP_INP_INFO_RLOCK();
head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(vtag,
SCTP_BASE_INFO(hashasocmark))];
LIST_FOREACH(stcb, head, sctp_asocs) {
SCTP_INP_RLOCK(stcb->sctp_ep);
if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
SCTP_INP_RUNLOCK(stcb->sctp_ep);
continue;
}
#ifdef SCTP_MVRF
for (i = 0; i < stcb->sctp_ep->num_vrfs; i++) {
if (stcb->sctp_ep->m_vrf_ids[i] == vrf_id) {
break;
}
}
if (i == stcb->sctp_ep->num_vrfs) {
SCTP_INP_RUNLOCK(inp);
continue;
}
#else
if (stcb->sctp_ep->def_vrf_id != vrf_id) {
SCTP_INP_RUNLOCK(stcb->sctp_ep);
continue;
}
#endif
SCTP_TCB_LOCK(stcb);
SCTP_INP_RUNLOCK(stcb->sctp_ep);
if (stcb->asoc.my_vtag == vtag) {
/* candidate */
if (stcb->rport != rport) {
SCTP_TCB_UNLOCK(stcb);
continue;
}
if (stcb->sctp_ep->sctp_lport != lport) {
SCTP_TCB_UNLOCK(stcb);
continue;
}
if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
SCTP_TCB_UNLOCK(stcb);
continue;
}
/* RRS:Need toaddr check here */
if (sctp_does_stcb_own_this_addr(stcb, to) == 0) {
/* Endpoint does not own this address */
SCTP_TCB_UNLOCK(stcb);
continue;
}
if (remote_tag) {
/* If we have both vtags that's all we match on */
if (stcb->asoc.peer_vtag == remote_tag) {
/* If both tags match we consider it conclusive
* and check NO source/destination addresses
*/
goto conclusive;
}
}
if (skip_src_check) {
conclusive:
if (from) {
*netp = sctp_findnet(stcb, from);
} else {
*netp = NULL; /* unknown */
}
if (inp_p)
*inp_p = stcb->sctp_ep;
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
net = sctp_findnet(stcb, from);
if (net) {
/* yep its him. */
*netp = net;
SCTP_STAT_INCR(sctps_vtagexpress);
*inp_p = stcb->sctp_ep;
SCTP_INP_INFO_RUNLOCK();
return (stcb);
} else {
/*
* not him, this should only happen in rare
* cases so I peg it.
*/
SCTP_STAT_INCR(sctps_vtagbogus);
}
}
SCTP_TCB_UNLOCK(stcb);
}
SCTP_INP_INFO_RUNLOCK();
return (NULL);
}
/*
* Find an association with the pointer to the inbound IP packet. This can be
* a IPv4 or IPv6 packet.
*/
struct sctp_tcb *
sctp_findassociation_addr(struct mbuf *m, int offset,
struct sockaddr *src, struct sockaddr *dst,
struct sctphdr *sh, struct sctp_chunkhdr *ch,
struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint32_t vrf_id)
{
struct sctp_tcb *stcb;
struct sctp_inpcb *inp;
if (sh->v_tag) {
/* we only go down this path if vtag is non-zero */
stcb = sctp_findassoc_by_vtag(src, dst, ntohl(sh->v_tag),
inp_p, netp, sh->src_port, sh->dest_port, 0, vrf_id, 0);
if (stcb) {
return (stcb);
}
}
if (inp_p) {
stcb = sctp_findassociation_addr_sa(src, dst, inp_p, netp,
1, vrf_id);
inp = *inp_p;
} else {
stcb = sctp_findassociation_addr_sa(src, dst, &inp, netp,
1, vrf_id);
}
SCTPDBG(SCTP_DEBUG_PCB1, "stcb:%p inp:%p\n", (void *)stcb, (void *)inp);
if (stcb == NULL && inp) {
/* Found a EP but not this address */
if ((ch->chunk_type == SCTP_INITIATION) ||
(ch->chunk_type == SCTP_INITIATION_ACK)) {
/*-
* special hook, we do NOT return linp or an
* association that is linked to an existing
* association that is under the TCP pool (i.e. no
* listener exists). The endpoint finding routine
* will always find a listener before examining the
* TCP pool.
*/
if (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) {
if (inp_p) {
*inp_p = NULL;
}
return (NULL);
}
stcb = sctp_findassociation_special_addr(m,
offset, sh, &inp, netp, dst);
if (inp_p != NULL) {
*inp_p = inp;
}
}
}
SCTPDBG(SCTP_DEBUG_PCB1, "stcb is %p\n", (void *)stcb);
return (stcb);
}
/*
* lookup an association by an ASCONF lookup address.
* if the lookup address is 0.0.0.0 or ::0, use the vtag to do the lookup
*/
struct sctp_tcb *
sctp_findassociation_ep_asconf(struct mbuf *m, int offset,
struct sockaddr *dst, struct sctphdr *sh,
struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint32_t vrf_id)
{
struct sctp_tcb *stcb;
union sctp_sockstore remote_store;
struct sctp_paramhdr param_buf, *phdr;
int ptype;
int zero_address = 0;
#ifdef INET
struct sockaddr_in *sin;
#endif
#ifdef INET6
struct sockaddr_in6 *sin6;
#endif
memset(&remote_store, 0, sizeof(remote_store));
phdr = sctp_get_next_param(m, offset + sizeof(struct sctp_asconf_chunk),
¶m_buf, sizeof(struct sctp_paramhdr));
if (phdr == NULL) {
SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf lookup addr\n",
__func__);
return NULL;
}
ptype = (int)((uint32_t) ntohs(phdr->param_type));
/* get the correlation address */
switch (ptype) {
#ifdef INET6
case SCTP_IPV6_ADDRESS:
{
/* ipv6 address param */
struct sctp_ipv6addr_param *p6, p6_buf;
if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv6addr_param)) {
return NULL;
}
p6 = (struct sctp_ipv6addr_param *)sctp_get_next_param(m,
offset + sizeof(struct sctp_asconf_chunk),
&p6_buf.ph, sizeof(p6_buf));
if (p6 == NULL) {
SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf v6 lookup addr\n",
__func__);
return (NULL);
}
sin6 = &remote_store.sin6;
sin6->sin6_family = AF_INET6;
#ifdef HAVE_SIN6_LEN
sin6->sin6_len = sizeof(*sin6);
#endif
sin6->sin6_port = sh->src_port;
memcpy(&sin6->sin6_addr, &p6->addr, sizeof(struct in6_addr));
if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
zero_address = 1;
break;
}
#endif
#ifdef INET
case SCTP_IPV4_ADDRESS:
{
/* ipv4 address param */
struct sctp_ipv4addr_param *p4, p4_buf;
if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv4addr_param)) {
return NULL;
}
p4 = (struct sctp_ipv4addr_param *)sctp_get_next_param(m,
offset + sizeof(struct sctp_asconf_chunk),
&p4_buf.ph, sizeof(p4_buf));
if (p4 == NULL) {
SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf v4 lookup addr\n",
__func__);
return (NULL);
}
sin = &remote_store.sin;
sin->sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
sin->sin_len = sizeof(*sin);
#endif
sin->sin_port = sh->src_port;
memcpy(&sin->sin_addr, &p4->addr, sizeof(struct in_addr));
if (sin->sin_addr.s_addr == INADDR_ANY)
zero_address = 1;
break;
}
#endif
default:
/* invalid address param type */
return NULL;
}
if (zero_address) {
stcb = sctp_findassoc_by_vtag(NULL, dst, ntohl(sh->v_tag), inp_p,
netp, sh->src_port, sh->dest_port, 1, vrf_id, 0);
if (stcb != NULL) {
SCTP_INP_DECR_REF(*inp_p);
}
} else {
stcb = sctp_findassociation_ep_addr(inp_p,
&remote_store.sa, netp,
dst, NULL);
}
return (stcb);
}
/*
* allocate a sctp_inpcb and setup a temporary binding to a port/all
* addresses. This way if we don't get a bind we by default pick a ephemeral
* port with all addresses bound.
*/
int
sctp_inpcb_alloc(struct socket *so, uint32_t vrf_id)
{
/*
* we get called when a new endpoint starts up. We need to allocate
* the sctp_inpcb structure from the zone and init it. Mark it as
* unbound and find a port that we can use as an ephemeral with
* INADDR_ANY. If the user binds later no problem we can then add in
* the specific addresses. And setup the default parameters for the
* EP.
*/
int i, error;
struct sctp_inpcb *inp;
struct sctp_pcb *m;
struct timeval time;
sctp_sharedkey_t *null_key;
error = 0;
SCTP_INP_INFO_WLOCK();
inp = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_ep), struct sctp_inpcb);
if (inp == NULL) {
SCTP_PRINTF("Out of SCTP-INPCB structures - no resources\n");
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
return (ENOBUFS);
}
/* zap it */
memset(inp, 0, sizeof(*inp));
/* bump generations */
#if defined(__APPLE__)
inp->ip_inp.inp.inp_state = INPCB_STATE_INUSE;
#endif
/* setup socket pointers */
inp->sctp_socket = so;
inp->ip_inp.inp.inp_socket = so;
#if defined(__FreeBSD__)
inp->ip_inp.inp.inp_cred = crhold(so->so_cred);
#endif
#ifdef INET6
#if !defined(__Userspace__) && !defined(__Windows__)
if (INP_SOCKAF(so) == AF_INET6) {
if (MODULE_GLOBAL(ip6_auto_flowlabel)) {
inp->ip_inp.inp.inp_flags |= IN6P_AUTOFLOWLABEL;
}
if (MODULE_GLOBAL(ip6_v6only)) {
inp->ip_inp.inp.inp_flags |= IN6P_IPV6_V6ONLY;
}
}
#endif
#endif
inp->sctp_associd_counter = 1;
inp->partial_delivery_point = SCTP_SB_LIMIT_RCV(so) >> SCTP_PARTIAL_DELIVERY_SHIFT;
inp->sctp_frag_point = SCTP_DEFAULT_MAXSEGMENT;
inp->max_cwnd = 0;
inp->sctp_cmt_on_off = SCTP_BASE_SYSCTL(sctp_cmt_on_off);
inp->ecn_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_ecn_enable);
inp->prsctp_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_pr_enable);
inp->auth_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_auth_enable);
inp->asconf_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_asconf_enable);
inp->reconfig_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_reconfig_enable);
inp->nrsack_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_nrsack_enable);
inp->pktdrop_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_pktdrop_enable);
inp->idata_supported = 0;
#if defined(__FreeBSD__)
inp->fibnum = so->so_fibnum;
#else
inp->fibnum = 0;
#endif
#if defined(__Userspace__)
inp->ulp_info = NULL;
inp->recv_callback = NULL;
inp->send_callback = NULL;
inp->send_sb_threshold = 0;
#endif
/* init the small hash table we use to track asocid <-> tcb */
inp->sctp_asocidhash = SCTP_HASH_INIT(SCTP_STACK_VTAG_HASH_SIZE, &inp->hashasocidmark);
if (inp->sctp_asocidhash == NULL) {
#if defined(__FreeBSD__)
crfree(inp->ip_inp.inp.inp_cred);
#endif
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
SCTP_INP_INFO_WUNLOCK();
return (ENOBUFS);
}
SCTP_INCR_EP_COUNT();
inp->ip_inp.inp.inp_ip_ttl = MODULE_GLOBAL(ip_defttl);
SCTP_INP_INFO_WUNLOCK();
so->so_pcb = (caddr_t)inp;
#if defined(__FreeBSD__) && __FreeBSD_version < 803000
if ((SCTP_SO_TYPE(so) == SOCK_DGRAM) ||
(SCTP_SO_TYPE(so) == SOCK_SEQPACKET)) {
#else
if (SCTP_SO_TYPE(so) == SOCK_SEQPACKET) {
#endif
/* UDP style socket */
inp->sctp_flags = (SCTP_PCB_FLAGS_UDPTYPE |
SCTP_PCB_FLAGS_UNBOUND);
/* Be sure it is NON-BLOCKING IO for UDP */
/* SCTP_SET_SO_NBIO(so); */
} else if (SCTP_SO_TYPE(so) == SOCK_STREAM) {
/* TCP style socket */
inp->sctp_flags = (SCTP_PCB_FLAGS_TCPTYPE |
SCTP_PCB_FLAGS_UNBOUND);
/* Be sure we have blocking IO by default */
SOCK_LOCK(so);
SCTP_CLEAR_SO_NBIO(so);
SOCK_UNLOCK(so);
#if defined(__Panda__)
} else if (SCTP_SO_TYPE(so) == SOCK_FASTSEQPACKET) {
inp->sctp_flags = (SCTP_PCB_FLAGS_UDPTYPE |
SCTP_PCB_FLAGS_UNBOUND);
} else if (SCTP_SO_TYPE(so) == SOCK_FASTSTREAM) {
inp->sctp_flags = (SCTP_PCB_FLAGS_TCPTYPE |
SCTP_PCB_FLAGS_UNBOUND);
#endif
} else {
/*
* unsupported socket type (RAW, etc)- in case we missed it
* in protosw
*/
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EOPNOTSUPP);
so->so_pcb = NULL;
#if defined(__FreeBSD__)
crfree(inp->ip_inp.inp.inp_cred);
#endif
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
return (EOPNOTSUPP);
}
if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_1) {
sctp_feature_on(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
sctp_feature_off(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
} else if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_2) {
sctp_feature_on(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
sctp_feature_on(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
} else if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_0) {
sctp_feature_off(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
sctp_feature_off(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
}
inp->sctp_tcbhash = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_pcbtblsize),
&inp->sctp_hashmark);
if (inp->sctp_tcbhash == NULL) {
SCTP_PRINTF("Out of SCTP-INPCB->hashinit - no resources\n");
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
so->so_pcb = NULL;
#if defined(__FreeBSD__)
crfree(inp->ip_inp.inp.inp_cred);
#endif
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
return (ENOBUFS);
}
#ifdef SCTP_MVRF
inp->vrf_size = SCTP_DEFAULT_VRF_SIZE;
SCTP_MALLOC(inp->m_vrf_ids, uint32_t *,
(sizeof(uint32_t) * inp->vrf_size), SCTP_M_MVRF);
if (inp->m_vrf_ids == NULL) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
so->so_pcb = NULL;
SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark);
#if defined(__FreeBSD__)
crfree(inp->ip_inp.inp.inp_cred);
#endif
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
return (ENOBUFS);
}
inp->m_vrf_ids[0] = vrf_id;
inp->num_vrfs = 1;
#endif
inp->def_vrf_id = vrf_id;
#if defined(__APPLE__)
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
inp->ip_inp.inp.inpcb_mtx = lck_mtx_alloc_init(SCTP_BASE_INFO(sctbinfo).mtx_grp, SCTP_BASE_INFO(sctbinfo).mtx_attr);
if (inp->ip_inp.inp.inpcb_mtx == NULL) {
SCTP_PRINTF("in_pcballoc: can't alloc mutex! so=%p\n", (void *)so);
#ifdef SCTP_MVRF
SCTP_FREE(inp->m_vrf_ids, SCTP_M_MVRF);
#endif
SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark);
so->so_pcb = NULL;
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
SCTP_UNLOCK_EXC(SCTP_BASE_INFO(sctbinfo).ipi_lock);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM);
return (ENOMEM);
}
#elif defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
lck_mtx_init(&inp->ip_inp.inp.inpcb_mtx, SCTP_BASE_INFO(sctbinfo).mtx_grp, SCTP_BASE_INFO(sctbinfo).mtx_attr);
#else
lck_mtx_init(&inp->ip_inp.inp.inpcb_mtx, SCTP_BASE_INFO(sctbinfo).ipi_lock_grp, SCTP_BASE_INFO(sctbinfo).ipi_lock_attr);
#endif
#endif
SCTP_INP_INFO_WLOCK();
SCTP_INP_LOCK_INIT(inp);
#if defined(__FreeBSD__)
INP_LOCK_INIT(&inp->ip_inp.inp, "inp", "sctpinp");
#endif
SCTP_INP_READ_INIT(inp);
SCTP_ASOC_CREATE_LOCK_INIT(inp);
/* lock the new ep */
SCTP_INP_WLOCK(inp);
/* add it to the info area */
LIST_INSERT_HEAD(&SCTP_BASE_INFO(listhead), inp, sctp_list);
#if defined(__APPLE__)
inp->ip_inp.inp.inp_pcbinfo = &SCTP_BASE_INFO(sctbinfo);
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
LIST_INSERT_HEAD(SCTP_BASE_INFO(sctbinfo).listhead, &inp->ip_inp.inp, inp_list);
#else
LIST_INSERT_HEAD(SCTP_BASE_INFO(sctbinfo).ipi_listhead, &inp->ip_inp.inp, inp_list);
#endif
#endif
SCTP_INP_INFO_WUNLOCK();
TAILQ_INIT(&inp->read_queue);
LIST_INIT(&inp->sctp_addr_list);
LIST_INIT(&inp->sctp_asoc_list);
#ifdef SCTP_TRACK_FREED_ASOCS
/* TEMP CODE */
LIST_INIT(&inp->sctp_asoc_free_list);
#endif
/* Init the timer structure for signature change */
SCTP_OS_TIMER_INIT(&inp->sctp_ep.signature_change.timer);
inp->sctp_ep.signature_change.type = SCTP_TIMER_TYPE_NEWCOOKIE;
/* now init the actual endpoint default data */
m = &inp->sctp_ep;
/* setup the base timeout information */
m->sctp_timeoutticks[SCTP_TIMER_SEND] = SEC_TO_TICKS(SCTP_SEND_SEC); /* needed ? */
m->sctp_timeoutticks[SCTP_TIMER_INIT] = SEC_TO_TICKS(SCTP_INIT_SEC); /* needed ? */
m->sctp_timeoutticks[SCTP_TIMER_RECV] = MSEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_delayed_sack_time_default));
m->sctp_timeoutticks[SCTP_TIMER_HEARTBEAT] = MSEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_heartbeat_interval_default));
m->sctp_timeoutticks[SCTP_TIMER_PMTU] = SEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_pmtu_raise_time_default));
m->sctp_timeoutticks[SCTP_TIMER_MAXSHUTDOWN] = SEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_shutdown_guard_time_default));
m->sctp_timeoutticks[SCTP_TIMER_SIGNATURE] = SEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_secret_lifetime_default));
/* all max/min max are in ms */
m->sctp_maxrto = SCTP_BASE_SYSCTL(sctp_rto_max_default);
m->sctp_minrto = SCTP_BASE_SYSCTL(sctp_rto_min_default);
m->initial_rto = SCTP_BASE_SYSCTL(sctp_rto_initial_default);
m->initial_init_rto_max = SCTP_BASE_SYSCTL(sctp_init_rto_max_default);
m->sctp_sack_freq = SCTP_BASE_SYSCTL(sctp_sack_freq_default);
m->max_init_times = SCTP_BASE_SYSCTL(sctp_init_rtx_max_default);
m->max_send_times = SCTP_BASE_SYSCTL(sctp_assoc_rtx_max_default);
m->def_net_failure = SCTP_BASE_SYSCTL(sctp_path_rtx_max_default);
m->def_net_pf_threshold = SCTP_BASE_SYSCTL(sctp_path_pf_threshold);
m->sctp_sws_sender = SCTP_SWS_SENDER_DEF;
m->sctp_sws_receiver = SCTP_SWS_RECEIVER_DEF;
m->max_burst = SCTP_BASE_SYSCTL(sctp_max_burst_default);
m->fr_max_burst = SCTP_BASE_SYSCTL(sctp_fr_max_burst_default);
m->sctp_default_cc_module = SCTP_BASE_SYSCTL(sctp_default_cc_module);
m->sctp_default_ss_module = SCTP_BASE_SYSCTL(sctp_default_ss_module);
m->max_open_streams_intome = SCTP_BASE_SYSCTL(sctp_nr_incoming_streams_default);
/* number of streams to pre-open on a association */
m->pre_open_stream_count = SCTP_BASE_SYSCTL(sctp_nr_outgoing_streams_default);
m->default_mtu = 0;
/* Add adaptation cookie */
m->adaptation_layer_indicator = 0;
m->adaptation_layer_indicator_provided = 0;
/* seed random number generator */
m->random_counter = 1;
m->store_at = SCTP_SIGNATURE_SIZE;
SCTP_READ_RANDOM(m->random_numbers, sizeof(m->random_numbers));
sctp_fill_random_store(m);
/* Minimum cookie size */
m->size_of_a_cookie = (sizeof(struct sctp_init_msg) * 2) +
sizeof(struct sctp_state_cookie);
m->size_of_a_cookie += SCTP_SIGNATURE_SIZE;
/* Setup the initial secret */
(void)SCTP_GETTIME_TIMEVAL(&time);
m->time_of_secret_change = time.tv_sec;
for (i = 0; i < SCTP_NUMBER_OF_SECRETS; i++) {
m->secret_key[0][i] = sctp_select_initial_TSN(m);
}
sctp_timer_start(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL);
/* How long is a cookie good for ? */
m->def_cookie_life = MSEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_valid_cookie_life_default));
/*
* Initialize authentication parameters
*/
m->local_hmacs = sctp_default_supported_hmaclist();
m->local_auth_chunks = sctp_alloc_chunklist();
if (inp->asconf_supported) {
sctp_auth_add_chunk(SCTP_ASCONF, m->local_auth_chunks);
sctp_auth_add_chunk(SCTP_ASCONF_ACK, m->local_auth_chunks);
}
m->default_dscp = 0;
#ifdef INET6
m->default_flowlabel = 0;
#endif
m->port = 0; /* encapsulation disabled by default */
LIST_INIT(&m->shared_keys);
/* add default NULL key as key id 0 */
null_key = sctp_alloc_sharedkey();
sctp_insert_sharedkey(&m->shared_keys, null_key);
SCTP_INP_WUNLOCK(inp);
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 12);
#endif
return (error);
}
void
sctp_move_pcb_and_assoc(struct sctp_inpcb *old_inp, struct sctp_inpcb *new_inp,
struct sctp_tcb *stcb)
{
struct sctp_nets *net;
uint16_t lport, rport;
struct sctppcbhead *head;
struct sctp_laddr *laddr, *oladdr;
atomic_add_int(&stcb->asoc.refcnt, 1);
SCTP_TCB_UNLOCK(stcb);
SCTP_INP_INFO_WLOCK();
SCTP_INP_WLOCK(old_inp);
SCTP_INP_WLOCK(new_inp);
SCTP_TCB_LOCK(stcb);
atomic_subtract_int(&stcb->asoc.refcnt, 1);
new_inp->sctp_ep.time_of_secret_change =
old_inp->sctp_ep.time_of_secret_change;
memcpy(new_inp->sctp_ep.secret_key, old_inp->sctp_ep.secret_key,
sizeof(old_inp->sctp_ep.secret_key));
new_inp->sctp_ep.current_secret_number =
old_inp->sctp_ep.current_secret_number;
new_inp->sctp_ep.last_secret_number =
old_inp->sctp_ep.last_secret_number;
new_inp->sctp_ep.size_of_a_cookie = old_inp->sctp_ep.size_of_a_cookie;
/* make it so new data pours into the new socket */
stcb->sctp_socket = new_inp->sctp_socket;
stcb->sctp_ep = new_inp;
/* Copy the port across */
lport = new_inp->sctp_lport = old_inp->sctp_lport;
rport = stcb->rport;
/* Pull the tcb from the old association */
LIST_REMOVE(stcb, sctp_tcbhash);
LIST_REMOVE(stcb, sctp_tcblist);
if (stcb->asoc.in_asocid_hash) {
LIST_REMOVE(stcb, sctp_tcbasocidhash);
}
/* Now insert the new_inp into the TCP connected hash */
head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR((lport | rport), SCTP_BASE_INFO(hashtcpmark))];
LIST_INSERT_HEAD(head, new_inp, sctp_hash);
/* Its safe to access */
new_inp->sctp_flags &= ~SCTP_PCB_FLAGS_UNBOUND;
/* Now move the tcb into the endpoint list */
LIST_INSERT_HEAD(&new_inp->sctp_asoc_list, stcb, sctp_tcblist);
/*
* Question, do we even need to worry about the ep-hash since we
* only have one connection? Probably not :> so lets get rid of it
* and not suck up any kernel memory in that.
*/
if (stcb->asoc.in_asocid_hash) {
struct sctpasochead *lhd;
lhd = &new_inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(stcb->asoc.assoc_id,
new_inp->hashasocidmark)];
LIST_INSERT_HEAD(lhd, stcb, sctp_tcbasocidhash);
}
/* Ok. Let's restart timer. */
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
sctp_timer_start(SCTP_TIMER_TYPE_PATHMTURAISE, new_inp,
stcb, net);
}
SCTP_INP_INFO_WUNLOCK();
if (new_inp->sctp_tcbhash != NULL) {
SCTP_HASH_FREE(new_inp->sctp_tcbhash, new_inp->sctp_hashmark);
new_inp->sctp_tcbhash = NULL;
}
if ((new_inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
/* Subset bound, so copy in the laddr list from the old_inp */
LIST_FOREACH(oladdr, &old_inp->sctp_addr_list, sctp_nxt_addr) {
laddr = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
if (laddr == NULL) {
/*
* Gak, what can we do? This assoc is really
* HOSED. We probably should send an abort
* here.
*/
SCTPDBG(SCTP_DEBUG_PCB1, "Association hosed in TCP model, out of laddr memory\n");
continue;
}
SCTP_INCR_LADDR_COUNT();
memset(laddr, 0, sizeof(*laddr));
(void)SCTP_GETTIME_TIMEVAL(&laddr->start_time);
laddr->ifa = oladdr->ifa;
atomic_add_int(&laddr->ifa->refcount, 1);
LIST_INSERT_HEAD(&new_inp->sctp_addr_list, laddr,
sctp_nxt_addr);
new_inp->laddr_count++;
if (oladdr == stcb->asoc.last_used_address) {
stcb->asoc.last_used_address = laddr;
}
}
}
/* Now any running timers need to be adjusted
* since we really don't care if they are running
* or not just blast in the new_inp into all of
* them.
*/
stcb->asoc.dack_timer.ep = (void *)new_inp;
stcb->asoc.asconf_timer.ep = (void *)new_inp;
stcb->asoc.strreset_timer.ep = (void *)new_inp;
stcb->asoc.shut_guard_timer.ep = (void *)new_inp;
stcb->asoc.autoclose_timer.ep = (void *)new_inp;
stcb->asoc.delayed_event_timer.ep = (void *)new_inp;
stcb->asoc.delete_prim_timer.ep = (void *)new_inp;
/* now what about the nets? */
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
net->pmtu_timer.ep = (void *)new_inp;
net->hb_timer.ep = (void *)new_inp;
net->rxt_timer.ep = (void *)new_inp;
}
SCTP_INP_WUNLOCK(new_inp);
SCTP_INP_WUNLOCK(old_inp);
}
/*
* insert an laddr entry with the given ifa for the desired list
*/
static int
sctp_insert_laddr(struct sctpladdr *list, struct sctp_ifa *ifa, uint32_t act)
{
struct sctp_laddr *laddr;
laddr = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
if (laddr == NULL) {
/* out of memory? */
SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
SCTP_INCR_LADDR_COUNT();
memset(laddr, 0, sizeof(*laddr));
(void)SCTP_GETTIME_TIMEVAL(&laddr->start_time);
laddr->ifa = ifa;
laddr->action = act;
atomic_add_int(&ifa->refcount, 1);
/* insert it */
LIST_INSERT_HEAD(list, laddr, sctp_nxt_addr);
return (0);
}
/*
* Remove an laddr entry from the local address list (on an assoc)
*/
static void
sctp_remove_laddr(struct sctp_laddr *laddr)
{
/* remove from the list */
LIST_REMOVE(laddr, sctp_nxt_addr);
sctp_free_ifa(laddr->ifa);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_laddr), laddr);
SCTP_DECR_LADDR_COUNT();
}
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Userspace__))
/*
* Don't know why, but without this there is an unknown reference when
* compiling NetBSD... hmm
*/
extern void in6_sin6_2_sin(struct sockaddr_in *, struct sockaddr_in6 *sin6);
#endif
/* sctp_ifap is used to bypass normal local address validation checks */
int
#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
sctp_inpcb_bind(struct socket *so, struct sockaddr *addr,
struct sctp_ifa *sctp_ifap, struct thread *p)
#elif defined(__Windows__)
sctp_inpcb_bind(struct socket *so, struct sockaddr *addr,
struct sctp_ifa *sctp_ifap, PKTHREAD p)
#else
sctp_inpcb_bind(struct socket *so, struct sockaddr *addr,
struct sctp_ifa *sctp_ifap, struct proc *p)
#endif
{
/* bind a ep to a socket address */
struct sctppcbhead *head;
struct sctp_inpcb *inp, *inp_tmp;
#if defined(__FreeBSD__) || defined(__APPLE__)
struct inpcb *ip_inp;
#endif
int port_reuse_active = 0;
int bindall;
#ifdef SCTP_MVRF
int i;
#endif
uint16_t lport;
int error;
uint32_t vrf_id;
lport = 0;
bindall = 1;
inp = (struct sctp_inpcb *)so->so_pcb;
#if defined(__FreeBSD__) || defined(__APPLE__)
ip_inp = (struct inpcb *)so->so_pcb;
#endif
#ifdef SCTP_DEBUG
if (addr) {
SCTPDBG(SCTP_DEBUG_PCB1, "Bind called port: %d\n",
ntohs(((struct sockaddr_in *)addr)->sin_port));
SCTPDBG(SCTP_DEBUG_PCB1, "Addr: ");
SCTPDBG_ADDR(SCTP_DEBUG_PCB1, addr);
}
#endif
if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) == 0) {
/* already did a bind, subsequent binds NOT allowed ! */
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
#ifdef INVARIANTS
if (p == NULL)
panic("null proc/thread");
#endif
#endif
if (addr != NULL) {
switch (addr->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin;
/* IPV6_V6ONLY socket? */
if (SCTP_IPV6_V6ONLY(inp)) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#ifdef HAVE_SA_LEN
if (addr->sa_len != sizeof(*sin)) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#endif
sin = (struct sockaddr_in *)addr;
lport = sin->sin_port;
#if defined(__FreeBSD__) && __FreeBSD_version >= 800000
/*
* For LOOPBACK the prison_local_ip4() call will transmute the ip address
* to the proper value.
*/
if (p && (error = prison_local_ip4(p->td_ucred, &sin->sin_addr)) != 0) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
return (error);
}
#endif
if (sin->sin_addr.s_addr != INADDR_ANY) {
bindall = 0;
}
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
/* Only for pure IPv6 Address. (No IPv4 Mapped!) */
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)addr;
#ifdef HAVE_SA_LEN
if (addr->sa_len != sizeof(*sin6)) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#endif
lport = sin6->sin6_port;
#if defined(__FreeBSD__) && __FreeBSD_version >= 800000
/*
* For LOOPBACK the prison_local_ip6() call will transmute the ipv6 address
* to the proper value.
*/
if (p && (error = prison_local_ip6(p->td_ucred, &sin6->sin6_addr,
(SCTP_IPV6_V6ONLY(inp) != 0))) != 0) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
return (error);
}
#endif
if (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
bindall = 0;
#ifdef SCTP_EMBEDDED_V6_SCOPE
/* KAME hack: embed scopeid */
#if defined(SCTP_KAME)
if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#elif defined(__APPLE__)
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
if (in6_embedscope(&sin6->sin6_addr, sin6, ip_inp, NULL) != 0) {
#else
if (in6_embedscope(&sin6->sin6_addr, sin6, ip_inp, NULL, NULL) != 0) {
#endif
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#elif defined(__FreeBSD__)
error = scope6_check_id(sin6, MODULE_GLOBAL(ip6_use_defzone));
if (error != 0) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
return (error);
}
#else
if (in6_embedscope(&sin6->sin6_addr, sin6) != 0) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#endif
#endif /* SCTP_EMBEDDED_V6_SCOPE */
}
#ifndef SCOPEDROUTING
/* this must be cleared for ifa_ifwithaddr() */
sin6->sin6_scope_id = 0;
#endif /* SCOPEDROUTING */
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
{
struct sockaddr_conn *sconn;
#ifdef HAVE_SA_LEN
if (addr->sa_len != sizeof(struct sockaddr_conn)) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#endif
sconn = (struct sockaddr_conn *)addr;
lport = sconn->sconn_port;
if (sconn->sconn_addr != NULL) {
bindall = 0;
}
break;
}
#endif
default:
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EAFNOSUPPORT);
return (EAFNOSUPPORT);
}
}
SCTP_INP_INFO_WLOCK();
SCTP_INP_WLOCK(inp);
/* Setup a vrf_id to be the default for the non-bind-all case. */
vrf_id = inp->def_vrf_id;
/* increase our count due to the unlock we do */
SCTP_INP_INCR_REF(inp);
if (lport) {
/*
* Did the caller specify a port? if so we must see if an ep
* already has this one bound.
*/
/* got to be root to get at low ports */
#if !defined(__Windows__)
if (ntohs(lport) < IPPORT_RESERVED) {
if ((p != NULL) && ((error =
#ifdef __FreeBSD__
#if __FreeBSD_version > 602000
priv_check(p, PRIV_NETINET_RESERVEDPORT)
#elif __FreeBSD_version >= 500000
suser_cred(p->td_ucred, 0)
#else
suser(p)
#endif
#elif defined(__APPLE__)
suser(p->p_ucred, &p->p_acflag)
#elif defined(__Userspace__) /* must be true to use raw socket */
1
#else
suser(p, 0)
#endif
) != 0)) {
SCTP_INP_DECR_REF(inp);
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
return (error);
}
#if defined(__Panda__)
if (!SCTP_IS_PRIVILEDGED(so)) {
SCTP_INP_DECR_REF(inp);
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EACCES);
return (EACCES);
}
#endif
}
#endif /* __Windows__ */
SCTP_INP_WUNLOCK(inp);
if (bindall) {
#ifdef SCTP_MVRF
for (i = 0; i < inp->num_vrfs; i++) {
vrf_id = inp->m_vrf_ids[i];
#else
vrf_id = inp->def_vrf_id;
#endif
inp_tmp = sctp_pcb_findep(addr, 0, 1, vrf_id);
if (inp_tmp != NULL) {
/*
* lock guy returned and lower count
* note that we are not bound so
* inp_tmp should NEVER be inp. And
* it is this inp (inp_tmp) that gets
* the reference bump, so we must
* lower it.
*/
SCTP_INP_DECR_REF(inp_tmp);
/* unlock info */
if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
(sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
/* Ok, must be one-2-one and allowing port re-use */
port_reuse_active = 1;
goto continue_anyway;
}
SCTP_INP_DECR_REF(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
return (EADDRINUSE);
}
#ifdef SCTP_MVRF
}
#endif
} else {
inp_tmp = sctp_pcb_findep(addr, 0, 1, vrf_id);
if (inp_tmp != NULL) {
/*
* lock guy returned and lower count note
* that we are not bound so inp_tmp should
* NEVER be inp. And it is this inp (inp_tmp)
* that gets the reference bump, so we must
* lower it.
*/
SCTP_INP_DECR_REF(inp_tmp);
/* unlock info */
if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
(sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
/* Ok, must be one-2-one and allowing port re-use */
port_reuse_active = 1;
goto continue_anyway;
}
SCTP_INP_DECR_REF(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
return (EADDRINUSE);
}
}
continue_anyway:
SCTP_INP_WLOCK(inp);
if (bindall) {
/* verify that no lport is not used by a singleton */
if ((port_reuse_active == 0) &&
(inp_tmp = sctp_isport_inuse(inp, lport, vrf_id))) {
/* Sorry someone already has this one bound */
if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
(sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
port_reuse_active = 1;
} else {
SCTP_INP_DECR_REF(inp);
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
return (EADDRINUSE);
}
}
}
} else {
uint16_t first, last, candidate;
uint16_t count;
int done;
#if defined(__Windows__)
first = 1;
last = 0xffff;
#else
#if defined(__Userspace__)
/* TODO ensure uid is 0, etc... */
#elif defined(__FreeBSD__) || defined(__APPLE__)
if (ip_inp->inp_flags & INP_HIGHPORT) {
first = MODULE_GLOBAL(ipport_hifirstauto);
last = MODULE_GLOBAL(ipport_hilastauto);
} else if (ip_inp->inp_flags & INP_LOWPORT) {
if (p && (error =
#ifdef __FreeBSD__
#if __FreeBSD_version > 602000
priv_check(p, PRIV_NETINET_RESERVEDPORT)
#elif __FreeBSD_version >= 500000
suser_cred(p->td_ucred, 0)
#else
suser(p)
#endif
#elif defined(__APPLE__)
suser(p->p_ucred, &p->p_acflag)
#else
suser(p, 0)
#endif
)) {
SCTP_INP_DECR_REF(inp);
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
return (error);
}
first = MODULE_GLOBAL(ipport_lowfirstauto);
last = MODULE_GLOBAL(ipport_lowlastauto);
} else {
#endif
first = MODULE_GLOBAL(ipport_firstauto);
last = MODULE_GLOBAL(ipport_lastauto);
#if defined(__FreeBSD__) || defined(__APPLE__)
}
#endif
#endif /* __Windows__ */
if (first > last) {
uint16_t temp;
temp = first;
first = last;
last = temp;
}
count = last - first + 1; /* number of candidates */
candidate = first + sctp_select_initial_TSN(&inp->sctp_ep) % (count);
done = 0;
while (!done) {
#ifdef SCTP_MVRF
for (i = 0; i < inp->num_vrfs; i++) {
if (sctp_isport_inuse(inp, htons(candidate), inp->m_vrf_ids[i]) != NULL) {
break;
}
}
if (i == inp->num_vrfs) {
done = 1;
}
#else
if (sctp_isport_inuse(inp, htons(candidate), inp->def_vrf_id) == NULL) {
done = 1;
}
#endif
if (!done) {
if (--count == 0) {
SCTP_INP_DECR_REF(inp);
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
return (EADDRINUSE);
}
if (candidate == last)
candidate = first;
else
candidate = candidate + 1;
}
}
lport = htons(candidate);
}
SCTP_INP_DECR_REF(inp);
if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE |
SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
/*
* this really should not happen. The guy did a non-blocking
* bind and then did a close at the same time.
*/
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
/* ok we look clear to give out this port, so lets setup the binding */
if (bindall) {
/* binding to all addresses, so just set in the proper flags */
inp->sctp_flags |= SCTP_PCB_FLAGS_BOUNDALL;
/* set the automatic addr changes from kernel flag */
if (SCTP_BASE_SYSCTL(sctp_auto_asconf) == 0) {
sctp_feature_off(inp, SCTP_PCB_FLAGS_DO_ASCONF);
sctp_feature_off(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);
} else {
sctp_feature_on(inp, SCTP_PCB_FLAGS_DO_ASCONF);
sctp_feature_on(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);
}
if (SCTP_BASE_SYSCTL(sctp_multiple_asconfs) == 0) {
sctp_feature_off(inp, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS);
} else {
sctp_feature_on(inp, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS);
}
/* set the automatic mobility_base from kernel
flag (by micchie)
*/
if (SCTP_BASE_SYSCTL(sctp_mobility_base) == 0) {
sctp_mobility_feature_off(inp, SCTP_MOBILITY_BASE);
sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
} else {
sctp_mobility_feature_on(inp, SCTP_MOBILITY_BASE);
sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
}
/* set the automatic mobility_fasthandoff from kernel
flag (by micchie)
*/
if (SCTP_BASE_SYSCTL(sctp_mobility_fasthandoff) == 0) {
sctp_mobility_feature_off(inp, SCTP_MOBILITY_FASTHANDOFF);
sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
} else {
sctp_mobility_feature_on(inp, SCTP_MOBILITY_FASTHANDOFF);
sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
}
} else {
/*
* bind specific, make sure flags is off and add a new
* address structure to the sctp_addr_list inside the ep
* structure.
*
* We will need to allocate one and insert it at the head. The
* socketopt call can just insert new addresses in there as
* well. It will also have to do the embed scope kame hack
* too (before adding).
*/
struct sctp_ifa *ifa;
union sctp_sockstore store;
memset(&store, 0, sizeof(store));
switch (addr->sa_family) {
#ifdef INET
case AF_INET:
memcpy(&store.sin, addr, sizeof(struct sockaddr_in));
store.sin.sin_port = 0;
break;
#endif
#ifdef INET6
case AF_INET6:
memcpy(&store.sin6, addr, sizeof(struct sockaddr_in6));
store.sin6.sin6_port = 0;
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
memcpy(&store.sconn, addr, sizeof(struct sockaddr_conn));
store.sconn.sconn_port = 0;
break;
#endif
default:
break;
}
/*
* first find the interface with the bound address need to
* zero out the port to find the address! yuck! can't do
* this earlier since need port for sctp_pcb_findep()
*/
if (sctp_ifap != NULL) {
ifa = sctp_ifap;
} else {
/* Note for BSD we hit here always other
* O/S's will pass things in via the
* sctp_ifap argument (Panda).
*/
ifa = sctp_find_ifa_by_addr(&store.sa,
vrf_id, SCTP_ADDR_NOT_LOCKED);
}
if (ifa == NULL) {
/* Can't find an interface with that address */
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRNOTAVAIL);
return (EADDRNOTAVAIL);
}
#ifdef INET6
if (addr->sa_family == AF_INET6) {
/* GAK, more FIXME IFA lock? */
if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
/* Can't bind a non-existent addr. */
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
}
#endif
/* we're not bound all */
inp->sctp_flags &= ~SCTP_PCB_FLAGS_BOUNDALL;
/* allow bindx() to send ASCONF's for binding changes */
sctp_feature_on(inp, SCTP_PCB_FLAGS_DO_ASCONF);
/* clear automatic addr changes from kernel flag */
sctp_feature_off(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);
/* add this address to the endpoint list */
error = sctp_insert_laddr(&inp->sctp_addr_list, ifa, 0);
if (error != 0) {
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
return (error);
}
inp->laddr_count++;
}
/* find the bucket */
if (port_reuse_active) {
/* Put it into tcp 1-2-1 hash */
head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR(lport, SCTP_BASE_INFO(hashtcpmark))];
inp->sctp_flags |= SCTP_PCB_FLAGS_IN_TCPPOOL;
} else {
head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport, SCTP_BASE_INFO(hashmark))];
}
/* put it in the bucket */
LIST_INSERT_HEAD(head, inp, sctp_hash);
SCTPDBG(SCTP_DEBUG_PCB1, "Main hash to bind at head:%p, bound port:%d - in tcp_pool=%d\n",
(void *)head, ntohs(lport), port_reuse_active);
/* set in the port */
inp->sctp_lport = lport;
/* turn off just the unbound flag */
inp->sctp_flags &= ~SCTP_PCB_FLAGS_UNBOUND;
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
return (0);
}
static void
sctp_iterator_inp_being_freed(struct sctp_inpcb *inp)
{
struct sctp_iterator *it, *nit;
/*
* We enter with the only the ITERATOR_LOCK in place and a write
* lock on the inp_info stuff.
*/
it = sctp_it_ctl.cur_it;
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
if (it && (it->vn != curvnet)) {
/* Its not looking at our VNET */
return;
}
#endif
if (it && (it->inp == inp)) {
/*
* This is tricky and we hold the iterator lock,
* but when it returns and gets the lock (when we
* release it) the iterator will try to operate on
* inp. We need to stop that from happening. But
* of course the iterator has a reference on the
* stcb and inp. We can mark it and it will stop.
*
* If its a single iterator situation, we
* set the end iterator flag. Otherwise
* we set the iterator to go to the next inp.
*
*/
if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_IT;
} else {
sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_INP;
}
}
/* Now go through and remove any single reference to
* our inp that may be still pending on the list
*/
SCTP_IPI_ITERATOR_WQ_LOCK();
TAILQ_FOREACH_SAFE(it, &sctp_it_ctl.iteratorhead, sctp_nxt_itr, nit) {
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
if (it->vn != curvnet) {
continue;
}
#endif
if (it->inp == inp) {
/* This one points to me is it inp specific? */
if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
/* Remove and free this one */
TAILQ_REMOVE(&sctp_it_ctl.iteratorhead,
it, sctp_nxt_itr);
if (it->function_atend != NULL) {
(*it->function_atend) (it->pointer, it->val);
}
SCTP_FREE(it, SCTP_M_ITER);
} else {
it->inp = LIST_NEXT(it->inp, sctp_list);
if (it->inp) {
SCTP_INP_INCR_REF(it->inp);
}
}
/* When its put in the refcnt is incremented so decr it */
SCTP_INP_DECR_REF(inp);
}
}
SCTP_IPI_ITERATOR_WQ_UNLOCK();
}
/* release sctp_inpcb unbind the port */
void
sctp_inpcb_free(struct sctp_inpcb *inp, int immediate, int from)
{
/*
* Here we free a endpoint. We must find it (if it is in the Hash
* table) and remove it from there. Then we must also find it in the
* overall list and remove it from there. After all removals are
* complete then any timer has to be stopped. Then start the actual
* freeing. a) Any local lists. b) Any associations. c) The hash of
* all associations. d) finally the ep itself.
*/
struct sctp_tcb *asoc, *nasoc;
struct sctp_laddr *laddr, *nladdr;
struct inpcb *ip_pcb;
struct socket *so;
int being_refed = 0;
struct sctp_queued_to_read *sq, *nsq;
#if !defined(__Panda__) && !defined(__Userspace__)
#if !defined(__FreeBSD__) || __FreeBSD_version < 500000
sctp_rtentry_t *rt;
#endif
#endif
int cnt;
sctp_sharedkey_t *shared_key, *nshared_key;
#if defined(__APPLE__)
sctp_lock_assert(SCTP_INP_SO(inp));
#endif
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 0);
#endif
SCTP_ITERATOR_LOCK();
/* mark any iterators on the list or being processed */
sctp_iterator_inp_being_freed(inp);
SCTP_ITERATOR_UNLOCK();
so = inp->sctp_socket;
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
/* been here before.. eeks.. get out of here */
SCTP_PRINTF("This conflict in free SHOULD not be happening! from %d, imm %d\n", from, immediate);
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 1);
#endif
return;
}
SCTP_ASOC_CREATE_LOCK(inp);
SCTP_INP_INFO_WLOCK();
SCTP_INP_WLOCK(inp);
if (from == SCTP_CALLED_AFTER_CMPSET_OFCLOSE) {
inp->sctp_flags &= ~SCTP_PCB_FLAGS_CLOSE_IP;
/* socket is gone, so no more wakeups allowed */
inp->sctp_flags |= SCTP_PCB_FLAGS_DONT_WAKE;
inp->sctp_flags &= ~SCTP_PCB_FLAGS_WAKEINPUT;
inp->sctp_flags &= ~SCTP_PCB_FLAGS_WAKEOUTPUT;
}
/* First time through we have the socket lock, after that no more. */
sctp_timer_stop(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL,
SCTP_FROM_SCTP_PCB + SCTP_LOC_1);
if (inp->control) {
sctp_m_freem(inp->control);
inp->control = NULL;
}
if (inp->pkt) {
sctp_m_freem(inp->pkt);
inp->pkt = NULL;
}
ip_pcb = &inp->ip_inp.inp; /* we could just cast the main pointer
* here but I will be nice :> (i.e.
* ip_pcb = ep;) */
if (immediate == SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE) {
int cnt_in_sd;
cnt_in_sd = 0;
LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_list, sctp_tcblist, nasoc) {
SCTP_TCB_LOCK(asoc);
if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
/* Skip guys being freed */
cnt_in_sd++;
if (asoc->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE) {
/*
* Special case - we did not start a kill
* timer on the asoc due to it was not
* closed. So go ahead and start it now.
*/
SCTP_CLEAR_SUBSTATE(asoc, SCTP_STATE_IN_ACCEPT_QUEUE);
sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, asoc, NULL);
}
SCTP_TCB_UNLOCK(asoc);
continue;
}
if (((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
(SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) &&
(asoc->asoc.total_output_queue_size == 0)) {
/* If we have data in queue, we don't want to just
* free since the app may have done, send()/close
* or connect/send/close. And it wants the data
* to get across first.
*/
/* Just abandon things in the front states */
if (sctp_free_assoc(inp, asoc, SCTP_PCBFREE_NOFORCE,
SCTP_FROM_SCTP_PCB + SCTP_LOC_2) == 0) {
cnt_in_sd++;
}
continue;
}
/* Disconnect the socket please */
asoc->sctp_socket = NULL;
SCTP_ADD_SUBSTATE(asoc, SCTP_STATE_CLOSED_SOCKET);
if ((asoc->asoc.size_on_reasm_queue > 0) ||
(asoc->asoc.control_pdapi) ||
(asoc->asoc.size_on_all_streams > 0) ||
(so && (so->so_rcv.sb_cc > 0))) {
/* Left with Data unread */
struct mbuf *op_err;
op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB + SCTP_LOC_3;
sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED);
SCTP_STAT_INCR_COUNTER32(sctps_aborted);
if ((SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) ||
(SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
SCTP_STAT_DECR_GAUGE32(sctps_currestab);
}
if (sctp_free_assoc(inp, asoc,
SCTP_PCBFREE_NOFORCE, SCTP_FROM_SCTP_PCB + SCTP_LOC_4) == 0) {
cnt_in_sd++;
}
continue;
} else if (TAILQ_EMPTY(&asoc->asoc.send_queue) &&
TAILQ_EMPTY(&asoc->asoc.sent_queue) &&
(asoc->asoc.stream_queue_cnt == 0)) {
if ((*asoc->asoc.ss_functions.sctp_ss_is_user_msgs_incomplete)(asoc, &asoc->asoc)) {
goto abort_anyway;
}
if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
(SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
struct sctp_nets *netp;
/*
* there is nothing queued to send,
* so I send shutdown
*/
if ((SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) ||
(SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
SCTP_STAT_DECR_GAUGE32(sctps_currestab);
}
SCTP_SET_STATE(asoc, SCTP_STATE_SHUTDOWN_SENT);
sctp_stop_timers_for_shutdown(asoc);
if (asoc->asoc.alternate) {
netp = asoc->asoc.alternate;
} else {
netp = asoc->asoc.primary_destination;
}
sctp_send_shutdown(asoc, netp);
sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, asoc->sctp_ep, asoc,
netp);
sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, asoc->sctp_ep, asoc,
asoc->asoc.primary_destination);
sctp_chunk_output(inp, asoc, SCTP_OUTPUT_FROM_SHUT_TMR, SCTP_SO_LOCKED);
}
} else {
/* mark into shutdown pending */
SCTP_ADD_SUBSTATE(asoc, SCTP_STATE_SHUTDOWN_PENDING);
sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, asoc->sctp_ep, asoc,
asoc->asoc.primary_destination);
if ((*asoc->asoc.ss_functions.sctp_ss_is_user_msgs_incomplete)(asoc, &asoc->asoc)) {
SCTP_ADD_SUBSTATE(asoc, SCTP_STATE_PARTIAL_MSG_LEFT);
}
if (TAILQ_EMPTY(&asoc->asoc.send_queue) &&
TAILQ_EMPTY(&asoc->asoc.sent_queue) &&
(asoc->asoc.state & SCTP_STATE_PARTIAL_MSG_LEFT)) {
struct mbuf *op_err;
abort_anyway:
op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB + SCTP_LOC_5;
sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED);
SCTP_STAT_INCR_COUNTER32(sctps_aborted);
if ((SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) ||
(SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
SCTP_STAT_DECR_GAUGE32(sctps_currestab);
}
if (sctp_free_assoc(inp, asoc,
SCTP_PCBFREE_NOFORCE,
SCTP_FROM_SCTP_PCB + SCTP_LOC_6) == 0) {
cnt_in_sd++;
}
continue;
} else {
sctp_chunk_output(inp, asoc, SCTP_OUTPUT_FROM_CLOSING, SCTP_SO_LOCKED);
}
}
cnt_in_sd++;
SCTP_TCB_UNLOCK(asoc);
}
/* now is there some left in our SHUTDOWN state? */
if (cnt_in_sd) {
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 2);
#endif
inp->sctp_socket = NULL;
SCTP_INP_WUNLOCK(inp);
SCTP_ASOC_CREATE_UNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
return;
}
}
inp->sctp_socket = NULL;
if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) !=
SCTP_PCB_FLAGS_UNBOUND) {
/*
* ok, this guy has been bound. It's port is
* somewhere in the SCTP_BASE_INFO(hash table). Remove
* it!
*/
LIST_REMOVE(inp, sctp_hash);
inp->sctp_flags |= SCTP_PCB_FLAGS_UNBOUND;
}
/* If there is a timer running to kill us,
* forget it, since it may have a contest
* on the INP lock.. which would cause us
* to die ...
*/
cnt = 0;
LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_list, sctp_tcblist, nasoc) {
SCTP_TCB_LOCK(asoc);
if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
if (asoc->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE) {
SCTP_CLEAR_SUBSTATE(asoc, SCTP_STATE_IN_ACCEPT_QUEUE);
sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, asoc, NULL);
}
cnt++;
SCTP_TCB_UNLOCK(asoc);
continue;
}
/* Free associations that are NOT killing us */
if ((SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) &&
((asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) == 0)) {
struct mbuf *op_err;
op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB + SCTP_LOC_7;
sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED);
SCTP_STAT_INCR_COUNTER32(sctps_aborted);
} else if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
cnt++;
SCTP_TCB_UNLOCK(asoc);
continue;
}
if ((SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) ||
(SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
SCTP_STAT_DECR_GAUGE32(sctps_currestab);
}
if (sctp_free_assoc(inp, asoc, SCTP_PCBFREE_FORCE,
SCTP_FROM_SCTP_PCB + SCTP_LOC_8) == 0) {
cnt++;
}
}
if (cnt) {
/* Ok we have someone out there that will kill us */
(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.signature_change.timer);
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 3);
#endif
SCTP_INP_WUNLOCK(inp);
SCTP_ASOC_CREATE_UNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
return;
}
if (SCTP_INP_LOCK_CONTENDED(inp))
being_refed++;
if (SCTP_INP_READ_CONTENDED(inp))
being_refed++;
if (SCTP_ASOC_CREATE_LOCK_CONTENDED(inp))
being_refed++;
if ((inp->refcount) ||
(being_refed) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_CLOSE_IP)) {
(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.signature_change.timer);
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 4);
#endif
sctp_timer_start(SCTP_TIMER_TYPE_INPKILL, inp, NULL, NULL);
SCTP_INP_WUNLOCK(inp);
SCTP_ASOC_CREATE_UNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
return;
}
inp->sctp_ep.signature_change.type = 0;
inp->sctp_flags |= SCTP_PCB_FLAGS_SOCKET_ALLGONE;
/* Remove it from the list .. last thing we need a
* lock for.
*/
LIST_REMOVE(inp, sctp_list);
SCTP_INP_WUNLOCK(inp);
SCTP_ASOC_CREATE_UNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
/* Now we release all locks. Since this INP
* cannot be found anymore except possibly by the
* kill timer that might be running. We call
* the drain function here. It should hit the case
* were it sees the ACTIVE flag cleared and exit
* out freeing us to proceed and destroy everything.
*/
if (from != SCTP_CALLED_FROM_INPKILL_TIMER) {
(void)SCTP_OS_TIMER_STOP_DRAIN(&inp->sctp_ep.signature_change.timer);
} else {
/* Probably un-needed */
(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.signature_change.timer);
}
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 5);
#endif
#if !(defined(__Panda__) || defined(__Windows__) || defined(__Userspace__))
#if !defined(__FreeBSD__) || __FreeBSD_version < 500000
rt = ip_pcb->inp_route.ro_rt;
#endif
#endif
if ((inp->sctp_asocidhash) != NULL) {
SCTP_HASH_FREE(inp->sctp_asocidhash, inp->hashasocidmark);
inp->sctp_asocidhash = NULL;
}
/*sa_ignore FREED_MEMORY*/
TAILQ_FOREACH_SAFE(sq, &inp->read_queue, next, nsq) {
/* Its only abandoned if it had data left */
if (sq->length)
SCTP_STAT_INCR(sctps_left_abandon);
TAILQ_REMOVE(&inp->read_queue, sq, next);
sctp_free_remote_addr(sq->whoFrom);
if (so)
so->so_rcv.sb_cc -= sq->length;
if (sq->data) {
sctp_m_freem(sq->data);
sq->data = NULL;
}
/*
* no need to free the net count, since at this point all
* assoc's are gone.
*/
sctp_free_a_readq(NULL, sq);
}
/* Now the sctp_pcb things */
/*
* free each asoc if it is not already closed/free. we can't use the
* macro here since le_next will get freed as part of the
* sctp_free_assoc() call.
*/
#ifndef __Panda__
if (ip_pcb->inp_options) {
(void)sctp_m_free(ip_pcb->inp_options);
ip_pcb->inp_options = 0;
}
#endif
#if !(defined(__Panda__) || defined(__Windows__) || defined(__Userspace__))
#if !defined(__FreeBSD__) || __FreeBSD_version < 500000
if (rt) {
RTFREE(rt);
ip_pcb->inp_route.ro_rt = 0;
}
#endif
#if defined(__FreeBSD__) && __FreeBSD_version < 803000
#ifdef INET
if (ip_pcb->inp_moptions) {
inp_freemoptions(ip_pcb->inp_moptions);
ip_pcb->inp_moptions = 0;
}
#endif
#endif
#endif
#ifdef INET6
#if !(defined(__Panda__) || defined(__Windows__) || defined(__Userspace__))
#if defined(__FreeBSD__) || defined(__APPLE__)
if (ip_pcb->inp_vflag & INP_IPV6) {
#else
if (inp->inp_vflag & INP_IPV6) {
#endif
ip6_freepcbopts(ip_pcb->in6p_outputopts);
}
#endif
#endif /* INET6 */
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
inp->inp_vflag = 0;
#else
ip_pcb->inp_vflag = 0;
#endif
/* free up authentication fields */
if (inp->sctp_ep.local_auth_chunks != NULL)
sctp_free_chunklist(inp->sctp_ep.local_auth_chunks);
if (inp->sctp_ep.local_hmacs != NULL)
sctp_free_hmaclist(inp->sctp_ep.local_hmacs);
LIST_FOREACH_SAFE(shared_key, &inp->sctp_ep.shared_keys, next, nshared_key) {
LIST_REMOVE(shared_key, next);
sctp_free_sharedkey(shared_key);
/*sa_ignore FREED_MEMORY*/
}
#if defined(__APPLE__)
inp->ip_inp.inp.inp_state = INPCB_STATE_DEAD;
if (in_pcb_checkstate(&inp->ip_inp.inp, WNT_STOPUSING, 1) != WNT_STOPUSING) {
#ifdef INVARIANTS
panic("sctp_inpcb_free inp = %p couldn't set to STOPUSING\n", (void *)inp);
#else
SCTP_PRINTF("sctp_inpcb_free inp = %p couldn't set to STOPUSING\n", (void *)inp);
#endif
}
inp->ip_inp.inp.inp_socket->so_flags |= SOF_PCBCLEARING;
#endif
/*
* if we have an address list the following will free the list of
* ifaddr's that are set into this ep. Again macro limitations here,
* since the LIST_FOREACH could be a bad idea.
*/
LIST_FOREACH_SAFE(laddr, &inp->sctp_addr_list, sctp_nxt_addr, nladdr) {
sctp_remove_laddr(laddr);
}
#ifdef SCTP_TRACK_FREED_ASOCS
/* TEMP CODE */
LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_free_list, sctp_tcblist, nasoc) {
LIST_REMOVE(asoc, sctp_tcblist);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), asoc);
SCTP_DECR_ASOC_COUNT();
}
/* *** END TEMP CODE ****/
#endif
#ifdef SCTP_MVRF
SCTP_FREE(inp->m_vrf_ids, SCTP_M_MVRF);
#endif
/* Now lets see about freeing the EP hash table. */
if (inp->sctp_tcbhash != NULL) {
SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark);
inp->sctp_tcbhash = NULL;
}
/* Now we must put the ep memory back into the zone pool */
#if defined(__FreeBSD__)
crfree(inp->ip_inp.inp.inp_cred);
INP_LOCK_DESTROY(&inp->ip_inp.inp);
#endif
SCTP_INP_LOCK_DESTROY(inp);
SCTP_INP_READ_DESTROY(inp);
SCTP_ASOC_CREATE_LOCK_DESTROY(inp);
#if !defined(__APPLE__)
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
SCTP_DECR_EP_COUNT();
#else
/* For Tiger, we will do this later... */
#endif
}
struct sctp_nets *
sctp_findnet(struct sctp_tcb *stcb, struct sockaddr *addr)
{
struct sctp_nets *net;
/* locate the address */
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
if (sctp_cmpaddr(addr, (struct sockaddr *)&net->ro._l_addr))
return (net);
}
return (NULL);
}
int
sctp_is_address_on_local_host(struct sockaddr *addr, uint32_t vrf_id)
{
#ifdef __Panda__
return (0);
#else
struct sctp_ifa *sctp_ifa;
sctp_ifa = sctp_find_ifa_by_addr(addr, vrf_id, SCTP_ADDR_NOT_LOCKED);
if (sctp_ifa) {
return (1);
} else {
return (0);
}
#endif
}
/*
* add's a remote endpoint address, done with the INIT/INIT-ACK as well as
* when a ASCONF arrives that adds it. It will also initialize all the cwnd
* stats of stuff.
*/
int
sctp_add_remote_addr(struct sctp_tcb *stcb, struct sockaddr *newaddr,
struct sctp_nets **netp, uint16_t port, int set_scope, int from)
{
/*
* The following is redundant to the same lines in the
* sctp_aloc_assoc() but is needed since others call the add
* address function
*/
struct sctp_nets *net, *netfirst;
int addr_inscope;
SCTPDBG(SCTP_DEBUG_PCB1, "Adding an address (from:%d) to the peer: ",
from);
SCTPDBG_ADDR(SCTP_DEBUG_PCB1, newaddr);
netfirst = sctp_findnet(stcb, newaddr);
if (netfirst) {
/*
* Lie and return ok, we don't want to make the association
* go away for this behavior. It will happen in the TCP
* model in a connected socket. It does not reach the hash
* table until after the association is built so it can't be
* found. Mark as reachable, since the initial creation will
* have been cleared and the NOT_IN_ASSOC flag will have
* been added... and we don't want to end up removing it
* back out.
*/
if (netfirst->dest_state & SCTP_ADDR_UNCONFIRMED) {
netfirst->dest_state = (SCTP_ADDR_REACHABLE |
SCTP_ADDR_UNCONFIRMED);
} else {
netfirst->dest_state = SCTP_ADDR_REACHABLE;
}
return (0);
}
addr_inscope = 1;
switch (newaddr->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin;
sin = (struct sockaddr_in *)newaddr;
if (sin->sin_addr.s_addr == 0) {
/* Invalid address */
return (-1);
}
/* zero out the zero area */
memset(&sin->sin_zero, 0, sizeof(sin->sin_zero));
/* assure len is set */
#ifdef HAVE_SIN_LEN
sin->sin_len = sizeof(struct sockaddr_in);
#endif
if (set_scope) {
if (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
stcb->asoc.scope.ipv4_local_scope = 1;
}
} else {
/* Validate the address is in scope */
if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) &&
(stcb->asoc.scope.ipv4_local_scope == 0)) {
addr_inscope = 0;
}
}
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)newaddr;
if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
/* Invalid address */
return (-1);
}
/* assure len is set */
#ifdef HAVE_SIN6_LEN
sin6->sin6_len = sizeof(struct sockaddr_in6);
#endif
if (set_scope) {
if (sctp_is_address_on_local_host(newaddr, stcb->asoc.vrf_id)) {
stcb->asoc.scope.loopback_scope = 1;
stcb->asoc.scope.local_scope = 0;
stcb->asoc.scope.ipv4_local_scope = 1;
stcb->asoc.scope.site_scope = 1;
} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
/*
* If the new destination is a LINK_LOCAL we
* must have common site scope. Don't set
* the local scope since we may not share
* all links, only loopback can do this.
* Links on the local network would also be
* on our private network for v4 too.
*/
stcb->asoc.scope.ipv4_local_scope = 1;
stcb->asoc.scope.site_scope = 1;
} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr)) {
/*
* If the new destination is SITE_LOCAL then
* we must have site scope in common.
*/
stcb->asoc.scope.site_scope = 1;
}
} else {
/* Validate the address is in scope */
if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr) &&
(stcb->asoc.scope.loopback_scope == 0)) {
addr_inscope = 0;
} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) &&
(stcb->asoc.scope.local_scope == 0)) {
addr_inscope = 0;
} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr) &&
(stcb->asoc.scope.site_scope == 0)) {
addr_inscope = 0;
}
}
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
{
struct sockaddr_conn *sconn;
sconn = (struct sockaddr_conn *)newaddr;
if (sconn->sconn_addr == NULL) {
/* Invalid address */
return (-1);
}
#ifdef HAVE_SCONN_LEN
sconn->sconn_len = sizeof(struct sockaddr_conn);
#endif
break;
}
#endif
default:
/* not supported family type */
return (-1);
}
net = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_net), struct sctp_nets);
if (net == NULL) {
return (-1);
}
SCTP_INCR_RADDR_COUNT();
memset(net, 0, sizeof(struct sctp_nets));
(void)SCTP_GETTIME_TIMEVAL(&net->start_time);
#ifdef HAVE_SA_LEN
memcpy(&net->ro._l_addr, newaddr, newaddr->sa_len);
#endif
switch (newaddr->sa_family) {
#ifdef INET
case AF_INET:
#ifndef HAVE_SA_LEN
memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_in));
#endif
((struct sockaddr_in *)&net->ro._l_addr)->sin_port = stcb->rport;
break;
#endif
#ifdef INET6
case AF_INET6:
#ifndef HAVE_SA_LEN
memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_in6));
#endif
((struct sockaddr_in6 *)&net->ro._l_addr)->sin6_port = stcb->rport;
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
#ifndef HAVE_SA_LEN
memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_conn));
#endif
((struct sockaddr_conn *)&net->ro._l_addr)->sconn_port = stcb->rport;
break;
#endif
default:
break;
}
net->addr_is_local = sctp_is_address_on_local_host(newaddr, stcb->asoc.vrf_id);
if (net->addr_is_local && ((set_scope || (from == SCTP_ADDR_IS_CONFIRMED)))) {
stcb->asoc.scope.loopback_scope = 1;
stcb->asoc.scope.ipv4_local_scope = 1;
stcb->asoc.scope.local_scope = 0;
stcb->asoc.scope.site_scope = 1;
addr_inscope = 1;
}
net->failure_threshold = stcb->asoc.def_net_failure;
net->pf_threshold = stcb->asoc.def_net_pf_threshold;
if (addr_inscope == 0) {
net->dest_state = (SCTP_ADDR_REACHABLE |
SCTP_ADDR_OUT_OF_SCOPE);
} else {
if (from == SCTP_ADDR_IS_CONFIRMED)
/* SCTP_ADDR_IS_CONFIRMED is passed by connect_x */
net->dest_state = SCTP_ADDR_REACHABLE;
else
net->dest_state = SCTP_ADDR_REACHABLE |
SCTP_ADDR_UNCONFIRMED;
}
/* We set this to 0, the timer code knows that
* this means its an initial value
*/
net->rto_needed = 1;
net->RTO = 0;
net->RTO_measured = 0;
stcb->asoc.numnets++;
net->ref_count = 1;
net->cwr_window_tsn = net->last_cwr_tsn = stcb->asoc.sending_seq - 1;
net->port = port;
net->dscp = stcb->asoc.default_dscp;
#ifdef INET6
net->flowlabel = stcb->asoc.default_flowlabel;
#endif
if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_DONOT_HEARTBEAT)) {
net->dest_state |= SCTP_ADDR_NOHB;
} else {
net->dest_state &= ~SCTP_ADDR_NOHB;
}
if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_DO_NOT_PMTUD)) {
net->dest_state |= SCTP_ADDR_NO_PMTUD;
} else {
net->dest_state &= ~SCTP_ADDR_NO_PMTUD;
}
net->heart_beat_delay = stcb->asoc.heart_beat_delay;
/* Init the timer structure */
SCTP_OS_TIMER_INIT(&net->rxt_timer.timer);
SCTP_OS_TIMER_INIT(&net->pmtu_timer.timer);
SCTP_OS_TIMER_INIT(&net->hb_timer.timer);
/* Now generate a route for this guy */
#ifdef INET6
#ifdef SCTP_EMBEDDED_V6_SCOPE
/* KAME hack: embed scopeid */
if (newaddr->sa_family == AF_INET6) {
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
#if defined(__APPLE__)
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
(void)in6_embedscope(&sin6->sin6_addr, sin6, &stcb->sctp_ep->ip_inp.inp, NULL);
#else
(void)in6_embedscope(&sin6->sin6_addr, sin6, &stcb->sctp_ep->ip_inp.inp, NULL, NULL);
#endif
#elif defined(SCTP_KAME)
(void)sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone));
#else
(void)in6_embedscope(&sin6->sin6_addr, sin6);
#endif
#ifndef SCOPEDROUTING
sin6->sin6_scope_id = 0;
#endif
}
#endif /* SCTP_EMBEDDED_V6_SCOPE */
#endif
SCTP_RTALLOC((sctp_route_t *)&net->ro,
stcb->asoc.vrf_id,
stcb->sctp_ep->fibnum);
net->src_addr_selected = 0;
#if !defined(__Userspace__)
if (SCTP_ROUTE_HAS_VALID_IFN(&net->ro)) {
/* Get source address */
net->ro._s_addr = sctp_source_address_selection(stcb->sctp_ep,
stcb,
(sctp_route_t *)&net->ro,
net,
0,
stcb->asoc.vrf_id);
if (stcb->asoc.default_mtu > 0) {
net->mtu = stcb->asoc.default_mtu;
switch (net->ro._l_addr.sa.sa_family) {
#ifdef INET
case AF_INET:
net->mtu += SCTP_MIN_V4_OVERHEAD;
break;
#endif
#ifdef INET6
case AF_INET6:
net->mtu += SCTP_MIN_OVERHEAD;
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
net->mtu += sizeof(struct sctphdr);
break;
#endif
default:
break;
}
#if defined(INET) || defined(INET6)
if (net->port) {
net->mtu += (uint32_t)sizeof(struct udphdr);
}
#endif
} else if (net->ro._s_addr != NULL) {
uint32_t imtu, rmtu, hcmtu;
net->src_addr_selected = 1;
/* Now get the interface MTU */
if (net->ro._s_addr->ifn_p != NULL) {
imtu = SCTP_GATHER_MTU_FROM_INTFC(net->ro._s_addr->ifn_p);
} else {
imtu = 0;
}
rmtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, net->ro.ro_rt);
#if defined(__FreeBSD__)
hcmtu = sctp_hc_get_mtu(&net->ro._l_addr, stcb->sctp_ep->fibnum);
#else
hcmtu = 0;
#endif
net->mtu = sctp_min_mtu(hcmtu, rmtu, imtu);
if (rmtu == 0) {
/* Start things off to match mtu of interface please. */
SCTP_SET_MTU_OF_ROUTE(&net->ro._l_addr.sa,
net->ro.ro_rt, net->mtu);
}
}
}
#endif
if (net->mtu == 0) {
if (stcb->asoc.default_mtu > 0) {
net->mtu = stcb->asoc.default_mtu;
switch (net->ro._l_addr.sa.sa_family) {
#ifdef INET
case AF_INET:
net->mtu += SCTP_MIN_V4_OVERHEAD;
break;
#endif
#ifdef INET6
case AF_INET6:
net->mtu += SCTP_MIN_OVERHEAD;
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
net->mtu += sizeof(struct sctphdr);
break;
#endif
default:
break;
}
#if defined(INET) || defined(INET6)
if (net->port) {
net->mtu += (uint32_t)sizeof(struct udphdr);
}
#endif
} else {
switch (newaddr->sa_family) {
#ifdef INET
case AF_INET:
net->mtu = SCTP_DEFAULT_MTU;
break;
#endif
#ifdef INET6
case AF_INET6:
net->mtu = 1280;
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
net->mtu = 1280;
break;
#endif
default:
break;
}
}
}
#if defined(INET) || defined(INET6)
if (net->port) {
net->mtu -= (uint32_t)sizeof(struct udphdr);
}
#endif
if (from == SCTP_ALLOC_ASOC) {
stcb->asoc.smallest_mtu = net->mtu;
}
if (stcb->asoc.smallest_mtu > net->mtu) {
sctp_pathmtu_adjustment(stcb, net->mtu);
}
#ifdef INET6
#ifdef SCTP_EMBEDDED_V6_SCOPE
if (newaddr->sa_family == AF_INET6) {
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
#ifdef SCTP_KAME
(void)sa6_recoverscope(sin6);
#else
(void)in6_recoverscope(sin6, &sin6->sin6_addr, NULL);
#endif /* SCTP_KAME */
}
#endif /* SCTP_EMBEDDED_V6_SCOPE */
#endif
/* JRS - Use the congestion control given in the CC module */
if (stcb->asoc.cc_functions.sctp_set_initial_cc_param != NULL)
(*stcb->asoc.cc_functions.sctp_set_initial_cc_param)(stcb, net);
/*
* CMT: CUC algo - set find_pseudo_cumack to TRUE (1) at beginning
* of assoc (2005/06/27, iyengar@cis.udel.edu)
*/
net->find_pseudo_cumack = 1;
net->find_rtx_pseudo_cumack = 1;
#if defined(__FreeBSD__)
/* Choose an initial flowid. */
net->flowid = stcb->asoc.my_vtag ^
ntohs(stcb->rport) ^
ntohs(stcb->sctp_ep->sctp_lport);
net->flowtype = M_HASHTYPE_OPAQUE_HASH;
#endif
if (netp) {
*netp = net;
}
netfirst = TAILQ_FIRST(&stcb->asoc.nets);
if (net->ro.ro_rt == NULL) {
/* Since we have no route put it at the back */
TAILQ_INSERT_TAIL(&stcb->asoc.nets, net, sctp_next);
} else if (netfirst == NULL) {
/* We are the first one in the pool. */
TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
} else if (netfirst->ro.ro_rt == NULL) {
/*
* First one has NO route. Place this one ahead of the first
* one.
*/
TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
#ifndef __Panda__
} else if (net->ro.ro_rt->rt_ifp != netfirst->ro.ro_rt->rt_ifp) {
/*
* This one has a different interface than the one at the
* top of the list. Place it ahead.
*/
TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
#endif
} else {
/*
* Ok we have the same interface as the first one. Move
* forward until we find either a) one with a NULL route...
* insert ahead of that b) one with a different ifp.. insert
* after that. c) end of the list.. insert at the tail.
*/
struct sctp_nets *netlook;
do {
netlook = TAILQ_NEXT(netfirst, sctp_next);
if (netlook == NULL) {
/* End of the list */
TAILQ_INSERT_TAIL(&stcb->asoc.nets, net, sctp_next);
break;
} else if (netlook->ro.ro_rt == NULL) {
/* next one has NO route */
TAILQ_INSERT_BEFORE(netfirst, net, sctp_next);
break;
}
#ifndef __Panda__
else if (netlook->ro.ro_rt->rt_ifp != net->ro.ro_rt->rt_ifp)
#else
else
#endif
{
TAILQ_INSERT_AFTER(&stcb->asoc.nets, netlook,
net, sctp_next);
break;
}
#ifndef __Panda__
/* Shift forward */
netfirst = netlook;
#endif
} while (netlook != NULL);
}
/* got to have a primary set */
if (stcb->asoc.primary_destination == 0) {
stcb->asoc.primary_destination = net;
} else if ((stcb->asoc.primary_destination->ro.ro_rt == NULL) &&
(net->ro.ro_rt) &&
((net->dest_state & SCTP_ADDR_UNCONFIRMED) == 0)) {
/* No route to current primary adopt new primary */
stcb->asoc.primary_destination = net;
}
/* Validate primary is first */
net = TAILQ_FIRST(&stcb->asoc.nets);
if ((net != stcb->asoc.primary_destination) &&
(stcb->asoc.primary_destination)) {
/* first one on the list is NOT the primary
* sctp_cmpaddr() is much more efficient if
* the primary is the first on the list, make it
* so.
*/
TAILQ_REMOVE(&stcb->asoc.nets,
stcb->asoc.primary_destination, sctp_next);
TAILQ_INSERT_HEAD(&stcb->asoc.nets,
stcb->asoc.primary_destination, sctp_next);
}
return (0);
}
static uint32_t
sctp_aloc_a_assoc_id(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
{
uint32_t id;
struct sctpasochead *head;
struct sctp_tcb *lstcb;
try_again:
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
/* TSNH */
return (0);
}
/*
* We don't allow assoc id to be one of SCTP_FUTURE_ASSOC,
* SCTP_CURRENT_ASSOC and SCTP_ALL_ASSOC.
*/
if (inp->sctp_associd_counter <= SCTP_ALL_ASSOC) {
inp->sctp_associd_counter = SCTP_ALL_ASSOC + 1;
}
id = inp->sctp_associd_counter;
inp->sctp_associd_counter++;
lstcb = sctp_findasoc_ep_asocid_locked(inp, (sctp_assoc_t)id, 0);
if (lstcb) {
goto try_again;
}
head = &inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(id, inp->hashasocidmark)];
LIST_INSERT_HEAD(head, stcb, sctp_tcbasocidhash);
stcb->asoc.in_asocid_hash = 1;
return (id);
}
/*
* allocate an association and add it to the endpoint. The caller must be
* careful to add all additional addresses once they are know right away or
* else the assoc will be may experience a blackout scenario.
*/
struct sctp_tcb *
sctp_aloc_assoc(struct sctp_inpcb *inp, struct sockaddr *firstaddr,
int *error, uint32_t override_tag, uint32_t vrf_id,
uint16_t o_streams, uint16_t port,
#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
struct thread *p,
#elif defined(__Windows__)
PKTHREAD p,
#else
#if defined(__Userspace__)
/* __Userspace__ NULL proc is going to be passed here. See sctp_lower_sosend */
#endif
struct proc *p,
#endif
int initialize_auth_params)
{
/* note the p argument is only valid in unbound sockets */
struct sctp_tcb *stcb;
struct sctp_association *asoc;
struct sctpasochead *head;
uint16_t rport;
int err;
/*
* Assumption made here: Caller has done a
* sctp_findassociation_ep_addr(ep, addr's); to make sure the
* address does not exist already.
*/
if (SCTP_BASE_INFO(ipi_count_asoc) >= SCTP_MAX_NUM_OF_ASOC) {
/* Hit max assoc, sorry no more */
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
*error = ENOBUFS;
return (NULL);
}
if (firstaddr == NULL) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
SCTP_INP_RLOCK(inp);
if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) &&
((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_PORTREUSE)) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED))) {
/*
* If its in the TCP pool, its NOT allowed to create an
* association. The parent listener needs to call
* sctp_aloc_assoc.. or the one-2-many socket. If a peeled
* off, or connected one does this.. its an error.
*/
SCTP_INP_RUNLOCK(inp);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE)) {
if ((inp->sctp_flags & SCTP_PCB_FLAGS_WAS_CONNECTED) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_WAS_ABORTED)) {
SCTP_INP_RUNLOCK(inp);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
}
SCTPDBG(SCTP_DEBUG_PCB3, "Allocate an association for peer:");
#ifdef SCTP_DEBUG
if (firstaddr) {
SCTPDBG_ADDR(SCTP_DEBUG_PCB3, firstaddr);
switch (firstaddr->sa_family) {
#ifdef INET
case AF_INET:
SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n",
ntohs(((struct sockaddr_in *)firstaddr)->sin_port));
break;
#endif
#ifdef INET6
case AF_INET6:
SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n",
ntohs(((struct sockaddr_in6 *)firstaddr)->sin6_port));
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n",
ntohs(((struct sockaddr_conn *)firstaddr)->sconn_port));
break;
#endif
default:
break;
}
} else {
SCTPDBG(SCTP_DEBUG_PCB3,"None\n");
}
#endif /* SCTP_DEBUG */
switch (firstaddr->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin;
sin = (struct sockaddr_in *)firstaddr;
if ((ntohs(sin->sin_port) == 0) ||
(sin->sin_addr.s_addr == INADDR_ANY) ||
(sin->sin_addr.s_addr == INADDR_BROADCAST) ||
IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
/* Invalid address */
SCTP_INP_RUNLOCK(inp);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
rport = sin->sin_port;
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)firstaddr;
if ((ntohs(sin6->sin6_port) == 0) ||
IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) ||
IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
/* Invalid address */
SCTP_INP_RUNLOCK(inp);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
rport = sin6->sin6_port;
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
{
struct sockaddr_conn *sconn;
sconn = (struct sockaddr_conn *)firstaddr;
if ((ntohs(sconn->sconn_port) == 0) ||
(sconn->sconn_addr == NULL)) {
/* Invalid address */
SCTP_INP_RUNLOCK(inp);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
rport = sconn->sconn_port;
break;
}
#endif
default:
/* not supported family type */
SCTP_INP_RUNLOCK(inp);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
SCTP_INP_RUNLOCK(inp);
if (inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) {
/*
* If you have not performed a bind, then we need to do the
* ephemeral bind for you.
*/
if ((err = sctp_inpcb_bind(inp->sctp_socket,
(struct sockaddr *)NULL,
(struct sctp_ifa *)NULL,
#ifndef __Panda__
p
#else
(struct proc *)NULL
#endif
))) {
/* bind error, probably perm */
*error = err;
return (NULL);
}
}
stcb = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_asoc), struct sctp_tcb);
if (stcb == NULL) {
/* out of memory? */
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM);
*error = ENOMEM;
return (NULL);
}
SCTP_INCR_ASOC_COUNT();
memset(stcb, 0, sizeof(*stcb));
asoc = &stcb->asoc;
SCTP_TCB_LOCK_INIT(stcb);
SCTP_TCB_SEND_LOCK_INIT(stcb);
stcb->rport = rport;
/* setup back pointer's */
stcb->sctp_ep = inp;
stcb->sctp_socket = inp->sctp_socket;
if ((err = sctp_init_asoc(inp, stcb, override_tag, vrf_id, o_streams))) {
/* failed */
SCTP_TCB_LOCK_DESTROY(stcb);
SCTP_TCB_SEND_LOCK_DESTROY(stcb);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
SCTP_DECR_ASOC_COUNT();
*error = err;
return (NULL);
}
/* and the port */
SCTP_INP_INFO_WLOCK();
SCTP_INP_WLOCK(inp);
if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE | SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
/* inpcb freed while alloc going on */
SCTP_TCB_LOCK_DESTROY(stcb);
SCTP_TCB_SEND_LOCK_DESTROY(stcb);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_DECR_ASOC_COUNT();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
SCTP_TCB_LOCK(stcb);
asoc->assoc_id = sctp_aloc_a_assoc_id(inp, stcb);
/* now that my_vtag is set, add it to the hash */
head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(stcb->asoc.my_vtag, SCTP_BASE_INFO(hashasocmark))];
/* put it in the bucket in the vtag hash of assoc's for the system */
LIST_INSERT_HEAD(head, stcb, sctp_asocs);
SCTP_INP_INFO_WUNLOCK();
if ((err = sctp_add_remote_addr(stcb, firstaddr, NULL, port, SCTP_DO_SETSCOPE, SCTP_ALLOC_ASOC))) {
/* failure.. memory error? */
if (asoc->strmout) {
SCTP_FREE(asoc->strmout, SCTP_M_STRMO);
asoc->strmout = NULL;
}
if (asoc->mapping_array) {
SCTP_FREE(asoc->mapping_array, SCTP_M_MAP);
asoc->mapping_array = NULL;
}
if (asoc->nr_mapping_array) {
SCTP_FREE(asoc->nr_mapping_array, SCTP_M_MAP);
asoc->nr_mapping_array = NULL;
}
SCTP_DECR_ASOC_COUNT();
SCTP_TCB_UNLOCK(stcb);
SCTP_TCB_LOCK_DESTROY(stcb);
SCTP_TCB_SEND_LOCK_DESTROY(stcb);
LIST_REMOVE(stcb, sctp_tcbasocidhash);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
SCTP_INP_WUNLOCK(inp);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
*error = ENOBUFS;
return (NULL);
}
/* Init all the timers */
SCTP_OS_TIMER_INIT(&asoc->dack_timer.timer);
SCTP_OS_TIMER_INIT(&asoc->strreset_timer.timer);
SCTP_OS_TIMER_INIT(&asoc->asconf_timer.timer);
SCTP_OS_TIMER_INIT(&asoc->shut_guard_timer.timer);
SCTP_OS_TIMER_INIT(&asoc->autoclose_timer.timer);
SCTP_OS_TIMER_INIT(&asoc->delayed_event_timer.timer);
SCTP_OS_TIMER_INIT(&asoc->delete_prim_timer.timer);
LIST_INSERT_HEAD(&inp->sctp_asoc_list, stcb, sctp_tcblist);
/* now file the port under the hash as well */
if (inp->sctp_tcbhash != NULL) {
head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(stcb->rport,
inp->sctp_hashmark)];
LIST_INSERT_HEAD(head, stcb, sctp_tcbhash);
}
if (initialize_auth_params == SCTP_INITIALIZE_AUTH_PARAMS) {
sctp_initialize_auth_params(inp, stcb);
}
SCTP_INP_WUNLOCK(inp);
SCTPDBG(SCTP_DEBUG_PCB1, "Association %p now allocated\n", (void *)stcb);
return (stcb);
}
void
sctp_remove_net(struct sctp_tcb *stcb, struct sctp_nets *net)
{
struct sctp_association *asoc;
asoc = &stcb->asoc;
asoc->numnets--;
TAILQ_REMOVE(&asoc->nets, net, sctp_next);
if (net == asoc->primary_destination) {
/* Reset primary */
struct sctp_nets *lnet;
lnet = TAILQ_FIRST(&asoc->nets);
/* Mobility adaptation
Ideally, if deleted destination is the primary, it becomes
a fast retransmission trigger by the subsequent SET PRIMARY.
(by micchie)
*/
if (sctp_is_mobility_feature_on(stcb->sctp_ep,
SCTP_MOBILITY_BASE) ||
sctp_is_mobility_feature_on(stcb->sctp_ep,
SCTP_MOBILITY_FASTHANDOFF)) {
SCTPDBG(SCTP_DEBUG_ASCONF1, "remove_net: primary dst is deleting\n");
if (asoc->deleted_primary != NULL) {
SCTPDBG(SCTP_DEBUG_ASCONF1, "remove_net: deleted primary may be already stored\n");
goto out;
}
asoc->deleted_primary = net;
atomic_add_int(&net->ref_count, 1);
memset(&net->lastsa, 0, sizeof(net->lastsa));
memset(&net->lastsv, 0, sizeof(net->lastsv));
sctp_mobility_feature_on(stcb->sctp_ep,
SCTP_MOBILITY_PRIM_DELETED);
sctp_timer_start(SCTP_TIMER_TYPE_PRIM_DELETED,
stcb->sctp_ep, stcb, NULL);
}
out:
/* Try to find a confirmed primary */
asoc->primary_destination = sctp_find_alternate_net(stcb, lnet, 0);
}
if (net == asoc->last_data_chunk_from) {
/* Reset primary */
asoc->last_data_chunk_from = TAILQ_FIRST(&asoc->nets);
}
if (net == asoc->last_control_chunk_from) {
/* Clear net */
asoc->last_control_chunk_from = NULL;
}
if (net == stcb->asoc.alternate) {
sctp_free_remote_addr(stcb->asoc.alternate);
stcb->asoc.alternate = NULL;
}
sctp_free_remote_addr(net);
}
/*
* remove a remote endpoint address from an association, it will fail if the
* address does not exist.
*/
int
sctp_del_remote_addr(struct sctp_tcb *stcb, struct sockaddr *remaddr)
{
/*
* Here we need to remove a remote address. This is quite simple, we
* first find it in the list of address for the association
* (tasoc->asoc.nets) and then if it is there, we do a LIST_REMOVE
* on that item. Note we do not allow it to be removed if there are
* no other addresses.
*/
struct sctp_association *asoc;
struct sctp_nets *net, *nnet;
asoc = &stcb->asoc;
/* locate the address */
TAILQ_FOREACH_SAFE(net, &asoc->nets, sctp_next, nnet) {
if (net->ro._l_addr.sa.sa_family != remaddr->sa_family) {
continue;
}
if (sctp_cmpaddr((struct sockaddr *)&net->ro._l_addr,
remaddr)) {
/* we found the guy */
if (asoc->numnets < 2) {
/* Must have at LEAST two remote addresses */
return (-1);
} else {
sctp_remove_net(stcb, net);
return (0);
}
}
}
/* not found. */
return (-2);
}
void
sctp_delete_from_timewait(uint32_t tag, uint16_t lport, uint16_t rport)
{
struct sctpvtaghead *chain;
struct sctp_tagblock *twait_block;
int found = 0;
int i;
chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
if ((twait_block->vtag_block[i].v_tag == tag) &&
(twait_block->vtag_block[i].lport == lport) &&
(twait_block->vtag_block[i].rport == rport)) {
twait_block->vtag_block[i].tv_sec_at_expire = 0;
twait_block->vtag_block[i].v_tag = 0;
twait_block->vtag_block[i].lport = 0;
twait_block->vtag_block[i].rport = 0;
found = 1;
break;
}
}
if (found)
break;
}
}
int
sctp_is_in_timewait(uint32_t tag, uint16_t lport, uint16_t rport)
{
struct sctpvtaghead *chain;
struct sctp_tagblock *twait_block;
int found = 0;
int i;
SCTP_INP_INFO_WLOCK();
chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
if ((twait_block->vtag_block[i].v_tag == tag) &&
(twait_block->vtag_block[i].lport == lport) &&
(twait_block->vtag_block[i].rport == rport)) {
found = 1;
break;
}
}
if (found)
break;
}
SCTP_INP_INFO_WUNLOCK();
return (found);
}
void
sctp_add_vtag_to_timewait(uint32_t tag, uint32_t time, uint16_t lport, uint16_t rport)
{
struct sctpvtaghead *chain;
struct sctp_tagblock *twait_block;
struct timeval now;
int set, i;
if (time == 0) {
/* Its disabled */
return;
}
(void)SCTP_GETTIME_TIMEVAL(&now);
chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
set = 0;
LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
/* Block(s) present, lets find space, and expire on the fly */
for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
if ((twait_block->vtag_block[i].v_tag == 0) &&
!set) {
twait_block->vtag_block[i].tv_sec_at_expire =
now.tv_sec + time;
twait_block->vtag_block[i].v_tag = tag;
twait_block->vtag_block[i].lport = lport;
twait_block->vtag_block[i].rport = rport;
set = 1;
} else if ((twait_block->vtag_block[i].v_tag) &&
((long)twait_block->vtag_block[i].tv_sec_at_expire < now.tv_sec)) {
/* Audit expires this guy */
twait_block->vtag_block[i].tv_sec_at_expire = 0;
twait_block->vtag_block[i].v_tag = 0;
twait_block->vtag_block[i].lport = 0;
twait_block->vtag_block[i].rport = 0;
if (set == 0) {
/* Reuse it for my new tag */
twait_block->vtag_block[i].tv_sec_at_expire = now.tv_sec + time;
twait_block->vtag_block[i].v_tag = tag;
twait_block->vtag_block[i].lport = lport;
twait_block->vtag_block[i].rport = rport;
set = 1;
}
}
}
if (set) {
/*
* We only do up to the block where we can
* place our tag for audits
*/
break;
}
}
/* Need to add a new block to chain */
if (!set) {
SCTP_MALLOC(twait_block, struct sctp_tagblock *,
sizeof(struct sctp_tagblock), SCTP_M_TIMW);
if (twait_block == NULL) {
#ifdef INVARIANTS
panic("Can not alloc tagblock");
#endif
return;
}
memset(twait_block, 0, sizeof(struct sctp_tagblock));
LIST_INSERT_HEAD(chain, twait_block, sctp_nxt_tagblock);
twait_block->vtag_block[0].tv_sec_at_expire = now.tv_sec + time;
twait_block->vtag_block[0].v_tag = tag;
twait_block->vtag_block[0].lport = lport;
twait_block->vtag_block[0].rport = rport;
}
}
void
sctp_clean_up_stream(struct sctp_tcb *stcb, struct sctp_readhead *rh)
{
struct sctp_tmit_chunk *chk, *nchk;
struct sctp_queued_to_read *control, *ncontrol;
TAILQ_FOREACH_SAFE(control, rh, next_instrm, ncontrol) {
TAILQ_REMOVE(rh, control, next_instrm);
control->on_strm_q = 0;
if (control->on_read_q == 0) {
sctp_free_remote_addr(control->whoFrom);
if (control->data) {
sctp_m_freem(control->data);
control->data = NULL;
}
}
/* Reassembly free? */
TAILQ_FOREACH_SAFE(chk, &control->reasm, sctp_next, nchk) {
TAILQ_REMOVE(&control->reasm, chk, sctp_next);
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
if (chk->holds_key_ref)
sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
sctp_free_remote_addr(chk->whoTo);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
SCTP_DECR_CHK_COUNT();
/*sa_ignore FREED_MEMORY*/
}
/*
* We don't free the address here
* since all the net's were freed
* above.
*/
if (control->on_read_q == 0) {
sctp_free_a_readq(stcb, control);
}
}
}
#ifdef __Panda__
void panda_wakeup_socket(struct socket *so);
#endif
/*-
* Free the association after un-hashing the remote port. This
* function ALWAYS returns holding NO LOCK on the stcb. It DOES
* expect that the input to this function IS a locked TCB.
* It will return 0, if it did NOT destroy the association (instead
* it unlocks it. It will return NON-zero if it either destroyed the
* association OR the association is already destroyed.
*/
int
sctp_free_assoc(struct sctp_inpcb *inp, struct sctp_tcb *stcb, int from_inpcbfree, int from_location)
{
int i;
struct sctp_association *asoc;
struct sctp_nets *net, *nnet;
struct sctp_laddr *laddr, *naddr;
struct sctp_tmit_chunk *chk, *nchk;
struct sctp_asconf_addr *aparam, *naparam;
struct sctp_asconf_ack *aack, *naack;
struct sctp_stream_reset_list *strrst, *nstrrst;
struct sctp_queued_to_read *sq, *nsq;
struct sctp_stream_queue_pending *sp, *nsp;
sctp_sharedkey_t *shared_key, *nshared_key;
struct socket *so;
/* first, lets purge the entry from the hash table. */
#if defined(__APPLE__)
sctp_lock_assert(SCTP_INP_SO(inp));
#endif
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, stcb, 6);
#endif
if (stcb->asoc.state == 0) {
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 7);
#endif
/* there is no asoc, really TSNH :-0 */
return (1);
}
if (stcb->asoc.alternate) {
sctp_free_remote_addr(stcb->asoc.alternate);
stcb->asoc.alternate = NULL;
}
#if !defined(__APPLE__) /* TEMP: moved to below */
/* TEMP CODE */
if (stcb->freed_from_where == 0) {
/* Only record the first place free happened from */
stcb->freed_from_where = from_location;
}
/* TEMP CODE */
#endif
asoc = &stcb->asoc;
if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
/* nothing around */
so = NULL;
else
so = inp->sctp_socket;
/*
* We used timer based freeing if a reader or writer is in the way.
* So we first check if we are actually being called from a timer,
* if so we abort early if a reader or writer is still in the way.
*/
if ((stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) &&
(from_inpcbfree == SCTP_NORMAL_PROC)) {
/*
* is it the timer driving us? if so are the reader/writers
* gone?
*/
if (stcb->asoc.refcnt) {
/* nope, reader or writer in the way */
sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
/* no asoc destroyed */
SCTP_TCB_UNLOCK(stcb);
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, stcb, 8);
#endif
return (0);
}
}
/* now clean up any other timers */
(void)SCTP_OS_TIMER_STOP(&asoc->dack_timer.timer);
asoc->dack_timer.self = NULL;
(void)SCTP_OS_TIMER_STOP(&asoc->strreset_timer.timer);
/*-
* For stream reset we don't blast this unless
* it is a str-reset timer, it might be the
* free-asoc timer which we DON'T want to
* disturb.
*/
if (asoc->strreset_timer.type == SCTP_TIMER_TYPE_STRRESET)
asoc->strreset_timer.self = NULL;
(void)SCTP_OS_TIMER_STOP(&asoc->asconf_timer.timer);
asoc->asconf_timer.self = NULL;
(void)SCTP_OS_TIMER_STOP(&asoc->autoclose_timer.timer);
asoc->autoclose_timer.self = NULL;
(void)SCTP_OS_TIMER_STOP(&asoc->shut_guard_timer.timer);
asoc->shut_guard_timer.self = NULL;
(void)SCTP_OS_TIMER_STOP(&asoc->delayed_event_timer.timer);
asoc->delayed_event_timer.self = NULL;
/* Mobility adaptation */
(void)SCTP_OS_TIMER_STOP(&asoc->delete_prim_timer.timer);
asoc->delete_prim_timer.self = NULL;
TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
(void)SCTP_OS_TIMER_STOP(&net->rxt_timer.timer);
net->rxt_timer.self = NULL;
(void)SCTP_OS_TIMER_STOP(&net->pmtu_timer.timer);
net->pmtu_timer.self = NULL;
(void)SCTP_OS_TIMER_STOP(&net->hb_timer.timer);
net->hb_timer.self = NULL;
}
/* Now the read queue needs to be cleaned up (only once) */
if ((stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) == 0) {
SCTP_ADD_SUBSTATE(stcb, SCTP_STATE_ABOUT_TO_BE_FREED);
SCTP_INP_READ_LOCK(inp);
TAILQ_FOREACH(sq, &inp->read_queue, next) {
if (sq->stcb == stcb) {
sq->do_not_ref_stcb = 1;
sq->sinfo_cumtsn = stcb->asoc.cumulative_tsn;
/* If there is no end, there never
* will be now.
*/
if (sq->end_added == 0) {
/* Held for PD-API clear that. */
sq->pdapi_aborted = 1;
sq->held_length = 0;
if (sctp_stcb_is_feature_on(inp, stcb, SCTP_PCB_FLAGS_PDAPIEVNT) && (so != NULL)) {
/*
* Need to add a PD-API aborted indication.
* Setting the control_pdapi assures that it will
* be added right after this msg.
*/
uint32_t strseq;
stcb->asoc.control_pdapi = sq;
strseq = (sq->sinfo_stream << 16) | (sq->mid & 0x0000ffff);
sctp_ulp_notify(SCTP_NOTIFY_PARTIAL_DELVIERY_INDICATION,
stcb,
SCTP_PARTIAL_DELIVERY_ABORTED,
(void *)&strseq,
SCTP_SO_LOCKED);
stcb->asoc.control_pdapi = NULL;
}
}
/* Add an end to wake them */
sq->end_added = 1;
}
}
SCTP_INP_READ_UNLOCK(inp);
if (stcb->block_entry) {
SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_PCB, ECONNRESET);
stcb->block_entry->error = ECONNRESET;
stcb->block_entry = NULL;
}
}
if ((stcb->asoc.refcnt) || (stcb->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE)) {
/* Someone holds a reference OR the socket is unaccepted yet.
*/
if ((stcb->asoc.refcnt) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
SCTP_CLEAR_SUBSTATE(stcb, SCTP_STATE_IN_ACCEPT_QUEUE);
sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
}
SCTP_TCB_UNLOCK(stcb);
if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
/* nothing around */
so = NULL;
if (so) {
/* Wake any reader/writers */
sctp_sorwakeup(inp, so);
sctp_sowwakeup(inp, so);
}
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, stcb, 9);
#endif
/* no asoc destroyed */
return (0);
}
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, stcb, 10);
#endif
/* When I reach here, no others want
* to kill the assoc yet.. and I own
* the lock. Now its possible an abort
* comes in when I do the lock exchange
* below to grab all the locks to do
* the final take out. to prevent this
* we increment the count, which will
* start a timer and blow out above thus
* assuring us that we hold exclusive
* killing of the asoc. Note that
* after getting back the TCB lock
* we will go ahead and increment the
* counter back up and stop any timer
* a passing stranger may have started :-S
*/
if (from_inpcbfree == SCTP_NORMAL_PROC) {
atomic_add_int(&stcb->asoc.refcnt, 1);
SCTP_TCB_UNLOCK(stcb);
SCTP_INP_INFO_WLOCK();
SCTP_INP_WLOCK(inp);
SCTP_TCB_LOCK(stcb);
}
/* Double check the GONE flag */
if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
/* nothing around */
so = NULL;
if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
/*
* For TCP type we need special handling when we are
* connected. We also include the peel'ed off ones to.
*/
if (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) {
inp->sctp_flags &= ~SCTP_PCB_FLAGS_CONNECTED;
inp->sctp_flags |= SCTP_PCB_FLAGS_WAS_CONNECTED;
if (so) {
SOCKBUF_LOCK(&so->so_rcv);
so->so_state &= ~(SS_ISCONNECTING |
SS_ISDISCONNECTING |
SS_ISCONFIRMING |
SS_ISCONNECTED);
so->so_state |= SS_ISDISCONNECTED;
#if defined(__APPLE__)
socantrcvmore(so);
#else
socantrcvmore_locked(so);
#endif
socantsendmore(so);
sctp_sowwakeup(inp, so);
sctp_sorwakeup(inp, so);
SCTP_SOWAKEUP(so);
}
}
}
/* Make it invalid too, that way if its
* about to run it will abort and return.
*/
/* re-increment the lock */
if (from_inpcbfree == SCTP_NORMAL_PROC) {
atomic_add_int(&stcb->asoc.refcnt, -1);
}
if (stcb->asoc.refcnt) {
SCTP_CLEAR_SUBSTATE(stcb, SCTP_STATE_IN_ACCEPT_QUEUE);
sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
if (from_inpcbfree == SCTP_NORMAL_PROC) {
SCTP_INP_INFO_WUNLOCK();
SCTP_INP_WUNLOCK(inp);
}
SCTP_TCB_UNLOCK(stcb);
return (0);
}
asoc->state = 0;
if (inp->sctp_tcbhash) {
LIST_REMOVE(stcb, sctp_tcbhash);
}
if (stcb->asoc.in_asocid_hash) {
LIST_REMOVE(stcb, sctp_tcbasocidhash);
}
/* Now lets remove it from the list of ALL associations in the EP */
LIST_REMOVE(stcb, sctp_tcblist);
if (from_inpcbfree == SCTP_NORMAL_PROC) {
SCTP_INP_INCR_REF(inp);
SCTP_INP_WUNLOCK(inp);
}
/* pull from vtag hash */
LIST_REMOVE(stcb, sctp_asocs);
sctp_add_vtag_to_timewait(asoc->my_vtag, SCTP_BASE_SYSCTL(sctp_vtag_time_wait),
inp->sctp_lport, stcb->rport);
/* Now restop the timers to be sure
* this is paranoia at is finest!
*/
(void)SCTP_OS_TIMER_STOP(&asoc->strreset_timer.timer);
(void)SCTP_OS_TIMER_STOP(&asoc->dack_timer.timer);
(void)SCTP_OS_TIMER_STOP(&asoc->strreset_timer.timer);
(void)SCTP_OS_TIMER_STOP(&asoc->asconf_timer.timer);
(void)SCTP_OS_TIMER_STOP(&asoc->shut_guard_timer.timer);
(void)SCTP_OS_TIMER_STOP(&asoc->autoclose_timer.timer);
(void)SCTP_OS_TIMER_STOP(&asoc->delayed_event_timer.timer);
TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
(void)SCTP_OS_TIMER_STOP(&net->rxt_timer.timer);
(void)SCTP_OS_TIMER_STOP(&net->pmtu_timer.timer);
(void)SCTP_OS_TIMER_STOP(&net->hb_timer.timer);
}
asoc->strreset_timer.type = SCTP_TIMER_TYPE_NONE;
/*
* The chunk lists and such SHOULD be empty but we check them just
* in case.
*/
/* anything on the wheel needs to be removed */
SCTP_TCB_SEND_LOCK(stcb);
for (i = 0; i < asoc->streamoutcnt; i++) {
struct sctp_stream_out *outs;
outs = &asoc->strmout[i];
/* now clean up any chunks here */
TAILQ_FOREACH_SAFE(sp, &outs->outqueue, next, nsp) {
atomic_subtract_int(&asoc->stream_queue_cnt, 1);
TAILQ_REMOVE(&outs->outqueue, sp, next);
stcb->asoc.ss_functions.sctp_ss_remove_from_stream(stcb, asoc, outs, sp, 1);
sctp_free_spbufspace(stcb, asoc, sp);
if (sp->data) {
if (so) {
/* Still an open socket - report */
sctp_ulp_notify(SCTP_NOTIFY_SPECIAL_SP_FAIL, stcb,
0, (void *)sp, SCTP_SO_LOCKED);
}
if (sp->data) {
sctp_m_freem(sp->data);
sp->data = NULL;
sp->tail_mbuf = NULL;
sp->length = 0;
}
}
if (sp->net) {
sctp_free_remote_addr(sp->net);
sp->net = NULL;
}
sctp_free_a_strmoq(stcb, sp, SCTP_SO_LOCKED);
}
}
SCTP_TCB_SEND_UNLOCK(stcb);
/*sa_ignore FREED_MEMORY*/
TAILQ_FOREACH_SAFE(strrst, &asoc->resetHead, next_resp, nstrrst) {
TAILQ_REMOVE(&asoc->resetHead, strrst, next_resp);
SCTP_FREE(strrst, SCTP_M_STRESET);
}
TAILQ_FOREACH_SAFE(sq, &asoc->pending_reply_queue, next, nsq) {
TAILQ_REMOVE(&asoc->pending_reply_queue, sq, next);
if (sq->data) {
sctp_m_freem(sq->data);
sq->data = NULL;
}
sctp_free_remote_addr(sq->whoFrom);
sq->whoFrom = NULL;
sq->stcb = NULL;
/* Free the ctl entry */
sctp_free_a_readq(stcb, sq);
/*sa_ignore FREED_MEMORY*/
}
TAILQ_FOREACH_SAFE(chk, &asoc->free_chunks, sctp_next, nchk) {
TAILQ_REMOVE(&asoc->free_chunks, chk, sctp_next);
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
if (chk->holds_key_ref)
sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
SCTP_DECR_CHK_COUNT();
atomic_subtract_int(&SCTP_BASE_INFO(ipi_free_chunks), 1);
asoc->free_chunk_cnt--;
/*sa_ignore FREED_MEMORY*/
}
/* pending send queue SHOULD be empty */
TAILQ_FOREACH_SAFE(chk, &asoc->send_queue, sctp_next, nchk) {
if (asoc->strmout[chk->rec.data.sid].chunks_on_queues > 0) {
asoc->strmout[chk->rec.data.sid].chunks_on_queues--;
#ifdef INVARIANTS
} else {
panic("No chunks on the queues for sid %u.", chk->rec.data.sid);
#endif
}
TAILQ_REMOVE(&asoc->send_queue, chk, sctp_next);
if (chk->data) {
if (so) {
/* Still a socket? */
sctp_ulp_notify(SCTP_NOTIFY_UNSENT_DG_FAIL, stcb,
0, chk, SCTP_SO_LOCKED);
}
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
}
if (chk->holds_key_ref)
sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
if (chk->whoTo) {
sctp_free_remote_addr(chk->whoTo);
chk->whoTo = NULL;
}
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
SCTP_DECR_CHK_COUNT();
/*sa_ignore FREED_MEMORY*/
}
/* sent queue SHOULD be empty */
TAILQ_FOREACH_SAFE(chk, &asoc->sent_queue, sctp_next, nchk) {
if (chk->sent != SCTP_DATAGRAM_NR_ACKED) {
if (asoc->strmout[chk->rec.data.sid].chunks_on_queues > 0) {
asoc->strmout[chk->rec.data.sid].chunks_on_queues--;
#ifdef INVARIANTS
} else {
panic("No chunks on the queues for sid %u.", chk->rec.data.sid);
#endif
}
}
TAILQ_REMOVE(&asoc->sent_queue, chk, sctp_next);
if (chk->data) {
if (so) {
/* Still a socket? */
sctp_ulp_notify(SCTP_NOTIFY_SENT_DG_FAIL, stcb,
0, chk, SCTP_SO_LOCKED);
}
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
}
if (chk->holds_key_ref)
sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
sctp_free_remote_addr(chk->whoTo);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
SCTP_DECR_CHK_COUNT();
/*sa_ignore FREED_MEMORY*/
}
#ifdef INVARIANTS
for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
if (stcb->asoc.strmout[i].chunks_on_queues > 0) {
panic("%u chunks left for stream %u.", stcb->asoc.strmout[i].chunks_on_queues, i);
}
}
#endif
/* control queue MAY not be empty */
TAILQ_FOREACH_SAFE(chk, &asoc->control_send_queue, sctp_next, nchk) {
TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
if (chk->holds_key_ref)
sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
sctp_free_remote_addr(chk->whoTo);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
SCTP_DECR_CHK_COUNT();
/*sa_ignore FREED_MEMORY*/
}
/* ASCONF queue MAY not be empty */
TAILQ_FOREACH_SAFE(chk, &asoc->asconf_send_queue, sctp_next, nchk) {
TAILQ_REMOVE(&asoc->asconf_send_queue, chk, sctp_next);
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
if (chk->holds_key_ref)
sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
sctp_free_remote_addr(chk->whoTo);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
SCTP_DECR_CHK_COUNT();
/*sa_ignore FREED_MEMORY*/
}
if (asoc->mapping_array) {
SCTP_FREE(asoc->mapping_array, SCTP_M_MAP);
asoc->mapping_array = NULL;
}
if (asoc->nr_mapping_array) {
SCTP_FREE(asoc->nr_mapping_array, SCTP_M_MAP);
asoc->nr_mapping_array = NULL;
}
/* the stream outs */
if (asoc->strmout) {
SCTP_FREE(asoc->strmout, SCTP_M_STRMO);
asoc->strmout = NULL;
}
asoc->strm_realoutsize = asoc->streamoutcnt = 0;
if (asoc->strmin) {
for (i = 0; i < asoc->streamincnt; i++) {
sctp_clean_up_stream(stcb, &asoc->strmin[i].inqueue);
sctp_clean_up_stream(stcb, &asoc->strmin[i].uno_inqueue);
}
SCTP_FREE(asoc->strmin, SCTP_M_STRMI);
asoc->strmin = NULL;
}
asoc->streamincnt = 0;
TAILQ_FOREACH_SAFE(net, &asoc->nets, sctp_next, nnet) {
#ifdef INVARIANTS
if (SCTP_BASE_INFO(ipi_count_raddr) == 0) {
panic("no net's left alloc'ed, or list points to itself");
}
#endif
TAILQ_REMOVE(&asoc->nets, net, sctp_next);
sctp_free_remote_addr(net);
}
LIST_FOREACH_SAFE(laddr, &asoc->sctp_restricted_addrs, sctp_nxt_addr, naddr) {
/*sa_ignore FREED_MEMORY*/
sctp_remove_laddr(laddr);
}
/* pending asconf (address) parameters */
TAILQ_FOREACH_SAFE(aparam, &asoc->asconf_queue, next, naparam) {
/*sa_ignore FREED_MEMORY*/
TAILQ_REMOVE(&asoc->asconf_queue, aparam, next);
SCTP_FREE(aparam,SCTP_M_ASC_ADDR);
}
TAILQ_FOREACH_SAFE(aack, &asoc->asconf_ack_sent, next, naack) {
/*sa_ignore FREED_MEMORY*/
TAILQ_REMOVE(&asoc->asconf_ack_sent, aack, next);
if (aack->data != NULL) {
sctp_m_freem(aack->data);
}
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asconf_ack), aack);
}
/* clean up auth stuff */
if (asoc->local_hmacs)
sctp_free_hmaclist(asoc->local_hmacs);
if (asoc->peer_hmacs)
sctp_free_hmaclist(asoc->peer_hmacs);
if (asoc->local_auth_chunks)
sctp_free_chunklist(asoc->local_auth_chunks);
if (asoc->peer_auth_chunks)
sctp_free_chunklist(asoc->peer_auth_chunks);
sctp_free_authinfo(&asoc->authinfo);
LIST_FOREACH_SAFE(shared_key, &asoc->shared_keys, next, nshared_key) {
LIST_REMOVE(shared_key, next);
sctp_free_sharedkey(shared_key);
/*sa_ignore FREED_MEMORY*/
}
/* Insert new items here :> */
/* Get rid of LOCK */
SCTP_TCB_UNLOCK(stcb);
SCTP_TCB_LOCK_DESTROY(stcb);
SCTP_TCB_SEND_LOCK_DESTROY(stcb);
if (from_inpcbfree == SCTP_NORMAL_PROC) {
SCTP_INP_INFO_WUNLOCK();
SCTP_INP_RLOCK(inp);
}
#if defined(__APPLE__) /* TEMP CODE */
stcb->freed_from_where = from_location;
#endif
#ifdef SCTP_TRACK_FREED_ASOCS
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
/* now clean up the tasoc itself */
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
SCTP_DECR_ASOC_COUNT();
} else {
LIST_INSERT_HEAD(&inp->sctp_asoc_free_list, stcb, sctp_tcblist);
}
#else
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
SCTP_DECR_ASOC_COUNT();
#endif
if (from_inpcbfree == SCTP_NORMAL_PROC) {
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
/* If its NOT the inp_free calling us AND
* sctp_close as been called, we
* call back...
*/
SCTP_INP_RUNLOCK(inp);
/* This will start the kill timer (if we are
* the last one) since we hold an increment yet. But
* this is the only safe way to do this
* since otherwise if the socket closes
* at the same time we are here we might
* collide in the cleanup.
*/
sctp_inpcb_free(inp,
SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE,
SCTP_CALLED_DIRECTLY_NOCMPSET);
SCTP_INP_DECR_REF(inp);
goto out_of;
} else {
/* The socket is still open. */
SCTP_INP_DECR_REF(inp);
}
}
if (from_inpcbfree == SCTP_NORMAL_PROC) {
SCTP_INP_RUNLOCK(inp);
}
out_of:
/* destroyed the asoc */
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 11);
#endif
return (1);
}
/*
* determine if a destination is "reachable" based upon the addresses bound
* to the current endpoint (e.g. only v4 or v6 currently bound)
*/
/*
* FIX: if we allow assoc-level bindx(), then this needs to be fixed to use
* assoc level v4/v6 flags, as the assoc *may* not have the same address
* types bound as its endpoint
*/
int
sctp_destination_is_reachable(struct sctp_tcb *stcb, struct sockaddr *destaddr)
{
struct sctp_inpcb *inp;
int answer;
/*
* No locks here, the TCB, in all cases is already locked and an
* assoc is up. There is either a INP lock by the caller applied (in
* asconf case when deleting an address) or NOT in the HB case,
* however if HB then the INP increment is up and the INP will not
* be removed (on top of the fact that we have a TCB lock). So we
* only want to read the sctp_flags, which is either bound-all or
* not.. no protection needed since once an assoc is up you can't be
* changing your binding.
*/
inp = stcb->sctp_ep;
if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
/* if bound all, destination is not restricted */
/*
* RRS: Question during lock work: Is this correct? If you
* are bound-all you still might need to obey the V4--V6
* flags??? IMO this bound-all stuff needs to be removed!
*/
return (1);
}
/* NOTE: all "scope" checks are done when local addresses are added */
switch (destaddr->sa_family) {
#ifdef INET6
case AF_INET6:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
answer = inp->inp_vflag & INP_IPV6;
#else
answer = inp->ip_inp.inp.inp_vflag & INP_IPV6;
#endif
break;
#endif
#ifdef INET
case AF_INET:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
answer = inp->inp_vflag & INP_IPV4;
#else
answer = inp->ip_inp.inp.inp_vflag & INP_IPV4;
#endif
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
answer = inp->ip_inp.inp.inp_vflag & INP_CONN;
break;
#endif
default:
/* invalid family, so it's unreachable */
answer = 0;
break;
}
return (answer);
}
/*
* update the inp_vflags on an endpoint
*/
static void
sctp_update_ep_vflag(struct sctp_inpcb *inp)
{
struct sctp_laddr *laddr;
/* first clear the flag */
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
inp->inp_vflag = 0;
#else
inp->ip_inp.inp.inp_vflag = 0;
#endif
/* set the flag based on addresses on the ep list */
LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
if (laddr->ifa == NULL) {
SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n",
__func__);
continue;
}
if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
continue;
}
switch (laddr->ifa->address.sa.sa_family) {
#ifdef INET6
case AF_INET6:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
inp->inp_vflag |= INP_IPV6;
#else
inp->ip_inp.inp.inp_vflag |= INP_IPV6;
#endif
break;
#endif
#ifdef INET
case AF_INET:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
inp->inp_vflag |= INP_IPV4;
#else
inp->ip_inp.inp.inp_vflag |= INP_IPV4;
#endif
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
inp->ip_inp.inp.inp_vflag |= INP_CONN;
break;
#endif
default:
break;
}
}
}
/*
* Add the address to the endpoint local address list There is nothing to be
* done if we are bound to all addresses
*/
void
sctp_add_local_addr_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa, uint32_t action)
{
struct sctp_laddr *laddr;
struct sctp_tcb *stcb;
int fnd, error = 0;
fnd = 0;
if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
/* You are already bound to all. You have it already */
return;
}
#ifdef INET6
if (ifa->address.sa.sa_family == AF_INET6) {
if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
/* Can't bind a non-useable addr. */
return;
}
}
#endif
/* first, is it already present? */
LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
if (laddr->ifa == ifa) {
fnd = 1;
break;
}
}
if (fnd == 0) {
/* Not in the ep list */
error = sctp_insert_laddr(&inp->sctp_addr_list, ifa, action);
if (error != 0)
return;
inp->laddr_count++;
/* update inp_vflag flags */
switch (ifa->address.sa.sa_family) {
#ifdef INET6
case AF_INET6:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
inp->inp_vflag |= INP_IPV6;
#else
inp->ip_inp.inp.inp_vflag |= INP_IPV6;
#endif
break;
#endif
#ifdef INET
case AF_INET:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
inp->inp_vflag |= INP_IPV4;
#else
inp->ip_inp.inp.inp_vflag |= INP_IPV4;
#endif
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
inp->ip_inp.inp.inp_vflag |= INP_CONN;
break;
#endif
default:
break;
}
LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
sctp_add_local_addr_restricted(stcb, ifa);
}
}
return;
}
/*
* select a new (hopefully reachable) destination net (should only be used
* when we deleted an ep addr that is the only usable source address to reach
* the destination net)
*/
static void
sctp_select_primary_destination(struct sctp_tcb *stcb)
{
struct sctp_nets *net;
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
/* for now, we'll just pick the first reachable one we find */
if (net->dest_state & SCTP_ADDR_UNCONFIRMED)
continue;
if (sctp_destination_is_reachable(stcb,
(struct sockaddr *)&net->ro._l_addr)) {
/* found a reachable destination */
stcb->asoc.primary_destination = net;
}
}
/* I can't there from here! ...we're gonna die shortly... */
}
/*
* Delete the address from the endpoint local address list. There is nothing
* to be done if we are bound to all addresses
*/
void
sctp_del_local_addr_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa)
{
struct sctp_laddr *laddr;
int fnd;
fnd = 0;
if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
/* You are already bound to all. You have it already */
return;
}
LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
if (laddr->ifa == ifa) {
fnd = 1;
break;
}
}
if (fnd && (inp->laddr_count < 2)) {
/* can't delete unless there are at LEAST 2 addresses */
return;
}
if (fnd) {
/*
* clean up any use of this address go through our
* associations and clear any last_used_address that match
* this one for each assoc, see if a new primary_destination
* is needed
*/
struct sctp_tcb *stcb;
/* clean up "next_addr_touse" */
if (inp->next_addr_touse == laddr)
/* delete this address */
inp->next_addr_touse = NULL;
/* clean up "last_used_address" */
LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
struct sctp_nets *net;
SCTP_TCB_LOCK(stcb);
if (stcb->asoc.last_used_address == laddr)
/* delete this address */
stcb->asoc.last_used_address = NULL;
/* Now spin through all the nets and purge any ref to laddr */
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
if (net->ro._s_addr == laddr->ifa) {
/* Yep, purge src address selected */
sctp_rtentry_t *rt;
/* delete this address if cached */
rt = net->ro.ro_rt;
if (rt != NULL) {
RTFREE(rt);
net->ro.ro_rt = NULL;
}
sctp_free_ifa(net->ro._s_addr);
net->ro._s_addr = NULL;
net->src_addr_selected = 0;
}
}
SCTP_TCB_UNLOCK(stcb);
} /* for each tcb */
/* remove it from the ep list */
sctp_remove_laddr(laddr);
inp->laddr_count--;
/* update inp_vflag flags */
sctp_update_ep_vflag(inp);
}
return;
}
/*
* Add the address to the TCB local address restricted list.
* This is a "pending" address list (eg. addresses waiting for an
* ASCONF-ACK response) and cannot be used as a valid source address.
*/
void
sctp_add_local_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa)
{
struct sctp_laddr *laddr;
struct sctpladdr *list;
/*
* Assumes TCB is locked.. and possibly the INP. May need to
* confirm/fix that if we need it and is not the case.
*/
list = &stcb->asoc.sctp_restricted_addrs;
#ifdef INET6
if (ifa->address.sa.sa_family == AF_INET6) {
if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
/* Can't bind a non-existent addr. */
return;
}
}
#endif
/* does the address already exist? */
LIST_FOREACH(laddr, list, sctp_nxt_addr) {
if (laddr->ifa == ifa) {
return;
}
}
/* add to the list */
(void)sctp_insert_laddr(list, ifa, 0);
return;
}
/*
* Remove a local address from the TCB local address restricted list
*/
void
sctp_del_local_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa)
{
struct sctp_inpcb *inp;
struct sctp_laddr *laddr;
/*
* This is called by asconf work. It is assumed that a) The TCB is
* locked and b) The INP is locked. This is true in as much as I can
* trace through the entry asconf code where I did these locks.
* Again, the ASCONF code is a bit different in that it does lock
* the INP during its work often times. This must be since we don't
* want other proc's looking up things while what they are looking
* up is changing :-D
*/
inp = stcb->sctp_ep;
/* if subset bound and don't allow ASCONF's, can't delete last */
if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) &&
sctp_is_feature_off(inp, SCTP_PCB_FLAGS_DO_ASCONF)) {
if (stcb->sctp_ep->laddr_count < 2) {
/* can't delete last address */
return;
}
}
LIST_FOREACH(laddr, &stcb->asoc.sctp_restricted_addrs, sctp_nxt_addr) {
/* remove the address if it exists */
if (laddr->ifa == NULL)
continue;
if (laddr->ifa == ifa) {
sctp_remove_laddr(laddr);
return;
}
}
/* address not found! */
return;
}
#if defined(__FreeBSD__)
/*
* Temporarily remove for __APPLE__ until we use the Tiger equivalents
*/
/* sysctl */
static int sctp_max_number_of_assoc = SCTP_MAX_NUM_OF_ASOC;
static int sctp_scale_up_for_address = SCTP_SCALE_FOR_ADDR;
#endif /* FreeBSD || APPLE */
#if defined(__FreeBSD__) && defined(SCTP_MCORE_INPUT) && defined(SMP)
struct sctp_mcore_ctrl *sctp_mcore_workers = NULL;
int *sctp_cpuarry = NULL;
void
sctp_queue_to_mcore(struct mbuf *m, int off, int cpu_to_use)
{
/* Queue a packet to a processor for the specified core */
struct sctp_mcore_queue *qent;
struct sctp_mcore_ctrl *wkq;
int need_wake = 0;
if (sctp_mcore_workers == NULL) {
/* Something went way bad during setup */
sctp_input_with_port(m, off, 0);
return;
}
SCTP_MALLOC(qent, struct sctp_mcore_queue *,
(sizeof(struct sctp_mcore_queue)),
SCTP_M_MCORE);
if (qent == NULL) {
/* This is trouble */
sctp_input_with_port(m, off, 0);
return;
}
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
qent->vn = curvnet;
#endif
qent->m = m;
qent->off = off;
qent->v6 = 0;
wkq = &sctp_mcore_workers[cpu_to_use];
SCTP_MCORE_QLOCK(wkq);
TAILQ_INSERT_TAIL(&wkq->que, qent, next);
if (wkq->running == 0) {
need_wake = 1;
}
SCTP_MCORE_QUNLOCK(wkq);
if (need_wake) {
wakeup(&wkq->running);
}
}
static void
sctp_mcore_thread(void *arg)
{
struct sctp_mcore_ctrl *wkq;
struct sctp_mcore_queue *qent;
wkq = (struct sctp_mcore_ctrl *)arg;
struct mbuf *m;
int off, v6;
/* Wait for first tickle */
SCTP_MCORE_LOCK(wkq);
wkq->running = 0;
msleep(&wkq->running,
&wkq->core_mtx,
0, "wait for pkt", 0);
SCTP_MCORE_UNLOCK(wkq);
/* Bind to our cpu */
thread_lock(curthread);
sched_bind(curthread, wkq->cpuid);
thread_unlock(curthread);
/* Now lets start working */
SCTP_MCORE_LOCK(wkq);
/* Now grab lock and go */
for (;;) {
SCTP_MCORE_QLOCK(wkq);
skip_sleep:
wkq->running = 1;
qent = TAILQ_FIRST(&wkq->que);
if (qent) {
TAILQ_REMOVE(&wkq->que, qent, next);
SCTP_MCORE_QUNLOCK(wkq);
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
CURVNET_SET(qent->vn);
#endif
m = qent->m;
off = qent->off;
v6 = qent->v6;
SCTP_FREE(qent, SCTP_M_MCORE);
if (v6 == 0) {
sctp_input_with_port(m, off, 0);
} else {
SCTP_PRINTF("V6 not yet supported\n");
sctp_m_freem(m);
}
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
CURVNET_RESTORE();
#endif
SCTP_MCORE_QLOCK(wkq);
}
wkq->running = 0;
if (!TAILQ_EMPTY(&wkq->que)) {
goto skip_sleep;
}
SCTP_MCORE_QUNLOCK(wkq);
msleep(&wkq->running,
&wkq->core_mtx,
0, "wait for pkt", 0);
}
}
static void
sctp_startup_mcore_threads(void)
{
int i, cpu;
if (mp_ncpus == 1)
return;
if (sctp_mcore_workers != NULL) {
/* Already been here in some previous
* vnet?
*/
return;
}
SCTP_MALLOC(sctp_mcore_workers, struct sctp_mcore_ctrl *,
((mp_maxid+1) * sizeof(struct sctp_mcore_ctrl)),
SCTP_M_MCORE);
if (sctp_mcore_workers == NULL) {
/* TSNH I hope */
return;
}
memset(sctp_mcore_workers, 0 , ((mp_maxid+1) *
sizeof(struct sctp_mcore_ctrl)));
/* Init the structures */
for (i = 0; i<=mp_maxid; i++) {
TAILQ_INIT(&sctp_mcore_workers[i].que);
SCTP_MCORE_LOCK_INIT(&sctp_mcore_workers[i]);
SCTP_MCORE_QLOCK_INIT(&sctp_mcore_workers[i]);
sctp_mcore_workers[i].cpuid = i;
}
if (sctp_cpuarry == NULL) {
SCTP_MALLOC(sctp_cpuarry, int *,
(mp_ncpus * sizeof(int)),
SCTP_M_MCORE);
i = 0;
CPU_FOREACH(cpu) {
sctp_cpuarry[i] = cpu;
i++;
}
}
/* Now start them all */
CPU_FOREACH(cpu) {
#if __FreeBSD_version <= 701000
(void)kthread_create(sctp_mcore_thread,
(void *)&sctp_mcore_workers[cpu],
&sctp_mcore_workers[cpu].thread_proc,
RFPROC,
SCTP_KTHREAD_PAGES,
SCTP_MCORE_NAME);
#else
(void)kproc_create(sctp_mcore_thread,
(void *)&sctp_mcore_workers[cpu],
&sctp_mcore_workers[cpu].thread_proc,
RFPROC,
SCTP_KTHREAD_PAGES,
SCTP_MCORE_NAME);
#endif
}
}
#endif
#if defined(__FreeBSD__) && __FreeBSD_cc_version >= 1400000
static struct mbuf *
sctp_netisr_hdlr(struct mbuf *m, uintptr_t source)
{
struct ip *ip;
struct sctphdr *sh;
int offset;
uint32_t flowid, tag;
/*
* No flow id built by lower layers fix it so we
* create one.
*/
ip = mtod(m, struct ip *);
offset = (ip->ip_hl << 2) + sizeof(struct sctphdr);
if (SCTP_BUF_LEN(m) < offset) {
if ((m = m_pullup(m, offset)) == NULL) {
SCTP_STAT_INCR(sctps_hdrops);
return (NULL);
}
ip = mtod(m, struct ip *);
}
sh = (struct sctphdr *)((caddr_t)ip + (ip->ip_hl << 2));
tag = htonl(sh->v_tag);
flowid = tag ^ ntohs(sh->dest_port) ^ ntohs(sh->src_port);
m->m_pkthdr.flowid = flowid;
/* FIX ME */
m->m_flags |= M_FLOWID;
return (m);
}
#endif
void
#if defined(__Userspace__)
sctp_pcb_init(int start_threads)
#else
sctp_pcb_init(void)
#endif
{
/*
* SCTP initialization for the PCB structures should be called by
* the sctp_init() function.
*/
int i;
struct timeval tv;
if (SCTP_BASE_VAR(sctp_pcb_initialized) != 0) {
/* error I was called twice */
return;
}
SCTP_BASE_VAR(sctp_pcb_initialized) = 1;
#if defined(SCTP_PROCESS_LEVEL_LOCKS)
#if !defined(__Userspace_os_Windows)
pthread_mutexattr_init(&SCTP_BASE_VAR(mtx_attr));
#ifdef INVARIANTS
pthread_mutexattr_settype(&SCTP_BASE_VAR(mtx_attr), PTHREAD_MUTEX_ERRORCHECK);
#endif
#endif
#endif
#if defined(SCTP_LOCAL_TRACE_BUF)
#if defined(__Windows__)
if (SCTP_BASE_SYSCTL(sctp_log) != NULL) {
memset(SCTP_BASE_SYSCTL(sctp_log), 0, sizeof(struct sctp_log));
}
#else
memset(&SCTP_BASE_SYSCTL(sctp_log), 0, sizeof(struct sctp_log));
#endif
#endif
#if defined(__FreeBSD__) && defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
SCTP_MALLOC(SCTP_BASE_STATS, struct sctpstat *,
((mp_maxid+1) * sizeof(struct sctpstat)),
SCTP_M_MCORE);
#endif
(void)SCTP_GETTIME_TIMEVAL(&tv);
#if defined(__FreeBSD__) && defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
memset(SCTP_BASE_STATS, 0, sizeof(struct sctpstat) * (mp_maxid+1));
SCTP_BASE_STATS[PCPU_GET(cpuid)].sctps_discontinuitytime.tv_sec = (uint32_t)tv.tv_sec;
SCTP_BASE_STATS[PCPU_GET(cpuid)].sctps_discontinuitytime.tv_usec = (uint32_t)tv.tv_usec;
#else
memset(&SCTP_BASE_STATS, 0, sizeof(struct sctpstat));
SCTP_BASE_STAT(sctps_discontinuitytime).tv_sec = (uint32_t)tv.tv_sec;
SCTP_BASE_STAT(sctps_discontinuitytime).tv_usec = (uint32_t)tv.tv_usec;
#endif
/* init the empty list of (All) Endpoints */
LIST_INIT(&SCTP_BASE_INFO(listhead));
#if defined(__APPLE__)
LIST_INIT(&SCTP_BASE_INFO(inplisthead));
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
SCTP_BASE_INFO(sctbinfo).listhead = &SCTP_BASE_INFO(inplisthead);
SCTP_BASE_INFO(sctbinfo).mtx_grp_attr = lck_grp_attr_alloc_init();
lck_grp_attr_setdefault(SCTP_BASE_INFO(sctbinfo).mtx_grp_attr);
SCTP_BASE_INFO(sctbinfo).mtx_grp = lck_grp_alloc_init("sctppcb", SCTP_BASE_INFO(sctbinfo).mtx_grp_attr);
SCTP_BASE_INFO(sctbinfo).mtx_attr = lck_attr_alloc_init();
lck_attr_setdefault(SCTP_BASE_INFO(sctbinfo).mtx_attr);
#else
SCTP_BASE_INFO(sctbinfo).ipi_listhead = &SCTP_BASE_INFO(inplisthead);
SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr = lck_grp_attr_alloc_init();
lck_grp_attr_setdefault(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr);
SCTP_BASE_INFO(sctbinfo).ipi_lock_grp = lck_grp_alloc_init("sctppcb", SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr);
SCTP_BASE_INFO(sctbinfo).ipi_lock_attr = lck_attr_alloc_init();
lck_attr_setdefault(SCTP_BASE_INFO(sctbinfo).ipi_lock_attr);
#endif
#if !defined(APPLE_LEOPARD) && !defined(APPLE_SNOWLEOPARD) && !defined(APPLE_LION) && !defined(APPLE_MOUNTAINLION)
SCTP_BASE_INFO(sctbinfo).ipi_gc = sctp_gc;
in_pcbinfo_attach(&SCTP_BASE_INFO(sctbinfo));
#endif
#endif
/* init the hash table of endpoints */
#if defined(__FreeBSD__)
#if defined(__FreeBSD_cc_version) && __FreeBSD_cc_version >= 440000
TUNABLE_INT_FETCH("net.inet.sctp.tcbhashsize", &SCTP_BASE_SYSCTL(sctp_hashtblsize));
TUNABLE_INT_FETCH("net.inet.sctp.pcbhashsize", &SCTP_BASE_SYSCTL(sctp_pcbtblsize));
TUNABLE_INT_FETCH("net.inet.sctp.chunkscale", &SCTP_BASE_SYSCTL(sctp_chunkscale));
#else
TUNABLE_INT_FETCH("net.inet.sctp.tcbhashsize", SCTP_TCBHASHSIZE,
SCTP_BASE_SYSCTL(sctp_hashtblsize));
TUNABLE_INT_FETCH("net.inet.sctp.pcbhashsize", SCTP_PCBHASHSIZE,
SCTP_BASE_SYSCTL(sctp_pcbtblsize));
TUNABLE_INT_FETCH("net.inet.sctp.chunkscale", SCTP_CHUNKQUEUE_SCALE,
SCTP_BASE_SYSCTL(sctp_chunkscale));
#endif
#endif
SCTP_BASE_INFO(sctp_asochash) = SCTP_HASH_INIT((SCTP_BASE_SYSCTL(sctp_hashtblsize) * 31),
&SCTP_BASE_INFO(hashasocmark));
SCTP_BASE_INFO(sctp_ephash) = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_hashtblsize),
&SCTP_BASE_INFO(hashmark));
SCTP_BASE_INFO(sctp_tcpephash) = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_hashtblsize),
&SCTP_BASE_INFO(hashtcpmark));
SCTP_BASE_INFO(hashtblsize) = SCTP_BASE_SYSCTL(sctp_hashtblsize);
SCTP_BASE_INFO(sctp_vrfhash) = SCTP_HASH_INIT(SCTP_SIZE_OF_VRF_HASH,
&SCTP_BASE_INFO(hashvrfmark));
SCTP_BASE_INFO(vrf_ifn_hash) = SCTP_HASH_INIT(SCTP_VRF_IFN_HASH_SIZE,
&SCTP_BASE_INFO(vrf_ifn_hashmark));
/* init the zones */
/*
* FIX ME: Should check for NULL returns, but if it does fail we are
* doomed to panic anyways... add later maybe.
*/
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_ep), "sctp_ep",
sizeof(struct sctp_inpcb), maxsockets);
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asoc), "sctp_asoc",
sizeof(struct sctp_tcb), sctp_max_number_of_assoc);
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_laddr), "sctp_laddr",
sizeof(struct sctp_laddr),
(sctp_max_number_of_assoc * sctp_scale_up_for_address));
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_net), "sctp_raddr",
sizeof(struct sctp_nets),
(sctp_max_number_of_assoc * sctp_scale_up_for_address));
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_chunk), "sctp_chunk",
sizeof(struct sctp_tmit_chunk),
(sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_readq), "sctp_readq",
sizeof(struct sctp_queued_to_read),
(sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_strmoq), "sctp_stream_msg_out",
sizeof(struct sctp_stream_queue_pending),
(sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asconf), "sctp_asconf",
sizeof(struct sctp_asconf),
(sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asconf_ack), "sctp_asconf_ack",
sizeof(struct sctp_asconf_ack),
(sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
/* Master Lock INIT for info structure */
SCTP_INP_INFO_LOCK_INIT();
SCTP_STATLOG_INIT_LOCK();
SCTP_IPI_COUNT_INIT();
SCTP_IPI_ADDR_INIT();
#ifdef SCTP_PACKET_LOGGING
SCTP_IP_PKTLOG_INIT();
#endif
LIST_INIT(&SCTP_BASE_INFO(addr_wq));
SCTP_WQ_ADDR_INIT();
/* not sure if we need all the counts */
SCTP_BASE_INFO(ipi_count_ep) = 0;
/* assoc/tcb zone info */
SCTP_BASE_INFO(ipi_count_asoc) = 0;
/* local addrlist zone info */
SCTP_BASE_INFO(ipi_count_laddr) = 0;
/* remote addrlist zone info */
SCTP_BASE_INFO(ipi_count_raddr) = 0;
/* chunk info */
SCTP_BASE_INFO(ipi_count_chunk) = 0;
/* socket queue zone info */
SCTP_BASE_INFO(ipi_count_readq) = 0;
/* stream out queue cont */
SCTP_BASE_INFO(ipi_count_strmoq) = 0;
SCTP_BASE_INFO(ipi_free_strmoq) = 0;
SCTP_BASE_INFO(ipi_free_chunks) = 0;
SCTP_OS_TIMER_INIT(&SCTP_BASE_INFO(addr_wq_timer.timer));
/* Init the TIMEWAIT list */
for (i = 0; i < SCTP_STACK_VTAG_HASH_SIZE; i++) {
LIST_INIT(&SCTP_BASE_INFO(vtag_timewait)[i]);
}
#if defined(SCTP_PROCESS_LEVEL_LOCKS)
#if defined(__Userspace_os_Windows)
InitializeConditionVariable(&sctp_it_ctl.iterator_wakeup);
#else
(void)pthread_cond_init(&sctp_it_ctl.iterator_wakeup, NULL);
#endif
#endif
sctp_startup_iterator();
#if defined(__FreeBSD__) && defined(SCTP_MCORE_INPUT) && defined(SMP)
sctp_startup_mcore_threads();
#endif
#ifndef __Panda__
/*
* INIT the default VRF which for BSD is the only one, other O/S's
* may have more. But initially they must start with one and then
* add the VRF's as addresses are added.
*/
sctp_init_vrf_list(SCTP_DEFAULT_VRF);
#endif
#if defined(__FreeBSD__) && __FreeBSD_cc_version >= 1400000
if (ip_register_flow_handler(sctp_netisr_hdlr, IPPROTO_SCTP)) {
SCTP_PRINTF("***SCTP- Error can't register netisr handler***\n");
}
#endif
#if defined(_SCTP_NEEDS_CALLOUT_) || defined(_USER_SCTP_NEEDS_CALLOUT_)
/* allocate the lock for the callout/timer queue */
SCTP_TIMERQ_LOCK_INIT();
SCTP_TIMERWAIT_LOCK_INIT();
TAILQ_INIT(&SCTP_BASE_INFO(callqueue));
#endif
#if defined(__Userspace__)
mbuf_initialize(NULL);
atomic_init();
#if defined(INET) || defined(INET6)
if (start_threads)
recv_thread_init();
#endif
#endif
}
/*
* Assumes that the SCTP_BASE_INFO() lock is NOT held.
*/
void
sctp_pcb_finish(void)
{
struct sctp_vrflist *vrf_bucket;
struct sctp_vrf *vrf, *nvrf;
struct sctp_ifn *ifn, *nifn;
struct sctp_ifa *ifa, *nifa;
struct sctpvtaghead *chain;
struct sctp_tagblock *twait_block, *prev_twait_block;
struct sctp_laddr *wi, *nwi;
int i;
struct sctp_iterator *it, *nit;
if (SCTP_BASE_VAR(sctp_pcb_initialized) == 0) {
SCTP_PRINTF("%s: race condition on teardown.\n", __func__);
return;
}
SCTP_BASE_VAR(sctp_pcb_initialized) = 0;
#if !defined(__FreeBSD__)
/* Notify the iterator to exit. */
SCTP_IPI_ITERATOR_WQ_LOCK();
sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_MUST_EXIT;
sctp_wakeup_iterator();
SCTP_IPI_ITERATOR_WQ_UNLOCK();
#endif
#if defined(__APPLE__)
#if !defined(APPLE_LEOPARD) && !defined(APPLE_SNOWLEOPARD) && !defined(APPLE_LION) && !defined(APPLE_MOUNTAINLION)
in_pcbinfo_detach(&SCTP_BASE_INFO(sctbinfo));
#endif
SCTP_IPI_ITERATOR_WQ_LOCK();
do {
msleep(&sctp_it_ctl.iterator_flags,
sctp_it_ctl.ipi_iterator_wq_mtx,
0, "waiting_for_work", 0);
} while ((sctp_it_ctl.iterator_flags & SCTP_ITERATOR_EXITED) == 0);
thread_deallocate(sctp_it_ctl.thread_proc);
SCTP_IPI_ITERATOR_WQ_UNLOCK();
#endif
#if defined(__Windows__)
if (sctp_it_ctl.iterator_thread_obj != NULL) {
NTSTATUS status = STATUS_SUCCESS;
KeSetEvent(&sctp_it_ctl.iterator_wakeup[1], IO_NO_INCREMENT, FALSE);
status = KeWaitForSingleObject(sctp_it_ctl.iterator_thread_obj,
Executive,
KernelMode,
FALSE,
NULL);
ObDereferenceObject(sctp_it_ctl.iterator_thread_obj);
}
#endif
#if defined(__Userspace__)
if (sctp_it_ctl.thread_proc) {
#if defined(__Userspace_os_Windows)
WaitForSingleObject(sctp_it_ctl.thread_proc, INFINITE);
CloseHandle(sctp_it_ctl.thread_proc);
sctp_it_ctl.thread_proc = NULL;
#else
pthread_join(sctp_it_ctl.thread_proc, NULL);
sctp_it_ctl.thread_proc = 0;
#endif
}
#endif
#if defined(SCTP_PROCESS_LEVEL_LOCKS)
#if defined(__Userspace_os_Windows)
DeleteConditionVariable(&sctp_it_ctl.iterator_wakeup);
#else
pthread_cond_destroy(&sctp_it_ctl.iterator_wakeup);
pthread_mutexattr_destroy(&SCTP_BASE_VAR(mtx_attr));
#endif
#endif
/* In FreeBSD the iterator thread never exits
* but we do clean up.
* The only way FreeBSD reaches here is if we have VRF's
* but we still add the ifdef to make it compile on old versions.
*/
#if defined(__FreeBSD__)
retry:
#endif
SCTP_IPI_ITERATOR_WQ_LOCK();
#if defined(__FreeBSD__)
/*
* sctp_iterator_worker() might be working on an it entry without
* holding the lock. We won't find it on the list either and
* continue and free/destroy it. While holding the lock, spin, to
* avoid the race condition as sctp_iterator_worker() will have to
* wait to re-aquire the lock.
*/
if (sctp_it_ctl.iterator_running != 0 || sctp_it_ctl.cur_it != NULL) {
SCTP_IPI_ITERATOR_WQ_UNLOCK();
SCTP_PRINTF("%s: Iterator running while we held the lock. Retry. "
"cur_it=%p\n", __func__, sctp_it_ctl.cur_it);
DELAY(10);
goto retry;
}
#endif
TAILQ_FOREACH_SAFE(it, &sctp_it_ctl.iteratorhead, sctp_nxt_itr, nit) {
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
if (it->vn != curvnet) {
continue;
}
#endif
TAILQ_REMOVE(&sctp_it_ctl.iteratorhead, it, sctp_nxt_itr);
if (it->function_atend != NULL) {
(*it->function_atend) (it->pointer, it->val);
}
SCTP_FREE(it,SCTP_M_ITER);
}
SCTP_IPI_ITERATOR_WQ_UNLOCK();
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
SCTP_ITERATOR_LOCK();
if ((sctp_it_ctl.cur_it) &&
(sctp_it_ctl.cur_it->vn == curvnet)) {
sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_IT;
}
SCTP_ITERATOR_UNLOCK();
#endif
#if !defined(__FreeBSD__)
SCTP_IPI_ITERATOR_WQ_DESTROY();
SCTP_ITERATOR_LOCK_DESTROY();
#endif
SCTP_OS_TIMER_STOP_DRAIN(&SCTP_BASE_INFO(addr_wq_timer.timer));
SCTP_WQ_ADDR_LOCK();
LIST_FOREACH_SAFE(wi, &SCTP_BASE_INFO(addr_wq), sctp_nxt_addr, nwi) {
LIST_REMOVE(wi, sctp_nxt_addr);
SCTP_DECR_LADDR_COUNT();
if (wi->action == SCTP_DEL_IP_ADDRESS) {
SCTP_FREE(wi->ifa, SCTP_M_IFA);
}
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_laddr), wi);
}
SCTP_WQ_ADDR_UNLOCK();
/*
* free the vrf/ifn/ifa lists and hashes (be sure address monitor
* is destroyed first).
*/
vrf_bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(SCTP_DEFAULT_VRFID & SCTP_BASE_INFO(hashvrfmark))];
LIST_FOREACH_SAFE(vrf, vrf_bucket, next_vrf, nvrf) {
LIST_FOREACH_SAFE(ifn, &vrf->ifnlist, next_ifn, nifn) {
LIST_FOREACH_SAFE(ifa, &ifn->ifalist, next_ifa, nifa) {
/* free the ifa */
LIST_REMOVE(ifa, next_bucket);
LIST_REMOVE(ifa, next_ifa);
SCTP_FREE(ifa, SCTP_M_IFA);
}
/* free the ifn */
LIST_REMOVE(ifn, next_bucket);
LIST_REMOVE(ifn, next_ifn);
SCTP_FREE(ifn, SCTP_M_IFN);
}
SCTP_HASH_FREE(vrf->vrf_addr_hash, vrf->vrf_addr_hashmark);
/* free the vrf */
LIST_REMOVE(vrf, next_vrf);
SCTP_FREE(vrf, SCTP_M_VRF);
}
/* free the vrf hashes */
SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_vrfhash), SCTP_BASE_INFO(hashvrfmark));
SCTP_HASH_FREE(SCTP_BASE_INFO(vrf_ifn_hash), SCTP_BASE_INFO(vrf_ifn_hashmark));
/* free the TIMEWAIT list elements malloc'd in the function
* sctp_add_vtag_to_timewait()...
*/
for (i = 0; i < SCTP_STACK_VTAG_HASH_SIZE; i++) {
chain = &SCTP_BASE_INFO(vtag_timewait)[i];
if (!LIST_EMPTY(chain)) {
prev_twait_block = NULL;
LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
if (prev_twait_block) {
SCTP_FREE(prev_twait_block, SCTP_M_TIMW);
}
prev_twait_block = twait_block;
}
SCTP_FREE(prev_twait_block, SCTP_M_TIMW);
}
}
/* free the locks and mutexes */
#if defined(__APPLE__)
SCTP_TIMERQ_LOCK_DESTROY();
SCTP_TIMERWAIT_LOCK_DESTROY();
#endif
#ifdef SCTP_PACKET_LOGGING
SCTP_IP_PKTLOG_DESTROY();
#endif
SCTP_IPI_ADDR_DESTROY();
#if defined(__APPLE__)
SCTP_IPI_COUNT_DESTROY();
#endif
SCTP_STATLOG_DESTROY();
SCTP_INP_INFO_LOCK_DESTROY();
SCTP_WQ_ADDR_DESTROY();
#if defined(__APPLE__)
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
lck_grp_attr_free(SCTP_BASE_INFO(sctbinfo).mtx_grp_attr);
lck_grp_free(SCTP_BASE_INFO(sctbinfo).mtx_grp);
lck_attr_free(SCTP_BASE_INFO(sctbinfo).mtx_attr);
#else
lck_grp_attr_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr);
lck_grp_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp);
lck_attr_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_attr);
#endif
#endif
#if defined(__Userspace__)
SCTP_TIMERQ_LOCK_DESTROY();
SCTP_TIMERWAIT_LOCK_DESTROY();
SCTP_ZONE_DESTROY(zone_mbuf);
SCTP_ZONE_DESTROY(zone_clust);
SCTP_ZONE_DESTROY(zone_ext_refcnt);
#endif
/* Get rid of other stuff too. */
if (SCTP_BASE_INFO(sctp_asochash) != NULL)
SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_asochash), SCTP_BASE_INFO(hashasocmark));
if (SCTP_BASE_INFO(sctp_ephash) != NULL)
SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_ephash), SCTP_BASE_INFO(hashmark));
if (SCTP_BASE_INFO(sctp_tcpephash) != NULL)
SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_tcpephash), SCTP_BASE_INFO(hashtcpmark));
#if defined(__Windows__) || defined(__FreeBSD__) || defined(__Userspace__)
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_ep));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asoc));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_laddr));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_net));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_chunk));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_readq));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_strmoq));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asconf));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asconf_ack));
#endif
#if defined(__FreeBSD__) && defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
SCTP_FREE(SCTP_BASE_STATS, SCTP_M_MCORE);
#endif
}
int
sctp_load_addresses_from_init(struct sctp_tcb *stcb, struct mbuf *m,
int offset, int limit,
struct sockaddr *src, struct sockaddr *dst,
struct sockaddr *altsa, uint16_t port)
{
/*
* grub through the INIT pulling addresses and loading them to the
* nets structure in the asoc. The from address in the mbuf should
* also be loaded (if it is not already). This routine can be called
* with either INIT or INIT-ACK's as long as the m points to the IP
* packet and the offset points to the beginning of the parameters.
*/
struct sctp_inpcb *inp;
struct sctp_nets *net, *nnet, *net_tmp;
struct sctp_paramhdr *phdr, param_buf;
struct sctp_tcb *stcb_tmp;
uint16_t ptype, plen;
struct sockaddr *sa;
uint8_t random_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_random *p_random = NULL;
uint16_t random_len = 0;
uint8_t hmacs_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_hmac_algo *hmacs = NULL;
uint16_t hmacs_len = 0;
uint8_t saw_asconf = 0;
uint8_t saw_asconf_ack = 0;
uint8_t chunks_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_chunk_list *chunks = NULL;
uint16_t num_chunks = 0;
sctp_key_t *new_key;
uint32_t keylen;
int got_random = 0, got_hmacs = 0, got_chklist = 0;
uint8_t peer_supports_ecn;
uint8_t peer_supports_prsctp;
uint8_t peer_supports_auth;
uint8_t peer_supports_asconf;
uint8_t peer_supports_asconf_ack;
uint8_t peer_supports_reconfig;
uint8_t peer_supports_nrsack;
uint8_t peer_supports_pktdrop;
uint8_t peer_supports_idata;
#ifdef INET
struct sockaddr_in sin;
#endif
#ifdef INET6
struct sockaddr_in6 sin6;
#endif
/* First get the destination address setup too. */
#ifdef INET
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
sin.sin_len = sizeof(sin);
#endif
sin.sin_port = stcb->rport;
#endif
#ifdef INET6
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
#ifdef HAVE_SIN6_LEN
sin6.sin6_len = sizeof(struct sockaddr_in6);
#endif
sin6.sin6_port = stcb->rport;
#endif
if (altsa) {
sa = altsa;
} else {
sa = src;
}
peer_supports_idata = 0;
peer_supports_ecn = 0;
peer_supports_prsctp = 0;
peer_supports_auth = 0;
peer_supports_asconf = 0;
peer_supports_reconfig = 0;
peer_supports_nrsack = 0;
peer_supports_pktdrop = 0;
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
/* mark all addresses that we have currently on the list */
net->dest_state |= SCTP_ADDR_NOT_IN_ASSOC;
}
/* does the source address already exist? if so skip it */
inp = stcb->sctp_ep;
atomic_add_int(&stcb->asoc.refcnt, 1);
stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net_tmp, dst, stcb);
atomic_add_int(&stcb->asoc.refcnt, -1);
if ((stcb_tmp == NULL && inp == stcb->sctp_ep) || inp == NULL) {
/* we must add the source address */
/* no scope set here since we have a tcb already. */
switch (sa->sa_family) {
#ifdef INET
case AF_INET:
if (stcb->asoc.scope.ipv4_addr_legal) {
if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_2)) {
return (-1);
}
}
break;
#endif
#ifdef INET6
case AF_INET6:
if (stcb->asoc.scope.ipv6_addr_legal) {
if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_3)) {
return (-2);
}
}
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
if (stcb->asoc.scope.conn_addr_legal) {
if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_3)) {
return (-2);
}
}
break;
#endif
default:
break;
}
} else {
if (net_tmp != NULL && stcb_tmp == stcb) {
net_tmp->dest_state &= ~SCTP_ADDR_NOT_IN_ASSOC;
} else if (stcb_tmp != stcb) {
/* It belongs to another association? */
if (stcb_tmp)
SCTP_TCB_UNLOCK(stcb_tmp);
return (-3);
}
}
if (stcb->asoc.state == 0) {
/* the assoc was freed? */
return (-4);
}
/* now we must go through each of the params. */
phdr = sctp_get_next_param(m, offset, ¶m_buf, sizeof(param_buf));
while (phdr) {
ptype = ntohs(phdr->param_type);
plen = ntohs(phdr->param_length);
/*
* SCTP_PRINTF("ptype => %0x, plen => %d\n", (uint32_t)ptype,
* (int)plen);
*/
if (offset + plen > limit) {
break;
}
if (plen == 0) {
break;
}
#ifdef INET
if (ptype == SCTP_IPV4_ADDRESS) {
if (stcb->asoc.scope.ipv4_addr_legal) {
struct sctp_ipv4addr_param *p4, p4_buf;
/* ok get the v4 address and check/add */
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&p4_buf,
sizeof(p4_buf));
if (plen != sizeof(struct sctp_ipv4addr_param) ||
phdr == NULL) {
return (-5);
}
p4 = (struct sctp_ipv4addr_param *)phdr;
sin.sin_addr.s_addr = p4->addr;
if (IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
/* Skip multi-cast addresses */
goto next_param;
}
if ((sin.sin_addr.s_addr == INADDR_BROADCAST) ||
(sin.sin_addr.s_addr == INADDR_ANY)) {
goto next_param;
}
sa = (struct sockaddr *)&sin;
inp = stcb->sctp_ep;
atomic_add_int(&stcb->asoc.refcnt, 1);
stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net,
dst, stcb);
atomic_add_int(&stcb->asoc.refcnt, -1);
if ((stcb_tmp == NULL && inp == stcb->sctp_ep) ||
inp == NULL) {
/* we must add the source address */
/*
* no scope set since we have a tcb
* already
*/
/*
* we must validate the state again
* here
*/
add_it_now:
if (stcb->asoc.state == 0) {
/* the assoc was freed? */
return (-7);
}
if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_4)) {
return (-8);
}
} else if (stcb_tmp == stcb) {
if (stcb->asoc.state == 0) {
/* the assoc was freed? */
return (-10);
}
if (net != NULL) {
/* clear flag */
net->dest_state &=
~SCTP_ADDR_NOT_IN_ASSOC;
}
} else {
/*
* strange, address is in another
* assoc? straighten out locks.
*/
if (stcb_tmp) {
if (SCTP_GET_STATE(stcb_tmp) == SCTP_STATE_COOKIE_WAIT) {
struct mbuf *op_err;
char msg[SCTP_DIAG_INFO_LEN];
/* in setup state we abort this guy */
snprintf(msg, sizeof(msg),
"%s:%d at %s", __FILE__, __LINE__, __func__);
op_err = sctp_generate_cause(SCTP_BASE_SYSCTL(sctp_diag_info_code),
msg);
sctp_abort_an_association(stcb_tmp->sctp_ep,
stcb_tmp, op_err,
SCTP_SO_NOT_LOCKED);
goto add_it_now;
}
SCTP_TCB_UNLOCK(stcb_tmp);
}
if (stcb->asoc.state == 0) {
/* the assoc was freed? */
return (-12);
}
return (-13);
}
}
} else
#endif
#ifdef INET6
if (ptype == SCTP_IPV6_ADDRESS) {
if (stcb->asoc.scope.ipv6_addr_legal) {
/* ok get the v6 address and check/add */
struct sctp_ipv6addr_param *p6, p6_buf;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&p6_buf,
sizeof(p6_buf));
if (plen != sizeof(struct sctp_ipv6addr_param) ||
phdr == NULL) {
return (-14);
}
p6 = (struct sctp_ipv6addr_param *)phdr;
memcpy((caddr_t)&sin6.sin6_addr, p6->addr,
sizeof(p6->addr));
if (IN6_IS_ADDR_MULTICAST(&sin6.sin6_addr)) {
/* Skip multi-cast addresses */
goto next_param;
}
if (IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr)) {
/* Link local make no sense without scope */
goto next_param;
}
sa = (struct sockaddr *)&sin6;
inp = stcb->sctp_ep;
atomic_add_int(&stcb->asoc.refcnt, 1);
stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net,
dst, stcb);
atomic_add_int(&stcb->asoc.refcnt, -1);
if (stcb_tmp == NULL &&
(inp == stcb->sctp_ep || inp == NULL)) {
/*
* we must validate the state again
* here
*/
add_it_now6:
if (stcb->asoc.state == 0) {
/* the assoc was freed? */
return (-16);
}
/*
* we must add the address, no scope
* set
*/
if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_5)) {
return (-17);
}
} else if (stcb_tmp == stcb) {
/*
* we must validate the state again
* here
*/
if (stcb->asoc.state == 0) {
/* the assoc was freed? */
return (-19);
}
if (net != NULL) {
/* clear flag */
net->dest_state &=
~SCTP_ADDR_NOT_IN_ASSOC;
}
} else {
/*
* strange, address is in another
* assoc? straighten out locks.
*/
if (stcb_tmp) {
if (SCTP_GET_STATE(stcb_tmp) == SCTP_STATE_COOKIE_WAIT) {
struct mbuf *op_err;
char msg[SCTP_DIAG_INFO_LEN];
/* in setup state we abort this guy */
snprintf(msg, sizeof(msg),
"%s:%d at %s", __FILE__, __LINE__, __func__);
op_err = sctp_generate_cause(SCTP_BASE_SYSCTL(sctp_diag_info_code),
msg);
sctp_abort_an_association(stcb_tmp->sctp_ep,
stcb_tmp, op_err,
SCTP_SO_NOT_LOCKED);
goto add_it_now6;
}
SCTP_TCB_UNLOCK(stcb_tmp);
}
if (stcb->asoc.state == 0) {
/* the assoc was freed? */
return (-21);
}
return (-22);
}
}
} else
#endif
if (ptype == SCTP_ECN_CAPABLE) {
peer_supports_ecn = 1;
} else if (ptype == SCTP_ULP_ADAPTATION) {
if (stcb->asoc.state != SCTP_STATE_OPEN) {
struct sctp_adaptation_layer_indication ai, *aip;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&ai, sizeof(ai));
aip = (struct sctp_adaptation_layer_indication *)phdr;
if (aip) {
stcb->asoc.peers_adaptation = ntohl(aip->indication);
stcb->asoc.adaptation_needed = 1;
}
}
} else if (ptype == SCTP_SET_PRIM_ADDR) {
struct sctp_asconf_addr_param lstore, *fee;
int lptype;
struct sockaddr *lsa = NULL;
#ifdef INET
struct sctp_asconf_addrv4_param *fii;
#endif
if (stcb->asoc.asconf_supported == 0) {
return (-100);
}
if (plen > sizeof(lstore)) {
return (-23);
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&lstore,
plen);
if (phdr == NULL) {
return (-24);
}
fee = (struct sctp_asconf_addr_param *)phdr;
lptype = ntohs(fee->addrp.ph.param_type);
switch (lptype) {
#ifdef INET
case SCTP_IPV4_ADDRESS:
if (plen !=
sizeof(struct sctp_asconf_addrv4_param)) {
SCTP_PRINTF("Sizeof setprim in init/init ack not %d but %d - ignored\n",
(int)sizeof(struct sctp_asconf_addrv4_param),
plen);
} else {
fii = (struct sctp_asconf_addrv4_param *)fee;
sin.sin_addr.s_addr = fii->addrp.addr;
lsa = (struct sockaddr *)&sin;
}
break;
#endif
#ifdef INET6
case SCTP_IPV6_ADDRESS:
if (plen !=
sizeof(struct sctp_asconf_addr_param)) {
SCTP_PRINTF("Sizeof setprim (v6) in init/init ack not %d but %d - ignored\n",
(int)sizeof(struct sctp_asconf_addr_param),
plen);
} else {
memcpy(sin6.sin6_addr.s6_addr,
fee->addrp.addr,
sizeof(fee->addrp.addr));
lsa = (struct sockaddr *)&sin6;
}
break;
#endif
default:
break;
}
if (lsa) {
(void)sctp_set_primary_addr(stcb, sa, NULL);
}
} else if (ptype == SCTP_HAS_NAT_SUPPORT) {
stcb->asoc.peer_supports_nat = 1;
} else if (ptype == SCTP_PRSCTP_SUPPORTED) {
/* Peer supports pr-sctp */
peer_supports_prsctp = 1;
} else if (ptype == SCTP_SUPPORTED_CHUNK_EXT) {
/* A supported extension chunk */
struct sctp_supported_chunk_types_param *pr_supported;
uint8_t local_store[SCTP_PARAM_BUFFER_SIZE];
int num_ent, i;
if (plen > sizeof(local_store)) {
return (-35);
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&local_store, plen);
if (phdr == NULL) {
return (-25);
}
pr_supported = (struct sctp_supported_chunk_types_param *)phdr;
num_ent = plen - sizeof(struct sctp_paramhdr);
for (i = 0; i < num_ent; i++) {
switch (pr_supported->chunk_types[i]) {
case SCTP_ASCONF:
peer_supports_asconf = 1;
break;
case SCTP_ASCONF_ACK:
peer_supports_asconf_ack = 1;
break;
case SCTP_FORWARD_CUM_TSN:
peer_supports_prsctp = 1;
break;
case SCTP_PACKET_DROPPED:
peer_supports_pktdrop = 1;
break;
case SCTP_NR_SELECTIVE_ACK:
peer_supports_nrsack = 1;
break;
case SCTP_STREAM_RESET:
peer_supports_reconfig = 1;
break;
case SCTP_AUTHENTICATION:
peer_supports_auth = 1;
break;
case SCTP_IDATA:
peer_supports_idata = 1;
break;
default:
/* one I have not learned yet */
break;
}
}
} else if (ptype == SCTP_RANDOM) {
if (plen > sizeof(random_store))
break;
if (got_random) {
/* already processed a RANDOM */
goto next_param;
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)random_store,
plen);
if (phdr == NULL)
return (-26);
p_random = (struct sctp_auth_random *)phdr;
random_len = plen - sizeof(*p_random);
/* enforce the random length */
if (random_len != SCTP_AUTH_RANDOM_SIZE_REQUIRED) {
SCTPDBG(SCTP_DEBUG_AUTH1, "SCTP: invalid RANDOM len\n");
return (-27);
}
got_random = 1;
} else if (ptype == SCTP_HMAC_LIST) {
uint16_t num_hmacs;
uint16_t i;
if (plen > sizeof(hmacs_store))
break;
if (got_hmacs) {
/* already processed a HMAC list */
goto next_param;
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)hmacs_store,
plen);
if (phdr == NULL)
return (-28);
hmacs = (struct sctp_auth_hmac_algo *)phdr;
hmacs_len = plen - sizeof(*hmacs);
num_hmacs = hmacs_len / sizeof(hmacs->hmac_ids[0]);
/* validate the hmac list */
if (sctp_verify_hmac_param(hmacs, num_hmacs)) {
return (-29);
}
if (stcb->asoc.peer_hmacs != NULL)
sctp_free_hmaclist(stcb->asoc.peer_hmacs);
stcb->asoc.peer_hmacs = sctp_alloc_hmaclist(num_hmacs);
if (stcb->asoc.peer_hmacs != NULL) {
for (i = 0; i < num_hmacs; i++) {
(void)sctp_auth_add_hmacid(stcb->asoc.peer_hmacs,
ntohs(hmacs->hmac_ids[i]));
}
}
got_hmacs = 1;
} else if (ptype == SCTP_CHUNK_LIST) {
int i;
if (plen > sizeof(chunks_store))
break;
if (got_chklist) {
/* already processed a Chunks list */
goto next_param;
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)chunks_store,
plen);
if (phdr == NULL)
return (-30);
chunks = (struct sctp_auth_chunk_list *)phdr;
num_chunks = plen - sizeof(*chunks);
if (stcb->asoc.peer_auth_chunks != NULL)
sctp_clear_chunklist(stcb->asoc.peer_auth_chunks);
else
stcb->asoc.peer_auth_chunks = sctp_alloc_chunklist();
for (i = 0; i < num_chunks; i++) {
(void)sctp_auth_add_chunk(chunks->chunk_types[i],
stcb->asoc.peer_auth_chunks);
/* record asconf/asconf-ack if listed */
if (chunks->chunk_types[i] == SCTP_ASCONF)
saw_asconf = 1;
if (chunks->chunk_types[i] == SCTP_ASCONF_ACK)
saw_asconf_ack = 1;
}
got_chklist = 1;
} else if ((ptype == SCTP_HEARTBEAT_INFO) ||
(ptype == SCTP_STATE_COOKIE) ||
(ptype == SCTP_UNRECOG_PARAM) ||
(ptype == SCTP_COOKIE_PRESERVE) ||
(ptype == SCTP_SUPPORTED_ADDRTYPE) ||
(ptype == SCTP_ADD_IP_ADDRESS) ||
(ptype == SCTP_DEL_IP_ADDRESS) ||
(ptype == SCTP_ERROR_CAUSE_IND) ||
(ptype == SCTP_SUCCESS_REPORT)) {
/* don't care */ ;
} else {
if ((ptype & 0x8000) == 0x0000) {
/*
* must stop processing the rest of the
* param's. Any report bits were handled
* with the call to
* sctp_arethere_unrecognized_parameters()
* when the INIT or INIT-ACK was first seen.
*/
break;
}
}
next_param:
offset += SCTP_SIZE32(plen);
if (offset >= limit) {
break;
}
phdr = sctp_get_next_param(m, offset, ¶m_buf,
sizeof(param_buf));
}
/* Now check to see if we need to purge any addresses */
TAILQ_FOREACH_SAFE(net, &stcb->asoc.nets, sctp_next, nnet) {
if ((net->dest_state & SCTP_ADDR_NOT_IN_ASSOC) ==
SCTP_ADDR_NOT_IN_ASSOC) {
/* This address has been removed from the asoc */
/* remove and free it */
stcb->asoc.numnets--;
TAILQ_REMOVE(&stcb->asoc.nets, net, sctp_next);
sctp_free_remote_addr(net);
if (net == stcb->asoc.primary_destination) {
stcb->asoc.primary_destination = NULL;
sctp_select_primary_destination(stcb);
}
}
}
if ((stcb->asoc.ecn_supported == 1) &&
(peer_supports_ecn == 0)) {
stcb->asoc.ecn_supported = 0;
}
if ((stcb->asoc.prsctp_supported == 1) &&
(peer_supports_prsctp == 0)) {
stcb->asoc.prsctp_supported = 0;
}
if ((stcb->asoc.auth_supported == 1) &&
((peer_supports_auth == 0) ||
(got_random == 0) || (got_hmacs == 0))) {
stcb->asoc.auth_supported = 0;
}
if ((stcb->asoc.asconf_supported == 1) &&
((peer_supports_asconf == 0) || (peer_supports_asconf_ack == 0) ||
(stcb->asoc.auth_supported == 0) ||
(saw_asconf == 0) || (saw_asconf_ack == 0))) {
stcb->asoc.asconf_supported = 0;
}
if ((stcb->asoc.reconfig_supported == 1) &&
(peer_supports_reconfig == 0)) {
stcb->asoc.reconfig_supported = 0;
}
if ((stcb->asoc.idata_supported == 1) &&
(peer_supports_idata == 0)) {
stcb->asoc.idata_supported = 0;
}
if ((stcb->asoc.nrsack_supported == 1) &&
(peer_supports_nrsack == 0)) {
stcb->asoc.nrsack_supported = 0;
}
if ((stcb->asoc.pktdrop_supported == 1) &&
(peer_supports_pktdrop == 0)){
stcb->asoc.pktdrop_supported = 0;
}
/* validate authentication required parameters */
if ((peer_supports_auth == 0) && (got_chklist == 1)) {
/* peer does not support auth but sent a chunks list? */
return (-31);
}
if ((peer_supports_asconf == 1) && (peer_supports_auth == 0)) {
/* peer supports asconf but not auth? */
return (-32);
} else if ((peer_supports_asconf == 1) &&
(peer_supports_auth == 1) &&
((saw_asconf == 0) || (saw_asconf_ack == 0))) {
return (-33);
}
/* concatenate the full random key */
keylen = sizeof(*p_random) + random_len + sizeof(*hmacs) + hmacs_len;
if (chunks != NULL) {
keylen += sizeof(*chunks) + num_chunks;
}
new_key = sctp_alloc_key(keylen);
if (new_key != NULL) {
/* copy in the RANDOM */
if (p_random != NULL) {
keylen = sizeof(*p_random) + random_len;
memcpy(new_key->key, p_random, keylen);
} else {
keylen = 0;
}
/* append in the AUTH chunks */
if (chunks != NULL) {
memcpy(new_key->key + keylen, chunks,
sizeof(*chunks) + num_chunks);
keylen += sizeof(*chunks) + num_chunks;
}
/* append in the HMACs */
if (hmacs != NULL) {
memcpy(new_key->key + keylen, hmacs,
sizeof(*hmacs) + hmacs_len);
}
} else {
/* failed to get memory for the key */
return (-34);
}
if (stcb->asoc.authinfo.peer_random != NULL)
sctp_free_key(stcb->asoc.authinfo.peer_random);
stcb->asoc.authinfo.peer_random = new_key;
sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.assoc_keyid);
sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.recv_keyid);
return (0);
}
int
sctp_set_primary_addr(struct sctp_tcb *stcb, struct sockaddr *sa,
struct sctp_nets *net)
{
/* make sure the requested primary address exists in the assoc */
if (net == NULL && sa)
net = sctp_findnet(stcb, sa);
if (net == NULL) {
/* didn't find the requested primary address! */
return (-1);
} else {
/* set the primary address */
if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
/* Must be confirmed, so queue to set */
net->dest_state |= SCTP_ADDR_REQ_PRIMARY;
return (0);
}
stcb->asoc.primary_destination = net;
if (!(net->dest_state & SCTP_ADDR_PF) && (stcb->asoc.alternate)) {
sctp_free_remote_addr(stcb->asoc.alternate);
stcb->asoc.alternate = NULL;
}
net = TAILQ_FIRST(&stcb->asoc.nets);
if (net != stcb->asoc.primary_destination) {
/* first one on the list is NOT the primary
* sctp_cmpaddr() is much more efficient if
* the primary is the first on the list, make it
* so.
*/
TAILQ_REMOVE(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next);
TAILQ_INSERT_HEAD(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next);
}
return (0);
}
}
int
sctp_is_vtag_good(uint32_t tag, uint16_t lport, uint16_t rport, struct timeval *now)
{
/*
* This function serves two purposes. It will see if a TAG can be
* re-used and return 1 for yes it is ok and 0 for don't use that
* tag. A secondary function it will do is purge out old tags that
* can be removed.
*/
struct sctpvtaghead *chain;
struct sctp_tagblock *twait_block;
struct sctpasochead *head;
struct sctp_tcb *stcb;
int i;
SCTP_INP_INFO_RLOCK();
head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(tag,
SCTP_BASE_INFO(hashasocmark))];
LIST_FOREACH(stcb, head, sctp_asocs) {
/* We choose not to lock anything here. TCB's can't be
* removed since we have the read lock, so they can't
* be freed on us, same thing for the INP. I may
* be wrong with this assumption, but we will go
* with it for now :-)
*/
if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
continue;
}
if (stcb->asoc.my_vtag == tag) {
/* candidate */
if (stcb->rport != rport) {
continue;
}
if (stcb->sctp_ep->sctp_lport != lport) {
continue;
}
/* Its a used tag set */
SCTP_INP_INFO_RUNLOCK();
return (0);
}
}
chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
/* Now what about timed wait ? */
LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
/*
* Block(s) are present, lets see if we have this tag in the
* list
*/
for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
if (twait_block->vtag_block[i].v_tag == 0) {
/* not used */
continue;
} else if ((long)twait_block->vtag_block[i].tv_sec_at_expire <
now->tv_sec) {
/* Audit expires this guy */
twait_block->vtag_block[i].tv_sec_at_expire = 0;
twait_block->vtag_block[i].v_tag = 0;
twait_block->vtag_block[i].lport = 0;
twait_block->vtag_block[i].rport = 0;
} else if ((twait_block->vtag_block[i].v_tag == tag) &&
(twait_block->vtag_block[i].lport == lport) &&
(twait_block->vtag_block[i].rport == rport)) {
/* Bad tag, sorry :< */
SCTP_INP_INFO_RUNLOCK();
return (0);
}
}
}
SCTP_INP_INFO_RUNLOCK();
return (1);
}
static void
sctp_drain_mbufs(struct sctp_tcb *stcb)
{
/*
* We must hunt this association for MBUF's past the cumack (i.e.
* out of order data that we can renege on).
*/
struct sctp_association *asoc;
struct sctp_tmit_chunk *chk, *nchk;
uint32_t cumulative_tsn_p1;
struct sctp_queued_to_read *control, *ncontrol;
int cnt, strmat;
uint32_t gap, i;
int fnd = 0;
/* We look for anything larger than the cum-ack + 1 */
asoc = &stcb->asoc;
if (asoc->cumulative_tsn == asoc->highest_tsn_inside_map) {
/* none we can reneg on. */
return;
}
SCTP_STAT_INCR(sctps_protocol_drains_done);
cumulative_tsn_p1 = asoc->cumulative_tsn + 1;
cnt = 0;
/* Ok that was fun, now we will drain all the inbound streams? */
for (strmat = 0; strmat < asoc->streamincnt; strmat++) {
TAILQ_FOREACH_SAFE(control, &asoc->strmin[strmat].inqueue, next_instrm, ncontrol) {
#ifdef INVARIANTS
if (control->on_strm_q != SCTP_ON_ORDERED ) {
panic("Huh control: %p on_q: %d -- not ordered?",
control, control->on_strm_q);
}
#endif
if (SCTP_TSN_GT(control->sinfo_tsn, cumulative_tsn_p1)) {
/* Yep it is above cum-ack */
cnt++;
SCTP_CALC_TSN_TO_GAP(gap, control->sinfo_tsn, asoc->mapping_array_base_tsn);
KASSERT(control->length > 0, ("control has zero length"));
if (asoc->size_on_all_streams >= control->length) {
asoc->size_on_all_streams -= control->length;
} else {
#ifdef INVARIANTS
panic("size_on_all_streams = %u smaller than control length %u", asoc->size_on_all_streams, control->length);
#else
asoc->size_on_all_streams = 0;
#endif
}
sctp_ucount_decr(asoc->cnt_on_all_streams);
SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
if (control->on_read_q) {
TAILQ_REMOVE(&stcb->sctp_ep->read_queue, control, next);
control->on_read_q = 0;
}
TAILQ_REMOVE(&asoc->strmin[strmat].inqueue, control, next_instrm);
control->on_strm_q = 0;
if (control->data) {
sctp_m_freem(control->data);
control->data = NULL;
}
sctp_free_remote_addr(control->whoFrom);
/* Now its reasm? */
TAILQ_FOREACH_SAFE(chk, &control->reasm, sctp_next, nchk) {
cnt++;
SCTP_CALC_TSN_TO_GAP(gap, chk->rec.data.tsn, asoc->mapping_array_base_tsn);
KASSERT(chk->send_size > 0, ("chunk has zero length"));
if (asoc->size_on_reasm_queue >= chk->send_size) {
asoc->size_on_reasm_queue -= chk->send_size;
} else {
#ifdef INVARIANTS
panic("size_on_reasm_queue = %u smaller than chunk length %u", asoc->size_on_reasm_queue, chk->send_size);
#else
asoc->size_on_reasm_queue = 0;
#endif
}
sctp_ucount_decr(asoc->cnt_on_reasm_queue);
SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
TAILQ_REMOVE(&control->reasm, chk, sctp_next);
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
}
sctp_free_a_readq(stcb, control);
}
}
TAILQ_FOREACH_SAFE(control, &asoc->strmin[strmat].uno_inqueue, next_instrm, ncontrol) {
#ifdef INVARIANTS
if (control->on_strm_q != SCTP_ON_UNORDERED ) {
panic("Huh control: %p on_q: %d -- not unordered?",
control, control->on_strm_q);
}
#endif
if (SCTP_TSN_GT(control->sinfo_tsn, cumulative_tsn_p1)) {
/* Yep it is above cum-ack */
cnt++;
SCTP_CALC_TSN_TO_GAP(gap, control->sinfo_tsn, asoc->mapping_array_base_tsn);
KASSERT(control->length > 0, ("control has zero length"));
if (asoc->size_on_all_streams >= control->length) {
asoc->size_on_all_streams -= control->length;
} else {
#ifdef INVARIANTS
panic("size_on_all_streams = %u smaller than control length %u", asoc->size_on_all_streams, control->length);
#else
asoc->size_on_all_streams = 0;
#endif
}
sctp_ucount_decr(asoc->cnt_on_all_streams);
SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
if (control->on_read_q) {
TAILQ_REMOVE(&stcb->sctp_ep->read_queue, control, next);
control->on_read_q = 0;
}
TAILQ_REMOVE(&asoc->strmin[strmat].uno_inqueue, control, next_instrm);
control->on_strm_q = 0;
if (control->data) {
sctp_m_freem(control->data);
control->data = NULL;
}
sctp_free_remote_addr(control->whoFrom);
/* Now its reasm? */
TAILQ_FOREACH_SAFE(chk, &control->reasm, sctp_next, nchk) {
cnt++;
SCTP_CALC_TSN_TO_GAP(gap, chk->rec.data.tsn, asoc->mapping_array_base_tsn);
KASSERT(chk->send_size > 0, ("chunk has zero length"));
if (asoc->size_on_reasm_queue >= chk->send_size) {
asoc->size_on_reasm_queue -= chk->send_size;
} else {
#ifdef INVARIANTS
panic("size_on_reasm_queue = %u smaller than chunk length %u", asoc->size_on_reasm_queue, chk->send_size);
#else
asoc->size_on_reasm_queue = 0;
#endif
}
sctp_ucount_decr(asoc->cnt_on_reasm_queue);
SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
TAILQ_REMOVE(&control->reasm, chk, sctp_next);
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
}
sctp_free_a_readq(stcb, control);
}
}
}
if (cnt) {
/* We must back down to see what the new highest is */
for (i = asoc->highest_tsn_inside_map; SCTP_TSN_GE(i, asoc->mapping_array_base_tsn); i--) {
SCTP_CALC_TSN_TO_GAP(gap, i, asoc->mapping_array_base_tsn);
if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, gap)) {
asoc->highest_tsn_inside_map = i;
fnd = 1;
break;
}
}
if (!fnd) {
asoc->highest_tsn_inside_map = asoc->mapping_array_base_tsn - 1;
}
/*
* Question, should we go through the delivery queue? The only
* reason things are on here is the app not reading OR a p-d-api up.
* An attacker COULD send enough in to initiate the PD-API and then
* send a bunch of stuff to other streams... these would wind up on
* the delivery queue.. and then we would not get to them. But in
* order to do this I then have to back-track and un-deliver
* sequence numbers in streams.. el-yucko. I think for now we will
* NOT look at the delivery queue and leave it to be something to
* consider later. An alternative would be to abort the P-D-API with
* a notification and then deliver the data.... Or another method
* might be to keep track of how many times the situation occurs and
* if we see a possible attack underway just abort the association.
*/
#ifdef SCTP_DEBUG
SCTPDBG(SCTP_DEBUG_PCB1, "Freed %d chunks from reneg harvest\n", cnt);
#endif
/*
* Now do we need to find a new
* asoc->highest_tsn_inside_map?
*/
asoc->last_revoke_count = cnt;
(void)SCTP_OS_TIMER_STOP(&stcb->asoc.dack_timer.timer);
/*sa_ignore NO_NULL_CHK*/
sctp_send_sack(stcb, SCTP_SO_NOT_LOCKED);
sctp_chunk_output(stcb->sctp_ep, stcb, SCTP_OUTPUT_FROM_DRAIN, SCTP_SO_NOT_LOCKED);
}
/*
* Another issue, in un-setting the TSN's in the mapping array we
* DID NOT adjust the highest_tsn marker. This will cause one of two
* things to occur. It may cause us to do extra work in checking for
* our mapping array movement. More importantly it may cause us to
* SACK every datagram. This may not be a bad thing though since we
* will recover once we get our cum-ack above and all this stuff we
* dumped recovered.
*/
}
void
sctp_drain()
{
/*
* We must walk the PCB lists for ALL associations here. The system
* is LOW on MBUF's and needs help. This is where reneging will
* occur. We really hope this does NOT happen!
*/
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
VNET_ITERATOR_DECL(vnet_iter);
#else
struct sctp_inpcb *inp;
struct sctp_tcb *stcb;
SCTP_STAT_INCR(sctps_protocol_drain_calls);
if (SCTP_BASE_SYSCTL(sctp_do_drain) == 0) {
return;
}
#endif
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
VNET_LIST_RLOCK_NOSLEEP();
VNET_FOREACH(vnet_iter) {
CURVNET_SET(vnet_iter);
struct sctp_inpcb *inp;
struct sctp_tcb *stcb;
#endif
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
SCTP_STAT_INCR(sctps_protocol_drain_calls);
if (SCTP_BASE_SYSCTL(sctp_do_drain) == 0) {
#ifdef VIMAGE
continue;
#else
return;
#endif
}
#endif
SCTP_INP_INFO_RLOCK();
LIST_FOREACH(inp, &SCTP_BASE_INFO(listhead), sctp_list) {
/* For each endpoint */
SCTP_INP_RLOCK(inp);
LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
/* For each association */
SCTP_TCB_LOCK(stcb);
sctp_drain_mbufs(stcb);
SCTP_TCB_UNLOCK(stcb);
}
SCTP_INP_RUNLOCK(inp);
}
SCTP_INP_INFO_RUNLOCK();
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
CURVNET_RESTORE();
}
VNET_LIST_RUNLOCK_NOSLEEP();
#endif
}
/*
* start a new iterator
* iterates through all endpoints and associations based on the pcb_state
* flags and asoc_state. "af" (mandatory) is executed for all matching
* assocs and "ef" (optional) is executed when the iterator completes.
* "inpf" (optional) is executed for each new endpoint as it is being
* iterated through. inpe (optional) is called when the inp completes
* its way through all the stcbs.
*/
int
sctp_initiate_iterator(inp_func inpf,
asoc_func af,
inp_func inpe,
uint32_t pcb_state,
uint32_t pcb_features,
uint32_t asoc_state,
void *argp,
uint32_t argi,
end_func ef,
struct sctp_inpcb *s_inp,
uint8_t chunk_output_off)
{
struct sctp_iterator *it = NULL;
if (af == NULL) {
return (-1);
}
if (SCTP_BASE_VAR(sctp_pcb_initialized) == 0) {
SCTP_PRINTF("%s: abort on initialize being %d\n", __func__,
SCTP_BASE_VAR(sctp_pcb_initialized));
return (-1);
}
SCTP_MALLOC(it, struct sctp_iterator *, sizeof(struct sctp_iterator),
SCTP_M_ITER);
if (it == NULL) {
SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM);
return (ENOMEM);
}
memset(it, 0, sizeof(*it));
it->function_assoc = af;
it->function_inp = inpf;
if (inpf)
it->done_current_ep = 0;
else
it->done_current_ep = 1;
it->function_atend = ef;
it->pointer = argp;
it->val = argi;
it->pcb_flags = pcb_state;
it->pcb_features = pcb_features;
it->asoc_state = asoc_state;
it->function_inp_end = inpe;
it->no_chunk_output = chunk_output_off;
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
it->vn = curvnet;
#endif
if (s_inp) {
/* Assume lock is held here */
it->inp = s_inp;
SCTP_INP_INCR_REF(it->inp);
it->iterator_flags = SCTP_ITERATOR_DO_SINGLE_INP;
} else {
SCTP_INP_INFO_RLOCK();
it->inp = LIST_FIRST(&SCTP_BASE_INFO(listhead));
if (it->inp) {
SCTP_INP_INCR_REF(it->inp);
}
SCTP_INP_INFO_RUNLOCK();
it->iterator_flags = SCTP_ITERATOR_DO_ALL_INP;
}
SCTP_IPI_ITERATOR_WQ_LOCK();
if (SCTP_BASE_VAR(sctp_pcb_initialized) == 0) {
SCTP_IPI_ITERATOR_WQ_UNLOCK();
SCTP_PRINTF("%s: rollback on initialize being %d it=%p\n", __func__,
SCTP_BASE_VAR(sctp_pcb_initialized), it);
SCTP_FREE(it, SCTP_M_ITER);
return (-1);
}
TAILQ_INSERT_TAIL(&sctp_it_ctl.iteratorhead, it, sctp_nxt_itr);
if (sctp_it_ctl.iterator_running == 0) {
sctp_wakeup_iterator();
}
SCTP_IPI_ITERATOR_WQ_UNLOCK();
/* sa_ignore MEMLEAK {memory is put on the tailq for the iterator} */
return (0);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1370_1 |
crossvul-cpp_data_bad_4589_2 | /*
* The Python Imaging Library.
* $Id$
*
* decoder for Autodesk Animator FLI/FLC animations
*
* history:
* 97-01-03 fl Created
* 97-01-17 fl Added SS2 support (FLC)
*
* Copyright (c) Fredrik Lundh 1997.
* Copyright (c) Secret Labs AB 1997.
*
* See the README file for information on usage and redistribution.
*/
#include "Imaging.h"
#define I16(ptr)\
((ptr)[0] + ((ptr)[1] << 8))
#define I32(ptr)\
((ptr)[0] + ((ptr)[1] << 8) + ((ptr)[2] << 16) + ((ptr)[3] << 24))
int
ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)
{
UINT8* ptr;
int framesize;
int c, chunks, advance;
int l, lines;
int i, j, x = 0, y, ymax;
/* If not even the chunk size is present, we'd better leave */
if (bytes < 4)
return 0;
/* We don't decode anything unless we have a full chunk in the
input buffer (on the other hand, the Python part of the driver
makes sure this is always the case) */
ptr = buf;
framesize = I32(ptr);
if (framesize < I32(ptr))
return 0;
/* Make sure this is a frame chunk. The Python driver takes
case of other chunk types. */
if (I16(ptr+4) != 0xF1FA) {
state->errcode = IMAGING_CODEC_UNKNOWN;
return -1;
}
chunks = I16(ptr+6);
ptr += 16;
bytes -= 16;
/* Process subchunks */
for (c = 0; c < chunks; c++) {
UINT8* data;
if (bytes < 10) {
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
data = ptr + 6;
switch (I16(ptr+4)) {
case 4: case 11:
/* FLI COLOR chunk */
break; /* ignored; handled by Python code */
case 7:
/* FLI SS2 chunk (word delta) */
lines = I16(data); data += 2;
for (l = y = 0; l < lines && y < state->ysize; l++, y++) {
UINT8* buf = (UINT8*) im->image[y];
int p, packets;
packets = I16(data); data += 2;
while (packets & 0x8000) {
/* flag word */
if (packets & 0x4000) {
y += 65536 - packets; /* skip lines */
if (y >= state->ysize) {
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
buf = (UINT8*) im->image[y];
} else {
/* store last byte (used if line width is odd) */
buf[state->xsize-1] = (UINT8) packets;
}
packets = I16(data); data += 2;
}
for (p = x = 0; p < packets; p++) {
x += data[0]; /* pixel skip */
if (data[1] >= 128) {
i = 256-data[1]; /* run */
if (x + i + i > state->xsize)
break;
for (j = 0; j < i; j++) {
buf[x++] = data[2];
buf[x++] = data[3];
}
data += 2 + 2;
} else {
i = 2 * (int) data[1]; /* chunk */
if (x + i > state->xsize)
break;
memcpy(buf + x, data + 2, i);
data += 2 + i;
x += i;
}
}
if (p < packets)
break; /* didn't process all packets */
}
if (l < lines) {
/* didn't process all lines */
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
break;
case 12:
/* FLI LC chunk (byte delta) */
y = I16(data); ymax = y + I16(data+2); data += 4;
for (; y < ymax && y < state->ysize; y++) {
UINT8* out = (UINT8*) im->image[y];
int p, packets = *data++;
for (p = x = 0; p < packets; p++, x += i) {
x += data[0]; /* skip pixels */
if (data[1] & 0x80) {
i = 256-data[1]; /* run */
if (x + i > state->xsize)
break;
memset(out + x, data[2], i);
data += 3;
} else {
i = data[1]; /* chunk */
if (x + i > state->xsize)
break;
memcpy(out + x, data + 2, i);
data += i + 2;
}
}
if (p < packets)
break; /* didn't process all packets */
}
if (y < ymax) {
/* didn't process all lines */
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
break;
case 13:
/* FLI BLACK chunk */
for (y = 0; y < state->ysize; y++)
memset(im->image[y], 0, state->xsize);
break;
case 15:
/* FLI BRUN chunk */
for (y = 0; y < state->ysize; y++) {
UINT8* out = (UINT8*) im->image[y];
data += 1; /* ignore packetcount byte */
for (x = 0; x < state->xsize; x += i) {
if (data[0] & 0x80) {
i = 256 - data[0];
if (x + i > state->xsize)
break; /* safety first */
memcpy(out + x, data + 1, i);
data += i + 1;
} else {
i = data[0];
if (x + i > state->xsize)
break; /* safety first */
memset(out + x, data[1], i);
data += 2;
}
}
if (x != state->xsize) {
/* didn't unpack whole line */
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
}
break;
case 16:
/* COPY chunk */
for (y = 0; y < state->ysize; y++) {
UINT8* buf = (UINT8*) im->image[y];
memcpy(buf, data, state->xsize);
data += state->xsize;
}
break;
case 18:
/* PSTAMP chunk */
break; /* ignored */
default:
/* unknown chunk */
/* printf("unknown FLI/FLC chunk: %d\n", I16(ptr+4)); */
state->errcode = IMAGING_CODEC_UNKNOWN;
return -1;
}
advance = I32(ptr);
ptr += advance;
bytes -= advance;
}
return -1; /* end of frame */
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4589_2 |
crossvul-cpp_data_bad_3946_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* File System Virtual Channel
*
* Copyright 2010-2011 Vic Lee
* Copyright 2010-2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2015 Thincast Technologies GmbH
* Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
* Copyright 2016 David PHAM-VAN <d.phamvan@inuvika.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 <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/crt.h>
#include <winpr/path.h>
#include <winpr/file.h>
#include <winpr/string.h>
#include <winpr/synch.h>
#include <winpr/thread.h>
#include <winpr/stream.h>
#include <winpr/environment.h>
#include <winpr/interlocked.h>
#include <winpr/collections.h>
#include <winpr/shell.h>
#include <freerdp/channels/rdpdr.h>
#include "drive_file.h"
typedef struct _DRIVE_DEVICE DRIVE_DEVICE;
struct _DRIVE_DEVICE
{
DEVICE device;
WCHAR* path;
BOOL automount;
UINT32 PathLength;
wListDictionary* files;
HANDLE thread;
wMessageQueue* IrpQueue;
DEVMAN* devman;
rdpContext* rdpcontext;
};
static UINT sys_code_page = 0;
static DWORD drive_map_windows_err(DWORD fs_errno)
{
DWORD rc;
/* try to return NTSTATUS version of error code */
switch (fs_errno)
{
case STATUS_SUCCESS:
rc = STATUS_SUCCESS;
break;
case ERROR_ACCESS_DENIED:
case ERROR_SHARING_VIOLATION:
rc = STATUS_ACCESS_DENIED;
break;
case ERROR_FILE_NOT_FOUND:
rc = STATUS_NO_SUCH_FILE;
break;
case ERROR_BUSY_DRIVE:
rc = STATUS_DEVICE_BUSY;
break;
case ERROR_INVALID_DRIVE:
rc = STATUS_NO_SUCH_DEVICE;
break;
case ERROR_NOT_READY:
rc = STATUS_NO_SUCH_DEVICE;
break;
case ERROR_FILE_EXISTS:
case ERROR_ALREADY_EXISTS:
rc = STATUS_OBJECT_NAME_COLLISION;
break;
case ERROR_INVALID_NAME:
rc = STATUS_NO_SUCH_FILE;
break;
case ERROR_INVALID_HANDLE:
rc = STATUS_INVALID_HANDLE;
break;
case ERROR_NO_MORE_FILES:
rc = STATUS_NO_MORE_FILES;
break;
case ERROR_DIRECTORY:
rc = STATUS_NOT_A_DIRECTORY;
break;
case ERROR_PATH_NOT_FOUND:
rc = STATUS_OBJECT_PATH_NOT_FOUND;
break;
default:
rc = STATUS_UNSUCCESSFUL;
WLog_ERR(TAG, "Error code not found: %" PRIu32 "", fs_errno);
break;
}
return rc;
}
static DRIVE_FILE* drive_get_file_by_id(DRIVE_DEVICE* drive, UINT32 id)
{
DRIVE_FILE* file = NULL;
void* key = (void*)(size_t)id;
if (!drive)
return NULL;
file = (DRIVE_FILE*)ListDictionary_GetItemValue(drive->files, key);
return file;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_process_irp_create(DRIVE_DEVICE* drive, IRP* irp)
{
UINT32 FileId;
DRIVE_FILE* file;
BYTE Information;
UINT32 FileAttributes;
UINT32 SharedAccess;
UINT32 DesiredAccess;
UINT32 CreateDisposition;
UINT32 CreateOptions;
UINT32 PathLength;
UINT64 allocationSize;
const WCHAR* path;
if (!drive || !irp || !irp->devman || !irp->Complete)
return ERROR_INVALID_PARAMETER;
if (Stream_GetRemainingLength(irp->input) < 6 * 4 + 8)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, DesiredAccess);
Stream_Read_UINT64(irp->input, allocationSize);
Stream_Read_UINT32(irp->input, FileAttributes);
Stream_Read_UINT32(irp->input, SharedAccess);
Stream_Read_UINT32(irp->input, CreateDisposition);
Stream_Read_UINT32(irp->input, CreateOptions);
Stream_Read_UINT32(irp->input, PathLength);
if (Stream_GetRemainingLength(irp->input) < PathLength)
return ERROR_INVALID_DATA;
path = (const WCHAR*)Stream_Pointer(irp->input);
FileId = irp->devman->id_sequence++;
file = drive_file_new(drive->path, path, PathLength, FileId, DesiredAccess, CreateDisposition,
CreateOptions, FileAttributes, SharedAccess);
if (!file)
{
irp->IoStatus = drive_map_windows_err(GetLastError());
FileId = 0;
Information = 0;
}
else
{
void* key = (void*)(size_t)file->id;
if (!ListDictionary_Add(drive->files, key, file))
{
WLog_ERR(TAG, "ListDictionary_Add failed!");
return ERROR_INTERNAL_ERROR;
}
switch (CreateDisposition)
{
case FILE_SUPERSEDE:
case FILE_OPEN:
case FILE_CREATE:
case FILE_OVERWRITE:
Information = FILE_SUPERSEDED;
break;
case FILE_OPEN_IF:
Information = FILE_OPENED;
break;
case FILE_OVERWRITE_IF:
Information = FILE_OVERWRITTEN;
break;
default:
Information = 0;
break;
}
}
Stream_Write_UINT32(irp->output, FileId);
Stream_Write_UINT8(irp->output, Information);
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_process_irp_close(DRIVE_DEVICE* drive, IRP* irp)
{
void* key;
DRIVE_FILE* file;
if (!drive || !irp || !irp->Complete || !irp->output)
return ERROR_INVALID_PARAMETER;
file = drive_get_file_by_id(drive, irp->FileId);
key = (void*)(size_t)irp->FileId;
if (!file)
irp->IoStatus = STATUS_UNSUCCESSFUL;
else
{
ListDictionary_Remove(drive->files, key);
if (drive_file_free(file))
irp->IoStatus = STATUS_SUCCESS;
else
irp->IoStatus = drive_map_windows_err(GetLastError());
}
Stream_Zero(irp->output, 5); /* Padding(5) */
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_process_irp_read(DRIVE_DEVICE* drive, IRP* irp)
{
DRIVE_FILE* file;
UINT32 Length;
UINT64 Offset;
if (!drive || !irp || !irp->output || !irp->Complete)
return ERROR_INVALID_PARAMETER;
if (Stream_GetRemainingLength(irp->input) < 12)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, Length);
Stream_Read_UINT64(irp->input, Offset);
file = drive_get_file_by_id(drive, irp->FileId);
if (!file)
{
irp->IoStatus = STATUS_UNSUCCESSFUL;
Length = 0;
}
else if (!drive_file_seek(file, Offset))
{
irp->IoStatus = drive_map_windows_err(GetLastError());
Length = 0;
}
if (!Stream_EnsureRemainingCapacity(irp->output, Length + 4))
{
WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!");
return ERROR_INTERNAL_ERROR;
}
else if (Length == 0)
Stream_Write_UINT32(irp->output, 0);
else
{
BYTE* buffer = Stream_Pointer(irp->output) + sizeof(UINT32);
if (!drive_file_read(file, buffer, &Length))
{
irp->IoStatus = drive_map_windows_err(GetLastError());
Stream_Write_UINT32(irp->output, 0);
}
else
{
Stream_Write_UINT32(irp->output, Length);
Stream_Seek(irp->output, Length);
}
}
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_process_irp_write(DRIVE_DEVICE* drive, IRP* irp)
{
DRIVE_FILE* file;
UINT32 Length;
UINT64 Offset;
if (!drive || !irp || !irp->input || !irp->output || !irp->Complete)
return ERROR_INVALID_PARAMETER;
if (Stream_GetRemainingLength(irp->input) < 32)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, Length);
Stream_Read_UINT64(irp->input, Offset);
Stream_Seek(irp->input, 20); /* Padding */
file = drive_get_file_by_id(drive, irp->FileId);
if (!file)
{
irp->IoStatus = STATUS_UNSUCCESSFUL;
Length = 0;
}
else if (!drive_file_seek(file, Offset))
{
irp->IoStatus = drive_map_windows_err(GetLastError());
Length = 0;
}
else if (!drive_file_write(file, Stream_Pointer(irp->input), Length))
{
irp->IoStatus = drive_map_windows_err(GetLastError());
Length = 0;
}
Stream_Write_UINT32(irp->output, Length);
Stream_Write_UINT8(irp->output, 0); /* Padding */
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_process_irp_query_information(DRIVE_DEVICE* drive, IRP* irp)
{
DRIVE_FILE* file;
UINT32 FsInformationClass;
if (!drive || !irp || !irp->Complete)
return ERROR_INVALID_PARAMETER;
if (Stream_GetRemainingLength(irp->input) < 4)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, FsInformationClass);
file = drive_get_file_by_id(drive, irp->FileId);
if (!file)
{
irp->IoStatus = STATUS_UNSUCCESSFUL;
}
else if (!drive_file_query_information(file, FsInformationClass, irp->output))
{
irp->IoStatus = drive_map_windows_err(GetLastError());
}
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_process_irp_set_information(DRIVE_DEVICE* drive, IRP* irp)
{
DRIVE_FILE* file;
UINT32 FsInformationClass;
UINT32 Length;
if (!drive || !irp || !irp->Complete || !irp->input || !irp->output)
return ERROR_INVALID_PARAMETER;
if (Stream_GetRemainingLength(irp->input) < 32)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, FsInformationClass);
Stream_Read_UINT32(irp->input, Length);
Stream_Seek(irp->input, 24); /* Padding */
file = drive_get_file_by_id(drive, irp->FileId);
if (!file)
{
irp->IoStatus = STATUS_UNSUCCESSFUL;
}
else if (!drive_file_set_information(file, FsInformationClass, Length, irp->input))
{
irp->IoStatus = drive_map_windows_err(GetLastError());
}
if (file && file->is_dir && !PathIsDirectoryEmptyW(file->fullpath))
irp->IoStatus = STATUS_DIRECTORY_NOT_EMPTY;
Stream_Write_UINT32(irp->output, Length);
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_process_irp_query_volume_information(DRIVE_DEVICE* drive, IRP* irp)
{
UINT32 FsInformationClass;
wStream* output = NULL;
char* volumeLabel = { "FREERDP" };
char* diskType = { "FAT32" };
WCHAR* outStr = NULL;
int length;
DWORD lpSectorsPerCluster;
DWORD lpBytesPerSector;
DWORD lpNumberOfFreeClusters;
DWORD lpTotalNumberOfClusters;
WIN32_FILE_ATTRIBUTE_DATA wfad;
if (!drive || !irp)
return ERROR_INVALID_PARAMETER;
output = irp->output;
if (Stream_GetRemainingLength(irp->input) < 4)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, FsInformationClass);
GetDiskFreeSpaceW(drive->path, &lpSectorsPerCluster, &lpBytesPerSector, &lpNumberOfFreeClusters,
&lpTotalNumberOfClusters);
switch (FsInformationClass)
{
case FileFsVolumeInformation:
/* http://msdn.microsoft.com/en-us/library/cc232108.aspx */
if ((length = ConvertToUnicode(sys_code_page, 0, volumeLabel, -1, &outStr, 0) * 2) <= 0)
{
WLog_ERR(TAG, "ConvertToUnicode failed!");
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write_UINT32(output, 17 + length); /* Length */
if (!Stream_EnsureRemainingCapacity(output, 17 + length))
{
WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!");
free(outStr);
return CHANNEL_RC_NO_MEMORY;
}
GetFileAttributesExW(drive->path, GetFileExInfoStandard, &wfad);
Stream_Write_UINT32(output, wfad.ftCreationTime.dwLowDateTime); /* VolumeCreationTime */
Stream_Write_UINT32(output,
wfad.ftCreationTime.dwHighDateTime); /* VolumeCreationTime */
Stream_Write_UINT32(output, lpNumberOfFreeClusters & 0xffff); /* VolumeSerialNumber */
Stream_Write_UINT32(output, length); /* VolumeLabelLength */
Stream_Write_UINT8(output, 0); /* SupportsObjects */
/* Reserved(1), MUST NOT be added! */
Stream_Write(output, outStr, length); /* VolumeLabel (Unicode) */
free(outStr);
break;
case FileFsSizeInformation:
/* http://msdn.microsoft.com/en-us/library/cc232107.aspx */
Stream_Write_UINT32(output, 24); /* Length */
if (!Stream_EnsureRemainingCapacity(output, 24))
{
WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!");
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write_UINT64(output, lpTotalNumberOfClusters); /* TotalAllocationUnits */
Stream_Write_UINT64(output, lpNumberOfFreeClusters); /* AvailableAllocationUnits */
Stream_Write_UINT32(output, lpSectorsPerCluster); /* SectorsPerAllocationUnit */
Stream_Write_UINT32(output, lpBytesPerSector); /* BytesPerSector */
break;
case FileFsAttributeInformation:
/* http://msdn.microsoft.com/en-us/library/cc232101.aspx */
if ((length = ConvertToUnicode(sys_code_page, 0, diskType, -1, &outStr, 0) * 2) <= 0)
{
WLog_ERR(TAG, "ConvertToUnicode failed!");
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write_UINT32(output, 12 + length); /* Length */
if (!Stream_EnsureRemainingCapacity(output, 12 + length))
{
free(outStr);
WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!");
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write_UINT32(output, FILE_CASE_SENSITIVE_SEARCH | FILE_CASE_PRESERVED_NAMES |
FILE_UNICODE_ON_DISK); /* FileSystemAttributes */
Stream_Write_UINT32(output, MAX_PATH); /* MaximumComponentNameLength */
Stream_Write_UINT32(output, length); /* FileSystemNameLength */
Stream_Write(output, outStr, length); /* FileSystemName (Unicode) */
free(outStr);
break;
case FileFsFullSizeInformation:
/* http://msdn.microsoft.com/en-us/library/cc232104.aspx */
Stream_Write_UINT32(output, 32); /* Length */
if (!Stream_EnsureRemainingCapacity(output, 32))
{
WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!");
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write_UINT64(output, lpTotalNumberOfClusters); /* TotalAllocationUnits */
Stream_Write_UINT64(output,
lpNumberOfFreeClusters); /* CallerAvailableAllocationUnits */
Stream_Write_UINT64(output, lpNumberOfFreeClusters); /* AvailableAllocationUnits */
Stream_Write_UINT32(output, lpSectorsPerCluster); /* SectorsPerAllocationUnit */
Stream_Write_UINT32(output, lpBytesPerSector); /* BytesPerSector */
break;
case FileFsDeviceInformation:
/* http://msdn.microsoft.com/en-us/library/cc232109.aspx */
Stream_Write_UINT32(output, 8); /* Length */
if (!Stream_EnsureRemainingCapacity(output, 8))
{
WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!");
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write_UINT32(output, FILE_DEVICE_DISK); /* DeviceType */
Stream_Write_UINT32(output, 0); /* Characteristics */
break;
default:
irp->IoStatus = STATUS_UNSUCCESSFUL;
Stream_Write_UINT32(output, 0); /* Length */
break;
}
return irp->Complete(irp);
}
/* http://msdn.microsoft.com/en-us/library/cc241518.aspx */
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_process_irp_silent_ignore(DRIVE_DEVICE* drive, IRP* irp)
{
UINT32 FsInformationClass;
if (!drive || !irp || !irp->output || !irp->Complete)
return ERROR_INVALID_PARAMETER;
if (Stream_GetRemainingLength(irp->input) < 4)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, FsInformationClass);
Stream_Write_UINT32(irp->output, 0); /* Length */
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_process_irp_query_directory(DRIVE_DEVICE* drive, IRP* irp)
{
const WCHAR* path;
DRIVE_FILE* file;
BYTE InitialQuery;
UINT32 PathLength;
UINT32 FsInformationClass;
if (!drive || !irp || !irp->Complete)
return ERROR_INVALID_PARAMETER;
if (Stream_GetRemainingLength(irp->input) < 32)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, FsInformationClass);
Stream_Read_UINT8(irp->input, InitialQuery);
Stream_Read_UINT32(irp->input, PathLength);
Stream_Seek(irp->input, 23); /* Padding */
path = (WCHAR*)Stream_Pointer(irp->input);
file = drive_get_file_by_id(drive, irp->FileId);
if (file == NULL)
{
irp->IoStatus = STATUS_UNSUCCESSFUL;
Stream_Write_UINT32(irp->output, 0); /* Length */
}
else if (!drive_file_query_directory(file, FsInformationClass, InitialQuery, path, PathLength,
irp->output))
{
irp->IoStatus = drive_map_windows_err(GetLastError());
}
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_process_irp_directory_control(DRIVE_DEVICE* drive, IRP* irp)
{
if (!drive || !irp)
return ERROR_INVALID_PARAMETER;
switch (irp->MinorFunction)
{
case IRP_MN_QUERY_DIRECTORY:
return drive_process_irp_query_directory(drive, irp);
case IRP_MN_NOTIFY_CHANGE_DIRECTORY: /* TODO */
return irp->Discard(irp);
default:
irp->IoStatus = STATUS_NOT_SUPPORTED;
Stream_Write_UINT32(irp->output, 0); /* Length */
return irp->Complete(irp);
}
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_process_irp_device_control(DRIVE_DEVICE* drive, IRP* irp)
{
if (!drive || !irp)
return ERROR_INVALID_PARAMETER;
Stream_Write_UINT32(irp->output, 0); /* OutputBufferLength */
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_process_irp(DRIVE_DEVICE* drive, IRP* irp)
{
UINT error;
if (!drive || !irp)
return ERROR_INVALID_PARAMETER;
irp->IoStatus = STATUS_SUCCESS;
switch (irp->MajorFunction)
{
case IRP_MJ_CREATE:
error = drive_process_irp_create(drive, irp);
break;
case IRP_MJ_CLOSE:
error = drive_process_irp_close(drive, irp);
break;
case IRP_MJ_READ:
error = drive_process_irp_read(drive, irp);
break;
case IRP_MJ_WRITE:
error = drive_process_irp_write(drive, irp);
break;
case IRP_MJ_QUERY_INFORMATION:
error = drive_process_irp_query_information(drive, irp);
break;
case IRP_MJ_SET_INFORMATION:
error = drive_process_irp_set_information(drive, irp);
break;
case IRP_MJ_QUERY_VOLUME_INFORMATION:
error = drive_process_irp_query_volume_information(drive, irp);
break;
case IRP_MJ_LOCK_CONTROL:
error = drive_process_irp_silent_ignore(drive, irp);
break;
case IRP_MJ_DIRECTORY_CONTROL:
error = drive_process_irp_directory_control(drive, irp);
break;
case IRP_MJ_DEVICE_CONTROL:
error = drive_process_irp_device_control(drive, irp);
break;
default:
irp->IoStatus = STATUS_NOT_SUPPORTED;
error = irp->Complete(irp);
break;
}
return error;
}
static DWORD WINAPI drive_thread_func(LPVOID arg)
{
IRP* irp;
wMessage message;
DRIVE_DEVICE* drive = (DRIVE_DEVICE*)arg;
UINT error = CHANNEL_RC_OK;
if (!drive)
{
error = ERROR_INVALID_PARAMETER;
goto fail;
}
while (1)
{
if (!MessageQueue_Wait(drive->IrpQueue))
{
WLog_ERR(TAG, "MessageQueue_Wait failed!");
error = ERROR_INTERNAL_ERROR;
break;
}
if (!MessageQueue_Peek(drive->IrpQueue, &message, TRUE))
{
WLog_ERR(TAG, "MessageQueue_Peek failed!");
error = ERROR_INTERNAL_ERROR;
break;
}
if (message.id == WMQ_QUIT)
break;
irp = (IRP*)message.wParam;
if (irp)
{
if ((error = drive_process_irp(drive, irp)))
{
WLog_ERR(TAG, "drive_process_irp failed with error %" PRIu32 "!", error);
break;
}
}
}
fail:
if (error && drive && drive->rdpcontext)
setChannelError(drive->rdpcontext, error, "drive_thread_func reported an error");
ExitThread(error);
return error;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_irp_request(DEVICE* device, IRP* irp)
{
DRIVE_DEVICE* drive = (DRIVE_DEVICE*)device;
if (!drive)
return ERROR_INVALID_PARAMETER;
if (!MessageQueue_Post(drive->IrpQueue, NULL, 0, (void*)irp, NULL))
{
WLog_ERR(TAG, "MessageQueue_Post failed!");
return ERROR_INTERNAL_ERROR;
}
return CHANNEL_RC_OK;
}
static UINT drive_free_int(DRIVE_DEVICE* drive)
{
UINT error = CHANNEL_RC_OK;
if (!drive)
return ERROR_INVALID_PARAMETER;
CloseHandle(drive->thread);
ListDictionary_Free(drive->files);
MessageQueue_Free(drive->IrpQueue);
Stream_Free(drive->device.data, TRUE);
free(drive->path);
free(drive);
return error;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_free(DEVICE* device)
{
DRIVE_DEVICE* drive = (DRIVE_DEVICE*)device;
UINT error = CHANNEL_RC_OK;
if (!drive)
return ERROR_INVALID_PARAMETER;
if (MessageQueue_PostQuit(drive->IrpQueue, 0) &&
(WaitForSingleObject(drive->thread, INFINITE) == WAIT_FAILED))
{
error = GetLastError();
WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "", error);
return error;
}
return drive_free_int(drive);
}
/**
* Helper function used for freeing list dictionary value object
*/
static void drive_file_objfree(void* obj)
{
drive_file_free((DRIVE_FILE*)obj);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT drive_register_drive_path(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints, const char* name,
const char* path, BOOL automount)
{
size_t i, length;
DRIVE_DEVICE* drive;
UINT error = ERROR_INTERNAL_ERROR;
if (!pEntryPoints || !name || !path)
{
WLog_ERR(TAG, "[%s] Invalid parameters: pEntryPoints=%p, name=%p, path=%p", pEntryPoints,
name, path);
return ERROR_INVALID_PARAMETER;
}
if (name[0] && path[0])
{
size_t pathLength = strnlen(path, MAX_PATH);
drive = (DRIVE_DEVICE*)calloc(1, sizeof(DRIVE_DEVICE));
if (!drive)
{
WLog_ERR(TAG, "calloc failed!");
return CHANNEL_RC_NO_MEMORY;
}
drive->device.type = RDPDR_DTYP_FILESYSTEM;
drive->device.IRPRequest = drive_irp_request;
drive->device.Free = drive_free;
drive->rdpcontext = pEntryPoints->rdpcontext;
drive->automount = automount;
length = strlen(name);
drive->device.data = Stream_New(NULL, length + 1);
if (!drive->device.data)
{
WLog_ERR(TAG, "Stream_New failed!");
error = CHANNEL_RC_NO_MEMORY;
goto out_error;
}
for (i = 0; i < length; i++)
{
/* Filter 2.2.1.3 Device Announce Header (DEVICE_ANNOUNCE) forbidden symbols */
switch (name[i])
{
case ':':
case '<':
case '>':
case '\"':
case '/':
case '\\':
case '|':
case ' ':
Stream_Write_UINT8(drive->device.data, '_');
break;
default:
Stream_Write_UINT8(drive->device.data, (BYTE)name[i]);
break;
}
}
Stream_Write_UINT8(drive->device.data, '\0');
drive->device.name = (const char*)Stream_Buffer(drive->device.data);
if (!drive->device.name)
goto out_error;
if ((pathLength > 1) && (path[pathLength - 1] == '/'))
pathLength--;
if (ConvertToUnicode(sys_code_page, 0, path, pathLength, &drive->path, 0) <= 0)
{
WLog_ERR(TAG, "ConvertToUnicode failed!");
error = CHANNEL_RC_NO_MEMORY;
goto out_error;
}
drive->files = ListDictionary_New(TRUE);
if (!drive->files)
{
WLog_ERR(TAG, "ListDictionary_New failed!");
error = CHANNEL_RC_NO_MEMORY;
goto out_error;
}
ListDictionary_ValueObject(drive->files)->fnObjectFree = drive_file_objfree;
drive->IrpQueue = MessageQueue_New(NULL);
if (!drive->IrpQueue)
{
WLog_ERR(TAG, "ListDictionary_New failed!");
error = CHANNEL_RC_NO_MEMORY;
goto out_error;
}
if ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)drive)))
{
WLog_ERR(TAG, "RegisterDevice failed with error %" PRIu32 "!", error);
goto out_error;
}
if (!(drive->thread =
CreateThread(NULL, 0, drive_thread_func, drive, CREATE_SUSPENDED, NULL)))
{
WLog_ERR(TAG, "CreateThread failed!");
goto out_error;
}
ResumeThread(drive->thread);
}
return CHANNEL_RC_OK;
out_error:
drive_free_int(drive);
return error;
}
#ifdef BUILTIN_CHANNELS
#define DeviceServiceEntry drive_DeviceServiceEntry
#else
#define DeviceServiceEntry FREERDP_API DeviceServiceEntry
#endif
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
UINT DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)
{
RDPDR_DRIVE* drive;
UINT error;
#ifdef WIN32
char* dev;
int len;
char devlist[512], buf[512];
char* bufdup;
char* devdup;
#endif
drive = (RDPDR_DRIVE*)pEntryPoints->device;
#ifndef WIN32
sys_code_page = CP_UTF8;
if (strcmp(drive->Path, "*") == 0)
{
/* all drives */
free(drive->Path);
drive->Path = _strdup("/");
if (!drive->Path)
{
WLog_ERR(TAG, "_strdup failed!");
return CHANNEL_RC_NO_MEMORY;
}
}
else if (strcmp(drive->Path, "%") == 0)
{
free(drive->Path);
drive->Path = GetKnownPath(KNOWN_PATH_HOME);
if (!drive->Path)
{
WLog_ERR(TAG, "_strdup failed!");
return CHANNEL_RC_NO_MEMORY;
}
}
error = drive_register_drive_path(pEntryPoints, drive->Name, drive->Path, drive->automount);
#else
sys_code_page = GetACP();
/* Special case: path[0] == '*' -> export all drives */
/* Special case: path[0] == '%' -> user home dir */
if (strcmp(drive->Path, "%") == 0)
{
GetEnvironmentVariableA("USERPROFILE", buf, sizeof(buf));
PathCchAddBackslashA(buf, sizeof(buf));
free(drive->Path);
drive->Path = _strdup(buf);
if (!drive->Path)
{
WLog_ERR(TAG, "_strdup failed!");
return CHANNEL_RC_NO_MEMORY;
}
error = drive_register_drive_path(pEntryPoints, drive->Name, drive->Path, drive->automount);
}
else if (strcmp(drive->Path, "*") == 0)
{
int i;
/* Enumerate all devices: */
GetLogicalDriveStringsA(sizeof(devlist) - 1, devlist);
for (dev = devlist, i = 0; *dev; dev += 4, i++)
{
if (*dev > 'B')
{
/* Suppress disk drives A and B to avoid pesty messages */
len = sprintf_s(buf, sizeof(buf) - 4, "%s", drive->Name);
buf[len] = '_';
buf[len + 1] = dev[0];
buf[len + 2] = 0;
buf[len + 3] = 0;
if (!(bufdup = _strdup(buf)))
{
WLog_ERR(TAG, "_strdup failed!");
return CHANNEL_RC_NO_MEMORY;
}
if (!(devdup = _strdup(dev)))
{
WLog_ERR(TAG, "_strdup failed!");
return CHANNEL_RC_NO_MEMORY;
}
if ((error = drive_register_drive_path(pEntryPoints, bufdup, devdup, TRUE)))
{
break;
}
}
}
}
else
{
error = drive_register_drive_path(pEntryPoints, drive->Name, drive->Path, drive->automount);
}
#endif
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3946_0 |
crossvul-cpp_data_good_2645_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: Network File System (NFS) 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 "nfs.h"
#include "nfsfh.h"
#include "ip.h"
#include "ip6.h"
#include "rpc_auth.h"
#include "rpc_msg.h"
static const char tstr[] = " [|nfs]";
static void nfs_printfh(netdissect_options *, const uint32_t *, const u_int);
static int xid_map_enter(netdissect_options *, const struct sunrpc_msg *, const u_char *);
static int xid_map_find(const struct sunrpc_msg *, const u_char *,
uint32_t *, uint32_t *);
static void interp_reply(netdissect_options *, const struct sunrpc_msg *, uint32_t, uint32_t, int);
static const uint32_t *parse_post_op_attr(netdissect_options *, const uint32_t *, int);
/*
* Mapping of old NFS Version 2 RPC numbers to generic numbers.
*/
static uint32_t nfsv3_procid[NFS_NPROCS] = {
NFSPROC_NULL,
NFSPROC_GETATTR,
NFSPROC_SETATTR,
NFSPROC_NOOP,
NFSPROC_LOOKUP,
NFSPROC_READLINK,
NFSPROC_READ,
NFSPROC_NOOP,
NFSPROC_WRITE,
NFSPROC_CREATE,
NFSPROC_REMOVE,
NFSPROC_RENAME,
NFSPROC_LINK,
NFSPROC_SYMLINK,
NFSPROC_MKDIR,
NFSPROC_RMDIR,
NFSPROC_READDIR,
NFSPROC_FSSTAT,
NFSPROC_NOOP,
NFSPROC_NOOP,
NFSPROC_NOOP,
NFSPROC_NOOP,
NFSPROC_NOOP,
NFSPROC_NOOP,
NFSPROC_NOOP,
NFSPROC_NOOP
};
static const struct tok nfsproc_str[] = {
{ NFSPROC_NOOP, "nop" },
{ NFSPROC_NULL, "null" },
{ NFSPROC_GETATTR, "getattr" },
{ NFSPROC_SETATTR, "setattr" },
{ NFSPROC_LOOKUP, "lookup" },
{ NFSPROC_ACCESS, "access" },
{ NFSPROC_READLINK, "readlink" },
{ NFSPROC_READ, "read" },
{ NFSPROC_WRITE, "write" },
{ NFSPROC_CREATE, "create" },
{ NFSPROC_MKDIR, "mkdir" },
{ NFSPROC_SYMLINK, "symlink" },
{ NFSPROC_MKNOD, "mknod" },
{ NFSPROC_REMOVE, "remove" },
{ NFSPROC_RMDIR, "rmdir" },
{ NFSPROC_RENAME, "rename" },
{ NFSPROC_LINK, "link" },
{ NFSPROC_READDIR, "readdir" },
{ NFSPROC_READDIRPLUS, "readdirplus" },
{ NFSPROC_FSSTAT, "fsstat" },
{ NFSPROC_FSINFO, "fsinfo" },
{ NFSPROC_PATHCONF, "pathconf" },
{ NFSPROC_COMMIT, "commit" },
{ 0, NULL }
};
/*
* NFS V2 and V3 status values.
*
* Some of these come from the RFCs for NFS V2 and V3, with the message
* strings taken from the FreeBSD C library "errlst.c".
*
* Others are errors that are not in the RFC but that I suspect some
* NFS servers could return; the values are FreeBSD errno values, as
* the first NFS server was the SunOS 2.0 one, and until 5.0 SunOS
* was primarily BSD-derived.
*/
static const struct tok status2str[] = {
{ 1, "Operation not permitted" }, /* EPERM */
{ 2, "No such file or directory" }, /* ENOENT */
{ 5, "Input/output error" }, /* EIO */
{ 6, "Device not configured" }, /* ENXIO */
{ 11, "Resource deadlock avoided" }, /* EDEADLK */
{ 12, "Cannot allocate memory" }, /* ENOMEM */
{ 13, "Permission denied" }, /* EACCES */
{ 17, "File exists" }, /* EEXIST */
{ 18, "Cross-device link" }, /* EXDEV */
{ 19, "Operation not supported by device" }, /* ENODEV */
{ 20, "Not a directory" }, /* ENOTDIR */
{ 21, "Is a directory" }, /* EISDIR */
{ 22, "Invalid argument" }, /* EINVAL */
{ 26, "Text file busy" }, /* ETXTBSY */
{ 27, "File too large" }, /* EFBIG */
{ 28, "No space left on device" }, /* ENOSPC */
{ 30, "Read-only file system" }, /* EROFS */
{ 31, "Too many links" }, /* EMLINK */
{ 45, "Operation not supported" }, /* EOPNOTSUPP */
{ 62, "Too many levels of symbolic links" }, /* ELOOP */
{ 63, "File name too long" }, /* ENAMETOOLONG */
{ 66, "Directory not empty" }, /* ENOTEMPTY */
{ 69, "Disc quota exceeded" }, /* EDQUOT */
{ 70, "Stale NFS file handle" }, /* ESTALE */
{ 71, "Too many levels of remote in path" }, /* EREMOTE */
{ 99, "Write cache flushed to disk" }, /* NFSERR_WFLUSH (not used) */
{ 10001, "Illegal NFS file handle" }, /* NFS3ERR_BADHANDLE */
{ 10002, "Update synchronization mismatch" }, /* NFS3ERR_NOT_SYNC */
{ 10003, "READDIR/READDIRPLUS cookie is stale" }, /* NFS3ERR_BAD_COOKIE */
{ 10004, "Operation not supported" }, /* NFS3ERR_NOTSUPP */
{ 10005, "Buffer or request is too small" }, /* NFS3ERR_TOOSMALL */
{ 10006, "Unspecified error on server" }, /* NFS3ERR_SERVERFAULT */
{ 10007, "Object of that type not supported" }, /* NFS3ERR_BADTYPE */
{ 10008, "Request couldn't be completed in time" }, /* NFS3ERR_JUKEBOX */
{ 0, NULL }
};
static const struct tok nfsv3_writemodes[] = {
{ 0, "unstable" },
{ 1, "datasync" },
{ 2, "filesync" },
{ 0, NULL }
};
static const struct tok type2str[] = {
{ NFNON, "NON" },
{ NFREG, "REG" },
{ NFDIR, "DIR" },
{ NFBLK, "BLK" },
{ NFCHR, "CHR" },
{ NFLNK, "LNK" },
{ NFFIFO, "FIFO" },
{ 0, NULL }
};
static const struct tok sunrpc_auth_str[] = {
{ SUNRPC_AUTH_OK, "OK" },
{ SUNRPC_AUTH_BADCRED, "Bogus Credentials (seal broken)" },
{ SUNRPC_AUTH_REJECTEDCRED, "Rejected Credentials (client should begin new session)" },
{ SUNRPC_AUTH_BADVERF, "Bogus Verifier (seal broken)" },
{ SUNRPC_AUTH_REJECTEDVERF, "Verifier expired or was replayed" },
{ SUNRPC_AUTH_TOOWEAK, "Credentials are too weak" },
{ SUNRPC_AUTH_INVALIDRESP, "Bogus response verifier" },
{ SUNRPC_AUTH_FAILED, "Unknown failure" },
{ 0, NULL }
};
static const struct tok sunrpc_str[] = {
{ SUNRPC_PROG_UNAVAIL, "PROG_UNAVAIL" },
{ SUNRPC_PROG_MISMATCH, "PROG_MISMATCH" },
{ SUNRPC_PROC_UNAVAIL, "PROC_UNAVAIL" },
{ SUNRPC_GARBAGE_ARGS, "GARBAGE_ARGS" },
{ SUNRPC_SYSTEM_ERR, "SYSTEM_ERR" },
{ 0, NULL }
};
static void
print_nfsaddr(netdissect_options *ndo,
const u_char *bp, const char *s, const char *d)
{
const struct ip *ip;
const struct ip6_hdr *ip6;
char srcaddr[INET6_ADDRSTRLEN], dstaddr[INET6_ADDRSTRLEN];
srcaddr[0] = dstaddr[0] = '\0';
switch (IP_V((const struct ip *)bp)) {
case 4:
ip = (const struct ip *)bp;
strlcpy(srcaddr, ipaddr_string(ndo, &ip->ip_src), sizeof(srcaddr));
strlcpy(dstaddr, ipaddr_string(ndo, &ip->ip_dst), sizeof(dstaddr));
break;
case 6:
ip6 = (const struct ip6_hdr *)bp;
strlcpy(srcaddr, ip6addr_string(ndo, &ip6->ip6_src),
sizeof(srcaddr));
strlcpy(dstaddr, ip6addr_string(ndo, &ip6->ip6_dst),
sizeof(dstaddr));
break;
default:
strlcpy(srcaddr, "?", sizeof(srcaddr));
strlcpy(dstaddr, "?", sizeof(dstaddr));
break;
}
ND_PRINT((ndo, "%s.%s > %s.%s: ", srcaddr, s, dstaddr, d));
}
static const uint32_t *
parse_sattr3(netdissect_options *ndo,
const uint32_t *dp, struct nfsv3_sattr *sa3)
{
ND_TCHECK(dp[0]);
sa3->sa_modeset = EXTRACT_32BITS(dp);
dp++;
if (sa3->sa_modeset) {
ND_TCHECK(dp[0]);
sa3->sa_mode = EXTRACT_32BITS(dp);
dp++;
}
ND_TCHECK(dp[0]);
sa3->sa_uidset = EXTRACT_32BITS(dp);
dp++;
if (sa3->sa_uidset) {
ND_TCHECK(dp[0]);
sa3->sa_uid = EXTRACT_32BITS(dp);
dp++;
}
ND_TCHECK(dp[0]);
sa3->sa_gidset = EXTRACT_32BITS(dp);
dp++;
if (sa3->sa_gidset) {
ND_TCHECK(dp[0]);
sa3->sa_gid = EXTRACT_32BITS(dp);
dp++;
}
ND_TCHECK(dp[0]);
sa3->sa_sizeset = EXTRACT_32BITS(dp);
dp++;
if (sa3->sa_sizeset) {
ND_TCHECK(dp[0]);
sa3->sa_size = EXTRACT_32BITS(dp);
dp++;
}
ND_TCHECK(dp[0]);
sa3->sa_atimetype = EXTRACT_32BITS(dp);
dp++;
if (sa3->sa_atimetype == NFSV3SATTRTIME_TOCLIENT) {
ND_TCHECK(dp[1]);
sa3->sa_atime.nfsv3_sec = EXTRACT_32BITS(dp);
dp++;
sa3->sa_atime.nfsv3_nsec = EXTRACT_32BITS(dp);
dp++;
}
ND_TCHECK(dp[0]);
sa3->sa_mtimetype = EXTRACT_32BITS(dp);
dp++;
if (sa3->sa_mtimetype == NFSV3SATTRTIME_TOCLIENT) {
ND_TCHECK(dp[1]);
sa3->sa_mtime.nfsv3_sec = EXTRACT_32BITS(dp);
dp++;
sa3->sa_mtime.nfsv3_nsec = EXTRACT_32BITS(dp);
dp++;
}
return dp;
trunc:
return NULL;
}
static int nfserr; /* true if we error rather than trunc */
static void
print_sattr3(netdissect_options *ndo,
const struct nfsv3_sattr *sa3, int verbose)
{
if (sa3->sa_modeset)
ND_PRINT((ndo, " mode %o", sa3->sa_mode));
if (sa3->sa_uidset)
ND_PRINT((ndo, " uid %u", sa3->sa_uid));
if (sa3->sa_gidset)
ND_PRINT((ndo, " gid %u", sa3->sa_gid));
if (verbose > 1) {
if (sa3->sa_atimetype == NFSV3SATTRTIME_TOCLIENT)
ND_PRINT((ndo, " atime %u.%06u", sa3->sa_atime.nfsv3_sec,
sa3->sa_atime.nfsv3_nsec));
if (sa3->sa_mtimetype == NFSV3SATTRTIME_TOCLIENT)
ND_PRINT((ndo, " mtime %u.%06u", sa3->sa_mtime.nfsv3_sec,
sa3->sa_mtime.nfsv3_nsec));
}
}
void
nfsreply_print(netdissect_options *ndo,
register const u_char *bp, u_int length,
register const u_char *bp2)
{
register const struct sunrpc_msg *rp;
char srcid[20], dstid[20]; /*fits 32bit*/
nfserr = 0; /* assume no error */
rp = (const struct sunrpc_msg *)bp;
ND_TCHECK(rp->rm_xid);
if (!ndo->ndo_nflag) {
strlcpy(srcid, "nfs", sizeof(srcid));
snprintf(dstid, sizeof(dstid), "%u",
EXTRACT_32BITS(&rp->rm_xid));
} else {
snprintf(srcid, sizeof(srcid), "%u", NFS_PORT);
snprintf(dstid, sizeof(dstid), "%u",
EXTRACT_32BITS(&rp->rm_xid));
}
print_nfsaddr(ndo, bp2, srcid, dstid);
nfsreply_print_noaddr(ndo, bp, length, bp2);
return;
trunc:
if (!nfserr)
ND_PRINT((ndo, "%s", tstr));
}
void
nfsreply_print_noaddr(netdissect_options *ndo,
register const u_char *bp, u_int length,
register const u_char *bp2)
{
register const struct sunrpc_msg *rp;
uint32_t proc, vers, reply_stat;
enum sunrpc_reject_stat rstat;
uint32_t rlow;
uint32_t rhigh;
enum sunrpc_auth_stat rwhy;
nfserr = 0; /* assume no error */
rp = (const struct sunrpc_msg *)bp;
ND_TCHECK(rp->rm_reply.rp_stat);
reply_stat = EXTRACT_32BITS(&rp->rm_reply.rp_stat);
switch (reply_stat) {
case SUNRPC_MSG_ACCEPTED:
ND_PRINT((ndo, "reply ok %u", length));
if (xid_map_find(rp, bp2, &proc, &vers) >= 0)
interp_reply(ndo, rp, proc, vers, length);
break;
case SUNRPC_MSG_DENIED:
ND_PRINT((ndo, "reply ERR %u: ", length));
ND_TCHECK(rp->rm_reply.rp_reject.rj_stat);
rstat = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_stat);
switch (rstat) {
case SUNRPC_RPC_MISMATCH:
ND_TCHECK(rp->rm_reply.rp_reject.rj_vers.high);
rlow = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_vers.low);
rhigh = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_vers.high);
ND_PRINT((ndo, "RPC Version mismatch (%u-%u)", rlow, rhigh));
break;
case SUNRPC_AUTH_ERROR:
ND_TCHECK(rp->rm_reply.rp_reject.rj_why);
rwhy = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_why);
ND_PRINT((ndo, "Auth %s", tok2str(sunrpc_auth_str, "Invalid failure code %u", rwhy)));
break;
default:
ND_PRINT((ndo, "Unknown reason for rejecting rpc message %u", (unsigned int)rstat));
break;
}
break;
default:
ND_PRINT((ndo, "reply Unknown rpc response code=%u %u", reply_stat, length));
break;
}
return;
trunc:
if (!nfserr)
ND_PRINT((ndo, "%s", tstr));
}
/*
* Return a pointer to the first file handle in the packet.
* If the packet was truncated, return 0.
*/
static const uint32_t *
parsereq(netdissect_options *ndo,
register const struct sunrpc_msg *rp, register u_int length)
{
register const uint32_t *dp;
register u_int len;
/*
* find the start of the req data (if we captured it)
*/
dp = (const uint32_t *)&rp->rm_call.cb_cred;
ND_TCHECK(dp[1]);
len = EXTRACT_32BITS(&dp[1]);
if (len < length) {
dp += (len + (2 * sizeof(*dp) + 3)) / sizeof(*dp);
ND_TCHECK(dp[1]);
len = EXTRACT_32BITS(&dp[1]);
if (len < length) {
dp += (len + (2 * sizeof(*dp) + 3)) / sizeof(*dp);
ND_TCHECK2(dp[0], 0);
return (dp);
}
}
trunc:
return (NULL);
}
/*
* Print out an NFS file handle and return a pointer to following word.
* If packet was truncated, return 0.
*/
static const uint32_t *
parsefh(netdissect_options *ndo,
register const uint32_t *dp, int v3)
{
u_int len;
if (v3) {
ND_TCHECK(dp[0]);
len = EXTRACT_32BITS(dp) / 4;
dp++;
} else
len = NFSX_V2FH / 4;
if (ND_TTEST2(*dp, len * sizeof(*dp))) {
nfs_printfh(ndo, dp, len);
return (dp + len);
}
trunc:
return (NULL);
}
/*
* Print out a file name and return pointer to 32-bit word past it.
* If packet was truncated, return 0.
*/
static const uint32_t *
parsefn(netdissect_options *ndo,
register const uint32_t *dp)
{
register uint32_t len;
register const u_char *cp;
/* Bail if we don't have the string length */
ND_TCHECK(*dp);
/* Fetch string length; convert to host order */
len = *dp++;
NTOHL(len);
ND_TCHECK2(*dp, ((len + 3) & ~3));
cp = (const u_char *)dp;
/* Update 32-bit pointer (NFS filenames padded to 32-bit boundaries) */
dp += ((len + 3) & ~3) / sizeof(*dp);
ND_PRINT((ndo, "\""));
if (fn_printn(ndo, cp, len, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
return (dp);
trunc:
return NULL;
}
/*
* Print out file handle and file name.
* Return pointer to 32-bit word past file name.
* If packet was truncated (or there was some other error), return 0.
*/
static const uint32_t *
parsefhn(netdissect_options *ndo,
register const uint32_t *dp, int v3)
{
dp = parsefh(ndo, dp, v3);
if (dp == NULL)
return (NULL);
ND_PRINT((ndo, " "));
return (parsefn(ndo, dp));
}
void
nfsreq_print_noaddr(netdissect_options *ndo,
register const u_char *bp, u_int length,
register const u_char *bp2)
{
register const struct sunrpc_msg *rp;
register const uint32_t *dp;
nfs_type type;
int v3;
uint32_t proc;
uint32_t access_flags;
struct nfsv3_sattr sa3;
ND_PRINT((ndo, "%d", length));
nfserr = 0; /* assume no error */
rp = (const struct sunrpc_msg *)bp;
if (!xid_map_enter(ndo, rp, bp2)) /* record proc number for later on */
goto trunc;
v3 = (EXTRACT_32BITS(&rp->rm_call.cb_vers) == NFS_VER3);
proc = EXTRACT_32BITS(&rp->rm_call.cb_proc);
if (!v3 && proc < NFS_NPROCS)
proc = nfsv3_procid[proc];
ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc)));
switch (proc) {
case NFSPROC_GETATTR:
case NFSPROC_SETATTR:
case NFSPROC_READLINK:
case NFSPROC_FSSTAT:
case NFSPROC_FSINFO:
case NFSPROC_PATHCONF:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
parsefh(ndo, dp, v3) != NULL)
return;
break;
case NFSPROC_LOOKUP:
case NFSPROC_CREATE:
case NFSPROC_MKDIR:
case NFSPROC_REMOVE:
case NFSPROC_RMDIR:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
parsefhn(ndo, dp, v3) != NULL)
return;
break;
case NFSPROC_ACCESS:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_TCHECK(dp[0]);
access_flags = EXTRACT_32BITS(&dp[0]);
if (access_flags & ~NFSV3ACCESS_FULL) {
/* NFSV3ACCESS definitions aren't up to date */
ND_PRINT((ndo, " %04x", access_flags));
} else if ((access_flags & NFSV3ACCESS_FULL) == NFSV3ACCESS_FULL) {
ND_PRINT((ndo, " NFS_ACCESS_FULL"));
} else {
char separator = ' ';
if (access_flags & NFSV3ACCESS_READ) {
ND_PRINT((ndo, " NFS_ACCESS_READ"));
separator = '|';
}
if (access_flags & NFSV3ACCESS_LOOKUP) {
ND_PRINT((ndo, "%cNFS_ACCESS_LOOKUP", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_MODIFY) {
ND_PRINT((ndo, "%cNFS_ACCESS_MODIFY", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_EXTEND) {
ND_PRINT((ndo, "%cNFS_ACCESS_EXTEND", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_DELETE) {
ND_PRINT((ndo, "%cNFS_ACCESS_DELETE", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_EXECUTE)
ND_PRINT((ndo, "%cNFS_ACCESS_EXECUTE", separator));
}
return;
}
break;
case NFSPROC_READ:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
if (v3) {
ND_TCHECK(dp[2]);
ND_PRINT((ndo, " %u bytes @ %" PRIu64,
EXTRACT_32BITS(&dp[2]),
EXTRACT_64BITS(&dp[0])));
} else {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " %u bytes @ %u",
EXTRACT_32BITS(&dp[1]),
EXTRACT_32BITS(&dp[0])));
}
return;
}
break;
case NFSPROC_WRITE:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
if (v3) {
ND_TCHECK(dp[4]);
ND_PRINT((ndo, " %u (%u) bytes @ %" PRIu64,
EXTRACT_32BITS(&dp[4]),
EXTRACT_32BITS(&dp[2]),
EXTRACT_64BITS(&dp[0])));
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " <%s>",
tok2str(nfsv3_writemodes,
NULL, EXTRACT_32BITS(&dp[3]))));
}
} else {
ND_TCHECK(dp[3]);
ND_PRINT((ndo, " %u (%u) bytes @ %u (%u)",
EXTRACT_32BITS(&dp[3]),
EXTRACT_32BITS(&dp[2]),
EXTRACT_32BITS(&dp[1]),
EXTRACT_32BITS(&dp[0])));
}
return;
}
break;
case NFSPROC_SYMLINK:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefhn(ndo, dp, v3)) != NULL) {
ND_PRINT((ndo, " ->"));
if (v3 && (dp = parse_sattr3(ndo, dp, &sa3)) == NULL)
break;
if (parsefn(ndo, dp) == NULL)
break;
if (v3 && ndo->ndo_vflag)
print_sattr3(ndo, &sa3, ndo->ndo_vflag);
return;
}
break;
case NFSPROC_MKNOD:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefhn(ndo, dp, v3)) != NULL) {
ND_TCHECK(*dp);
type = (nfs_type)EXTRACT_32BITS(dp);
dp++;
if ((dp = parse_sattr3(ndo, dp, &sa3)) == NULL)
break;
ND_PRINT((ndo, " %s", tok2str(type2str, "unk-ft %d", type)));
if (ndo->ndo_vflag && (type == NFCHR || type == NFBLK)) {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " %u/%u",
EXTRACT_32BITS(&dp[0]),
EXTRACT_32BITS(&dp[1])));
dp += 2;
}
if (ndo->ndo_vflag)
print_sattr3(ndo, &sa3, ndo->ndo_vflag);
return;
}
break;
case NFSPROC_RENAME:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefhn(ndo, dp, v3)) != NULL) {
ND_PRINT((ndo, " ->"));
if (parsefhn(ndo, dp, v3) != NULL)
return;
}
break;
case NFSPROC_LINK:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_PRINT((ndo, " ->"));
if (parsefhn(ndo, dp, v3) != NULL)
return;
}
break;
case NFSPROC_READDIR:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
if (v3) {
ND_TCHECK(dp[4]);
/*
* We shouldn't really try to interpret the
* offset cookie here.
*/
ND_PRINT((ndo, " %u bytes @ %" PRId64,
EXTRACT_32BITS(&dp[4]),
EXTRACT_64BITS(&dp[0])));
if (ndo->ndo_vflag)
ND_PRINT((ndo, " verf %08x%08x", dp[2], dp[3]));
} else {
ND_TCHECK(dp[1]);
/*
* Print the offset as signed, since -1 is
* common, but offsets > 2^31 aren't.
*/
ND_PRINT((ndo, " %u bytes @ %d",
EXTRACT_32BITS(&dp[1]),
EXTRACT_32BITS(&dp[0])));
}
return;
}
break;
case NFSPROC_READDIRPLUS:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_TCHECK(dp[4]);
/*
* We don't try to interpret the offset
* cookie here.
*/
ND_PRINT((ndo, " %u bytes @ %" PRId64,
EXTRACT_32BITS(&dp[4]),
EXTRACT_64BITS(&dp[0])));
if (ndo->ndo_vflag) {
ND_TCHECK(dp[5]);
ND_PRINT((ndo, " max %u verf %08x%08x",
EXTRACT_32BITS(&dp[5]), dp[2], dp[3]));
}
return;
}
break;
case NFSPROC_COMMIT:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_TCHECK(dp[2]);
ND_PRINT((ndo, " %u bytes @ %" PRIu64,
EXTRACT_32BITS(&dp[2]),
EXTRACT_64BITS(&dp[0])));
return;
}
break;
default:
return;
}
trunc:
if (!nfserr)
ND_PRINT((ndo, "%s", tstr));
}
/*
* Print out an NFS file handle.
* We assume packet was not truncated before the end of the
* file handle pointed to by dp.
*
* Note: new version (using portable file-handle parser) doesn't produce
* generation number. It probably could be made to do that, with some
* additional hacking on the parser code.
*/
static void
nfs_printfh(netdissect_options *ndo,
register const uint32_t *dp, const u_int len)
{
my_fsid fsid;
uint32_t ino;
const char *sfsname = NULL;
char *spacep;
if (ndo->ndo_uflag) {
u_int i;
char const *sep = "";
ND_PRINT((ndo, " fh["));
for (i=0; i<len; i++) {
ND_PRINT((ndo, "%s%x", sep, dp[i]));
sep = ":";
}
ND_PRINT((ndo, "]"));
return;
}
Parse_fh((const u_char *)dp, len, &fsid, &ino, NULL, &sfsname, 0);
if (sfsname) {
/* file system ID is ASCII, not numeric, for this server OS */
static char temp[NFSX_V3FHMAX+1];
/* Make sure string is null-terminated */
strncpy(temp, sfsname, NFSX_V3FHMAX);
temp[sizeof(temp) - 1] = '\0';
/* Remove trailing spaces */
spacep = strchr(temp, ' ');
if (spacep)
*spacep = '\0';
ND_PRINT((ndo, " fh %s/", temp));
} else {
ND_PRINT((ndo, " fh %d,%d/",
fsid.Fsid_dev.Major, fsid.Fsid_dev.Minor));
}
if(fsid.Fsid_dev.Minor == 257)
/* Print the undecoded handle */
ND_PRINT((ndo, "%s", fsid.Opaque_Handle));
else
ND_PRINT((ndo, "%ld", (long) ino));
}
/*
* Maintain a small cache of recent client.XID.server/proc pairs, to allow
* us to match up replies with requests and thus to know how to parse
* the reply.
*/
struct xid_map_entry {
uint32_t xid; /* transaction ID (net order) */
int ipver; /* IP version (4 or 6) */
struct in6_addr client; /* client IP address (net order) */
struct in6_addr server; /* server IP address (net order) */
uint32_t proc; /* call proc number (host order) */
uint32_t vers; /* program version (host order) */
};
/*
* Map entries are kept in an array that we manage as a ring;
* new entries are always added at the tail of the ring. Initially,
* all the entries are zero and hence don't match anything.
*/
#define XIDMAPSIZE 64
static struct xid_map_entry xid_map[XIDMAPSIZE];
static int xid_map_next = 0;
static int xid_map_hint = 0;
static int
xid_map_enter(netdissect_options *ndo,
const struct sunrpc_msg *rp, const u_char *bp)
{
const struct ip *ip = NULL;
const struct ip6_hdr *ip6 = NULL;
struct xid_map_entry *xmep;
if (!ND_TTEST(rp->rm_call.cb_vers))
return (0);
switch (IP_V((const struct ip *)bp)) {
case 4:
ip = (const struct ip *)bp;
break;
case 6:
ip6 = (const struct ip6_hdr *)bp;
break;
default:
return (1);
}
xmep = &xid_map[xid_map_next];
if (++xid_map_next >= XIDMAPSIZE)
xid_map_next = 0;
UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid));
if (ip) {
xmep->ipver = 4;
UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src));
UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst));
}
else if (ip6) {
xmep->ipver = 6;
UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src));
UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
}
xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc);
xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers);
return (1);
}
/*
* Returns 0 and puts NFSPROC_xxx in proc return and
* version in vers return, or returns -1 on failure
*/
static int
xid_map_find(const struct sunrpc_msg *rp, const u_char *bp, uint32_t *proc,
uint32_t *vers)
{
int i;
struct xid_map_entry *xmep;
uint32_t xid;
const struct ip *ip = (const struct ip *)bp;
const struct ip6_hdr *ip6 = (const struct ip6_hdr *)bp;
int cmp;
UNALIGNED_MEMCPY(&xid, &rp->rm_xid, sizeof(xmep->xid));
/* Start searching from where we last left off */
i = xid_map_hint;
do {
xmep = &xid_map[i];
cmp = 1;
if (xmep->ipver != IP_V(ip) || xmep->xid != xid)
goto nextitem;
switch (xmep->ipver) {
case 4:
if (UNALIGNED_MEMCMP(&ip->ip_src, &xmep->server,
sizeof(ip->ip_src)) != 0 ||
UNALIGNED_MEMCMP(&ip->ip_dst, &xmep->client,
sizeof(ip->ip_dst)) != 0) {
cmp = 0;
}
break;
case 6:
if (UNALIGNED_MEMCMP(&ip6->ip6_src, &xmep->server,
sizeof(ip6->ip6_src)) != 0 ||
UNALIGNED_MEMCMP(&ip6->ip6_dst, &xmep->client,
sizeof(ip6->ip6_dst)) != 0) {
cmp = 0;
}
break;
default:
cmp = 0;
break;
}
if (cmp) {
/* match */
xid_map_hint = i;
*proc = xmep->proc;
*vers = xmep->vers;
return 0;
}
nextitem:
if (++i >= XIDMAPSIZE)
i = 0;
} while (i != xid_map_hint);
/* search failed */
return (-1);
}
/*
* Routines for parsing reply packets
*/
/*
* Return a pointer to the beginning of the actual results.
* If the packet was truncated, return 0.
*/
static const uint32_t *
parserep(netdissect_options *ndo,
register const struct sunrpc_msg *rp, register u_int length)
{
register const uint32_t *dp;
u_int len;
enum sunrpc_accept_stat astat;
/*
* Portability note:
* Here we find the address of the ar_verf credentials.
* Originally, this calculation was
* dp = (uint32_t *)&rp->rm_reply.rp_acpt.ar_verf
* On the wire, the rp_acpt field starts immediately after
* the (32 bit) rp_stat field. However, rp_acpt (which is a
* "struct accepted_reply") contains a "struct opaque_auth",
* whose internal representation contains a pointer, so on a
* 64-bit machine the compiler inserts 32 bits of padding
* before rp->rm_reply.rp_acpt.ar_verf. So, we cannot use
* the internal representation to parse the on-the-wire
* representation. Instead, we skip past the rp_stat field,
* which is an "enum" and so occupies one 32-bit word.
*/
dp = ((const uint32_t *)&rp->rm_reply) + 1;
ND_TCHECK(dp[1]);
len = EXTRACT_32BITS(&dp[1]);
if (len >= length)
return (NULL);
/*
* skip past the ar_verf credentials.
*/
dp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t);
/*
* now we can check the ar_stat field
*/
ND_TCHECK(dp[0]);
astat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp);
if (astat != SUNRPC_SUCCESS) {
ND_PRINT((ndo, " %s", tok2str(sunrpc_str, "ar_stat %d", astat)));
nfserr = 1; /* suppress trunc string */
return (NULL);
}
/* successful return */
ND_TCHECK2(*dp, sizeof(astat));
return ((const uint32_t *) (sizeof(astat) + ((const char *)dp)));
trunc:
return (0);
}
static const uint32_t *
parsestatus(netdissect_options *ndo,
const uint32_t *dp, int *er)
{
int errnum;
ND_TCHECK(dp[0]);
errnum = EXTRACT_32BITS(&dp[0]);
if (er)
*er = errnum;
if (errnum != 0) {
if (!ndo->ndo_qflag)
ND_PRINT((ndo, " ERROR: %s",
tok2str(status2str, "unk %d", errnum)));
nfserr = 1;
}
return (dp + 1);
trunc:
return NULL;
}
static const uint32_t *
parsefattr(netdissect_options *ndo,
const uint32_t *dp, int verbose, int v3)
{
const struct nfs_fattr *fap;
fap = (const struct nfs_fattr *)dp;
ND_TCHECK(fap->fa_gid);
if (verbose) {
ND_PRINT((ndo, " %s %o ids %d/%d",
tok2str(type2str, "unk-ft %d ",
EXTRACT_32BITS(&fap->fa_type)),
EXTRACT_32BITS(&fap->fa_mode),
EXTRACT_32BITS(&fap->fa_uid),
EXTRACT_32BITS(&fap->fa_gid)));
if (v3) {
ND_TCHECK(fap->fa3_size);
ND_PRINT((ndo, " sz %" PRIu64,
EXTRACT_64BITS((const uint32_t *)&fap->fa3_size)));
} else {
ND_TCHECK(fap->fa2_size);
ND_PRINT((ndo, " sz %d", EXTRACT_32BITS(&fap->fa2_size)));
}
}
/* print lots more stuff */
if (verbose > 1) {
if (v3) {
ND_TCHECK(fap->fa3_ctime);
ND_PRINT((ndo, " nlink %d rdev %d/%d",
EXTRACT_32BITS(&fap->fa_nlink),
EXTRACT_32BITS(&fap->fa3_rdev.specdata1),
EXTRACT_32BITS(&fap->fa3_rdev.specdata2)));
ND_PRINT((ndo, " fsid %" PRIx64,
EXTRACT_64BITS((const uint32_t *)&fap->fa3_fsid)));
ND_PRINT((ndo, " fileid %" PRIx64,
EXTRACT_64BITS((const uint32_t *)&fap->fa3_fileid)));
ND_PRINT((ndo, " a/m/ctime %u.%06u",
EXTRACT_32BITS(&fap->fa3_atime.nfsv3_sec),
EXTRACT_32BITS(&fap->fa3_atime.nfsv3_nsec)));
ND_PRINT((ndo, " %u.%06u",
EXTRACT_32BITS(&fap->fa3_mtime.nfsv3_sec),
EXTRACT_32BITS(&fap->fa3_mtime.nfsv3_nsec)));
ND_PRINT((ndo, " %u.%06u",
EXTRACT_32BITS(&fap->fa3_ctime.nfsv3_sec),
EXTRACT_32BITS(&fap->fa3_ctime.nfsv3_nsec)));
} else {
ND_TCHECK(fap->fa2_ctime);
ND_PRINT((ndo, " nlink %d rdev 0x%x fsid 0x%x nodeid 0x%x a/m/ctime",
EXTRACT_32BITS(&fap->fa_nlink),
EXTRACT_32BITS(&fap->fa2_rdev),
EXTRACT_32BITS(&fap->fa2_fsid),
EXTRACT_32BITS(&fap->fa2_fileid)));
ND_PRINT((ndo, " %u.%06u",
EXTRACT_32BITS(&fap->fa2_atime.nfsv2_sec),
EXTRACT_32BITS(&fap->fa2_atime.nfsv2_usec)));
ND_PRINT((ndo, " %u.%06u",
EXTRACT_32BITS(&fap->fa2_mtime.nfsv2_sec),
EXTRACT_32BITS(&fap->fa2_mtime.nfsv2_usec)));
ND_PRINT((ndo, " %u.%06u",
EXTRACT_32BITS(&fap->fa2_ctime.nfsv2_sec),
EXTRACT_32BITS(&fap->fa2_ctime.nfsv2_usec)));
}
}
return ((const uint32_t *)((const unsigned char *)dp +
(v3 ? NFSX_V3FATTR : NFSX_V2FATTR)));
trunc:
return (NULL);
}
static int
parseattrstat(netdissect_options *ndo,
const uint32_t *dp, int verbose, int v3)
{
int er;
dp = parsestatus(ndo, dp, &er);
if (dp == NULL)
return (0);
if (er)
return (1);
return (parsefattr(ndo, dp, verbose, v3) != NULL);
}
static int
parsediropres(netdissect_options *ndo,
const uint32_t *dp)
{
int er;
if (!(dp = parsestatus(ndo, dp, &er)))
return (0);
if (er)
return (1);
dp = parsefh(ndo, dp, 0);
if (dp == NULL)
return (0);
return (parsefattr(ndo, dp, ndo->ndo_vflag, 0) != NULL);
}
static int
parselinkres(netdissect_options *ndo,
const uint32_t *dp, int v3)
{
int er;
dp = parsestatus(ndo, dp, &er);
if (dp == NULL)
return(0);
if (er)
return(1);
if (v3 && !(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
return (0);
ND_PRINT((ndo, " "));
return (parsefn(ndo, dp) != NULL);
}
static int
parsestatfs(netdissect_options *ndo,
const uint32_t *dp, int v3)
{
const struct nfs_statfs *sfsp;
int er;
dp = parsestatus(ndo, dp, &er);
if (dp == NULL)
return (0);
if (!v3 && er)
return (1);
if (ndo->ndo_qflag)
return(1);
if (v3) {
if (ndo->ndo_vflag)
ND_PRINT((ndo, " POST:"));
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
return (0);
}
ND_TCHECK2(*dp, (v3 ? NFSX_V3STATFS : NFSX_V2STATFS));
sfsp = (const struct nfs_statfs *)dp;
if (v3) {
ND_PRINT((ndo, " tbytes %" PRIu64 " fbytes %" PRIu64 " abytes %" PRIu64,
EXTRACT_64BITS((const uint32_t *)&sfsp->sf_tbytes),
EXTRACT_64BITS((const uint32_t *)&sfsp->sf_fbytes),
EXTRACT_64BITS((const uint32_t *)&sfsp->sf_abytes)));
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " tfiles %" PRIu64 " ffiles %" PRIu64 " afiles %" PRIu64 " invar %u",
EXTRACT_64BITS((const uint32_t *)&sfsp->sf_tfiles),
EXTRACT_64BITS((const uint32_t *)&sfsp->sf_ffiles),
EXTRACT_64BITS((const uint32_t *)&sfsp->sf_afiles),
EXTRACT_32BITS(&sfsp->sf_invarsec)));
}
} else {
ND_PRINT((ndo, " tsize %d bsize %d blocks %d bfree %d bavail %d",
EXTRACT_32BITS(&sfsp->sf_tsize),
EXTRACT_32BITS(&sfsp->sf_bsize),
EXTRACT_32BITS(&sfsp->sf_blocks),
EXTRACT_32BITS(&sfsp->sf_bfree),
EXTRACT_32BITS(&sfsp->sf_bavail)));
}
return (1);
trunc:
return (0);
}
static int
parserddires(netdissect_options *ndo,
const uint32_t *dp)
{
int er;
dp = parsestatus(ndo, dp, &er);
if (dp == NULL)
return (0);
if (er)
return (1);
if (ndo->ndo_qflag)
return (1);
ND_TCHECK(dp[2]);
ND_PRINT((ndo, " offset 0x%x size %d ",
EXTRACT_32BITS(&dp[0]), EXTRACT_32BITS(&dp[1])));
if (dp[2] != 0)
ND_PRINT((ndo, " eof"));
return (1);
trunc:
return (0);
}
static const uint32_t *
parse_wcc_attr(netdissect_options *ndo,
const uint32_t *dp)
{
/* Our caller has already checked this */
ND_PRINT((ndo, " sz %" PRIu64, EXTRACT_64BITS(&dp[0])));
ND_PRINT((ndo, " mtime %u.%06u ctime %u.%06u",
EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[3]),
EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[5])));
return (dp + 6);
}
/*
* Pre operation attributes. Print only if vflag > 1.
*/
static const uint32_t *
parse_pre_op_attr(netdissect_options *ndo,
const uint32_t *dp, int verbose)
{
ND_TCHECK(dp[0]);
if (!EXTRACT_32BITS(&dp[0]))
return (dp + 1);
dp++;
ND_TCHECK2(*dp, 24);
if (verbose > 1) {
return parse_wcc_attr(ndo, dp);
} else {
/* If not verbose enough, just skip over wcc_attr */
return (dp + 6);
}
trunc:
return (NULL);
}
/*
* Post operation attributes are printed if vflag >= 1
*/
static const uint32_t *
parse_post_op_attr(netdissect_options *ndo,
const uint32_t *dp, int verbose)
{
ND_TCHECK(dp[0]);
if (!EXTRACT_32BITS(&dp[0]))
return (dp + 1);
dp++;
if (verbose) {
return parsefattr(ndo, dp, verbose, 1);
} else
return (dp + (NFSX_V3FATTR / sizeof (uint32_t)));
trunc:
return (NULL);
}
static const uint32_t *
parse_wcc_data(netdissect_options *ndo,
const uint32_t *dp, int verbose)
{
if (verbose > 1)
ND_PRINT((ndo, " PRE:"));
if (!(dp = parse_pre_op_attr(ndo, dp, verbose)))
return (0);
if (verbose)
ND_PRINT((ndo, " POST:"));
return parse_post_op_attr(ndo, dp, verbose);
}
static const uint32_t *
parsecreateopres(netdissect_options *ndo,
const uint32_t *dp, int verbose)
{
int er;
if (!(dp = parsestatus(ndo, dp, &er)))
return (0);
if (er)
dp = parse_wcc_data(ndo, dp, verbose);
else {
ND_TCHECK(dp[0]);
if (!EXTRACT_32BITS(&dp[0]))
return (dp + 1);
dp++;
if (!(dp = parsefh(ndo, dp, 1)))
return (0);
if (verbose) {
if (!(dp = parse_post_op_attr(ndo, dp, verbose)))
return (0);
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " dir attr:"));
dp = parse_wcc_data(ndo, dp, verbose);
}
}
}
return (dp);
trunc:
return (NULL);
}
static int
parsewccres(netdissect_options *ndo,
const uint32_t *dp, int verbose)
{
int er;
if (!(dp = parsestatus(ndo, dp, &er)))
return (0);
return parse_wcc_data(ndo, dp, verbose) != NULL;
}
static const uint32_t *
parsev3rddirres(netdissect_options *ndo,
const uint32_t *dp, int verbose)
{
int er;
if (!(dp = parsestatus(ndo, dp, &er)))
return (0);
if (ndo->ndo_vflag)
ND_PRINT((ndo, " POST:"));
if (!(dp = parse_post_op_attr(ndo, dp, verbose)))
return (0);
if (er)
return dp;
if (ndo->ndo_vflag) {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " verf %08x%08x", dp[0], dp[1]));
dp += 2;
}
return dp;
trunc:
return (NULL);
}
static int
parsefsinfo(netdissect_options *ndo,
const uint32_t *dp)
{
const struct nfsv3_fsinfo *sfp;
int er;
if (!(dp = parsestatus(ndo, dp, &er)))
return (0);
if (ndo->ndo_vflag)
ND_PRINT((ndo, " POST:"));
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
return (0);
if (er)
return (1);
sfp = (const struct nfsv3_fsinfo *)dp;
ND_TCHECK(*sfp);
ND_PRINT((ndo, " rtmax %u rtpref %u wtmax %u wtpref %u dtpref %u",
EXTRACT_32BITS(&sfp->fs_rtmax),
EXTRACT_32BITS(&sfp->fs_rtpref),
EXTRACT_32BITS(&sfp->fs_wtmax),
EXTRACT_32BITS(&sfp->fs_wtpref),
EXTRACT_32BITS(&sfp->fs_dtpref)));
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " rtmult %u wtmult %u maxfsz %" PRIu64,
EXTRACT_32BITS(&sfp->fs_rtmult),
EXTRACT_32BITS(&sfp->fs_wtmult),
EXTRACT_64BITS((const uint32_t *)&sfp->fs_maxfilesize)));
ND_PRINT((ndo, " delta %u.%06u ",
EXTRACT_32BITS(&sfp->fs_timedelta.nfsv3_sec),
EXTRACT_32BITS(&sfp->fs_timedelta.nfsv3_nsec)));
}
return (1);
trunc:
return (0);
}
static int
parsepathconf(netdissect_options *ndo,
const uint32_t *dp)
{
int er;
const struct nfsv3_pathconf *spp;
if (!(dp = parsestatus(ndo, dp, &er)))
return (0);
if (ndo->ndo_vflag)
ND_PRINT((ndo, " POST:"));
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
return (0);
if (er)
return (1);
spp = (const struct nfsv3_pathconf *)dp;
ND_TCHECK(*spp);
ND_PRINT((ndo, " linkmax %u namemax %u %s %s %s %s",
EXTRACT_32BITS(&spp->pc_linkmax),
EXTRACT_32BITS(&spp->pc_namemax),
EXTRACT_32BITS(&spp->pc_notrunc) ? "notrunc" : "",
EXTRACT_32BITS(&spp->pc_chownrestricted) ? "chownres" : "",
EXTRACT_32BITS(&spp->pc_caseinsensitive) ? "igncase" : "",
EXTRACT_32BITS(&spp->pc_casepreserving) ? "keepcase" : ""));
return (1);
trunc:
return (0);
}
static void
interp_reply(netdissect_options *ndo,
const struct sunrpc_msg *rp, uint32_t proc, uint32_t vers, int length)
{
register const uint32_t *dp;
register int v3;
int er;
v3 = (vers == NFS_VER3);
if (!v3 && proc < NFS_NPROCS)
proc = nfsv3_procid[proc];
ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc)));
switch (proc) {
case NFSPROC_GETATTR:
dp = parserep(ndo, rp, length);
if (dp != NULL && parseattrstat(ndo, dp, !ndo->ndo_qflag, v3) != 0)
return;
break;
case NFSPROC_SETATTR:
if (!(dp = parserep(ndo, rp, length)))
return;
if (v3) {
if (parsewccres(ndo, dp, ndo->ndo_vflag))
return;
} else {
if (parseattrstat(ndo, dp, !ndo->ndo_qflag, 0) != 0)
return;
}
break;
case NFSPROC_LOOKUP:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (er) {
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " post dattr:"));
dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag);
}
} else {
if (!(dp = parsefh(ndo, dp, v3)))
break;
if ((dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)) &&
ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " post dattr:"));
dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag);
}
}
if (dp)
return;
} else {
if (parsediropres(ndo, dp) != 0)
return;
}
break;
case NFSPROC_ACCESS:
if (!(dp = parserep(ndo, rp, length)))
break;
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (ndo->ndo_vflag)
ND_PRINT((ndo, " attr:"));
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
break;
if (!er) {
ND_TCHECK(dp[0]);
ND_PRINT((ndo, " c %04x", EXTRACT_32BITS(&dp[0])));
}
return;
case NFSPROC_READLINK:
dp = parserep(ndo, rp, length);
if (dp != NULL && parselinkres(ndo, dp, v3) != 0)
return;
break;
case NFSPROC_READ:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
break;
if (er)
return;
if (ndo->ndo_vflag) {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0])));
if (EXTRACT_32BITS(&dp[1]))
ND_PRINT((ndo, " EOF"));
}
return;
} else {
if (parseattrstat(ndo, dp, ndo->ndo_vflag, 0) != 0)
return;
}
break;
case NFSPROC_WRITE:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))
break;
if (er)
return;
if (ndo->ndo_vflag) {
ND_TCHECK(dp[0]);
ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0])));
if (ndo->ndo_vflag > 1) {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " <%s>",
tok2str(nfsv3_writemodes,
NULL, EXTRACT_32BITS(&dp[1]))));
}
return;
}
} else {
if (parseattrstat(ndo, dp, ndo->ndo_vflag, v3) != 0)
return;
}
break;
case NFSPROC_CREATE:
case NFSPROC_MKDIR:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL)
return;
} else {
if (parsediropres(ndo, dp) != 0)
return;
}
break;
case NFSPROC_SYMLINK:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL)
return;
} else {
if (parsestatus(ndo, dp, &er) != NULL)
return;
}
break;
case NFSPROC_MKNOD:
if (!(dp = parserep(ndo, rp, length)))
break;
if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL)
return;
break;
case NFSPROC_REMOVE:
case NFSPROC_RMDIR:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (parsewccres(ndo, dp, ndo->ndo_vflag))
return;
} else {
if (parsestatus(ndo, dp, &er) != NULL)
return;
}
break;
case NFSPROC_RENAME:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " from:"));
if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))
break;
ND_PRINT((ndo, " to:"));
if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))
break;
}
return;
} else {
if (parsestatus(ndo, dp, &er) != NULL)
return;
}
break;
case NFSPROC_LINK:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " file POST:"));
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
break;
ND_PRINT((ndo, " dir:"));
if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))
break;
return;
}
} else {
if (parsestatus(ndo, dp, &er) != NULL)
return;
}
break;
case NFSPROC_READDIR:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (parsev3rddirres(ndo, dp, ndo->ndo_vflag))
return;
} else {
if (parserddires(ndo, dp) != 0)
return;
}
break;
case NFSPROC_READDIRPLUS:
if (!(dp = parserep(ndo, rp, length)))
break;
if (parsev3rddirres(ndo, dp, ndo->ndo_vflag))
return;
break;
case NFSPROC_FSSTAT:
dp = parserep(ndo, rp, length);
if (dp != NULL && parsestatfs(ndo, dp, v3) != 0)
return;
break;
case NFSPROC_FSINFO:
dp = parserep(ndo, rp, length);
if (dp != NULL && parsefsinfo(ndo, dp) != 0)
return;
break;
case NFSPROC_PATHCONF:
dp = parserep(ndo, rp, length);
if (dp != NULL && parsepathconf(ndo, dp) != 0)
return;
break;
case NFSPROC_COMMIT:
dp = parserep(ndo, rp, length);
if (dp != NULL && parsewccres(ndo, dp, ndo->ndo_vflag) != 0)
return;
break;
default:
return;
}
trunc:
if (!nfserr)
ND_PRINT((ndo, "%s", tstr));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2645_0 |
crossvul-cpp_data_bad_3339_0 | /*
* Driver for the NXP SAA7164 PCIe bridge
*
* Copyright (c) 2010-2015 Steven Toth <stoth@kernellabs.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*/
#include "saa7164.h"
/* The message bus to/from the firmware is a ring buffer in PCI address
* space. Establish the defaults.
*/
int saa7164_bus_setup(struct saa7164_dev *dev)
{
struct tmComResBusInfo *b = &dev->bus;
mutex_init(&b->lock);
b->Type = TYPE_BUS_PCIe;
b->m_wMaxReqSize = SAA_DEVICE_MAXREQUESTSIZE;
b->m_pdwSetRing = (u8 __iomem *)(dev->bmmio +
((u32)dev->busdesc.CommandRing));
b->m_dwSizeSetRing = SAA_DEVICE_BUFFERBLOCKSIZE;
b->m_pdwGetRing = (u8 __iomem *)(dev->bmmio +
((u32)dev->busdesc.ResponseRing));
b->m_dwSizeGetRing = SAA_DEVICE_BUFFERBLOCKSIZE;
b->m_dwSetWritePos = ((u32)dev->intfdesc.BARLocation) +
(2 * sizeof(u64));
b->m_dwSetReadPos = b->m_dwSetWritePos + (1 * sizeof(u32));
b->m_dwGetWritePos = b->m_dwSetWritePos + (2 * sizeof(u32));
b->m_dwGetReadPos = b->m_dwSetWritePos + (3 * sizeof(u32));
return 0;
}
void saa7164_bus_dump(struct saa7164_dev *dev)
{
struct tmComResBusInfo *b = &dev->bus;
dprintk(DBGLVL_BUS, "Dumping the bus structure:\n");
dprintk(DBGLVL_BUS, " .type = %d\n", b->Type);
dprintk(DBGLVL_BUS, " .dev->bmmio = 0x%p\n", dev->bmmio);
dprintk(DBGLVL_BUS, " .m_wMaxReqSize = 0x%x\n", b->m_wMaxReqSize);
dprintk(DBGLVL_BUS, " .m_pdwSetRing = 0x%p\n", b->m_pdwSetRing);
dprintk(DBGLVL_BUS, " .m_dwSizeSetRing = 0x%x\n", b->m_dwSizeSetRing);
dprintk(DBGLVL_BUS, " .m_pdwGetRing = 0x%p\n", b->m_pdwGetRing);
dprintk(DBGLVL_BUS, " .m_dwSizeGetRing = 0x%x\n", b->m_dwSizeGetRing);
dprintk(DBGLVL_BUS, " .m_dwSetReadPos = 0x%x (0x%08x)\n",
b->m_dwSetReadPos, saa7164_readl(b->m_dwSetReadPos));
dprintk(DBGLVL_BUS, " .m_dwSetWritePos = 0x%x (0x%08x)\n",
b->m_dwSetWritePos, saa7164_readl(b->m_dwSetWritePos));
dprintk(DBGLVL_BUS, " .m_dwGetReadPos = 0x%x (0x%08x)\n",
b->m_dwGetReadPos, saa7164_readl(b->m_dwGetReadPos));
dprintk(DBGLVL_BUS, " .m_dwGetWritePos = 0x%x (0x%08x)\n",
b->m_dwGetWritePos, saa7164_readl(b->m_dwGetWritePos));
}
/* Intensionally throw a BUG() if the state of the message bus looks corrupt */
static void saa7164_bus_verify(struct saa7164_dev *dev)
{
struct tmComResBusInfo *b = &dev->bus;
int bug = 0;
if (saa7164_readl(b->m_dwSetReadPos) > b->m_dwSizeSetRing)
bug++;
if (saa7164_readl(b->m_dwSetWritePos) > b->m_dwSizeSetRing)
bug++;
if (saa7164_readl(b->m_dwGetReadPos) > b->m_dwSizeGetRing)
bug++;
if (saa7164_readl(b->m_dwGetWritePos) > b->m_dwSizeGetRing)
bug++;
if (bug) {
saa_debug = 0xffff; /* Ensure we get the bus dump */
saa7164_bus_dump(dev);
saa_debug = 1024; /* Ensure we get the bus dump */
BUG();
}
}
static void saa7164_bus_dumpmsg(struct saa7164_dev *dev, struct tmComResInfo *m,
void *buf)
{
dprintk(DBGLVL_BUS, "Dumping msg structure:\n");
dprintk(DBGLVL_BUS, " .id = %d\n", m->id);
dprintk(DBGLVL_BUS, " .flags = 0x%x\n", m->flags);
dprintk(DBGLVL_BUS, " .size = 0x%x\n", m->size);
dprintk(DBGLVL_BUS, " .command = 0x%x\n", m->command);
dprintk(DBGLVL_BUS, " .controlselector = 0x%x\n", m->controlselector);
dprintk(DBGLVL_BUS, " .seqno = %d\n", m->seqno);
if (buf)
dprintk(DBGLVL_BUS, " .buffer (ignored)\n");
}
/*
* Places a command or a response on the bus. The implementation does not
* know if it is a command or a response it just places the data on the
* bus depending on the bus information given in the struct tmComResBusInfo
* structure. If the command or response does not fit into the bus ring
* buffer it will be refused.
*
* Return Value:
* SAA_OK The function executed successfully.
* < 0 One or more members are not initialized.
*/
int saa7164_bus_set(struct saa7164_dev *dev, struct tmComResInfo* msg,
void *buf)
{
struct tmComResBusInfo *bus = &dev->bus;
u32 bytes_to_write, free_write_space, timeout, curr_srp, curr_swp;
u32 new_swp, space_rem;
int ret = SAA_ERR_BAD_PARAMETER;
u16 size;
if (!msg) {
printk(KERN_ERR "%s() !msg\n", __func__);
return SAA_ERR_BAD_PARAMETER;
}
dprintk(DBGLVL_BUS, "%s()\n", __func__);
saa7164_bus_verify(dev);
if (msg->size > dev->bus.m_wMaxReqSize) {
printk(KERN_ERR "%s() Exceeded dev->bus.m_wMaxReqSize\n",
__func__);
return SAA_ERR_BAD_PARAMETER;
}
if ((msg->size > 0) && (buf == NULL)) {
printk(KERN_ERR "%s() Missing message buffer\n", __func__);
return SAA_ERR_BAD_PARAMETER;
}
/* Lock the bus from any other access */
mutex_lock(&bus->lock);
bytes_to_write = sizeof(*msg) + msg->size;
free_write_space = 0;
timeout = SAA_BUS_TIMEOUT;
curr_srp = saa7164_readl(bus->m_dwSetReadPos);
curr_swp = saa7164_readl(bus->m_dwSetWritePos);
/* Deal with ring wrapping issues */
if (curr_srp > curr_swp)
/* Deal with the wrapped ring */
free_write_space = curr_srp - curr_swp;
else
/* The ring has not wrapped yet */
free_write_space = (curr_srp + bus->m_dwSizeSetRing) - curr_swp;
dprintk(DBGLVL_BUS, "%s() bytes_to_write = %d\n", __func__,
bytes_to_write);
dprintk(DBGLVL_BUS, "%s() free_write_space = %d\n", __func__,
free_write_space);
dprintk(DBGLVL_BUS, "%s() curr_srp = %x\n", __func__, curr_srp);
dprintk(DBGLVL_BUS, "%s() curr_swp = %x\n", __func__, curr_swp);
/* Process the msg and write the content onto the bus */
while (bytes_to_write >= free_write_space) {
if (timeout-- == 0) {
printk(KERN_ERR "%s() bus timeout\n", __func__);
ret = SAA_ERR_NO_RESOURCES;
goto out;
}
/* TODO: Review this delay, efficient? */
/* Wait, allowing the hardware fetch time */
mdelay(1);
/* Check the space usage again */
curr_srp = saa7164_readl(bus->m_dwSetReadPos);
/* Deal with ring wrapping issues */
if (curr_srp > curr_swp)
/* Deal with the wrapped ring */
free_write_space = curr_srp - curr_swp;
else
/* Read didn't wrap around the buffer */
free_write_space = (curr_srp + bus->m_dwSizeSetRing) -
curr_swp;
}
/* Calculate the new write position */
new_swp = curr_swp + bytes_to_write;
dprintk(DBGLVL_BUS, "%s() new_swp = %x\n", __func__, new_swp);
dprintk(DBGLVL_BUS, "%s() bus->m_dwSizeSetRing = %x\n", __func__,
bus->m_dwSizeSetRing);
/*
* Make a copy of msg->size before it is converted to le16 since it is
* used in the code below.
*/
size = msg->size;
/* Convert to le16/le32 */
msg->size = (__force u16)cpu_to_le16(msg->size);
msg->command = (__force u32)cpu_to_le32(msg->command);
msg->controlselector = (__force u16)cpu_to_le16(msg->controlselector);
/* Mental Note: line 462 tmmhComResBusPCIe.cpp */
/* Check if we're going to wrap again */
if (new_swp > bus->m_dwSizeSetRing) {
/* Ring wraps */
new_swp -= bus->m_dwSizeSetRing;
space_rem = bus->m_dwSizeSetRing - curr_swp;
dprintk(DBGLVL_BUS, "%s() space_rem = %x\n", __func__,
space_rem);
dprintk(DBGLVL_BUS, "%s() sizeof(*msg) = %d\n", __func__,
(u32)sizeof(*msg));
if (space_rem < sizeof(*msg)) {
dprintk(DBGLVL_BUS, "%s() tr4\n", __func__);
/* Split the msg into pieces as the ring wraps */
memcpy_toio(bus->m_pdwSetRing + curr_swp, msg, space_rem);
memcpy_toio(bus->m_pdwSetRing, (u8 *)msg + space_rem,
sizeof(*msg) - space_rem);
memcpy_toio(bus->m_pdwSetRing + sizeof(*msg) - space_rem,
buf, size);
} else if (space_rem == sizeof(*msg)) {
dprintk(DBGLVL_BUS, "%s() tr5\n", __func__);
/* Additional data at the beginning of the ring */
memcpy_toio(bus->m_pdwSetRing + curr_swp, msg, sizeof(*msg));
memcpy_toio(bus->m_pdwSetRing, buf, size);
} else {
/* Additional data wraps around the ring */
memcpy_toio(bus->m_pdwSetRing + curr_swp, msg, sizeof(*msg));
if (size > 0) {
memcpy_toio(bus->m_pdwSetRing + curr_swp +
sizeof(*msg), buf, space_rem -
sizeof(*msg));
memcpy_toio(bus->m_pdwSetRing, (u8 *)buf +
space_rem - sizeof(*msg),
bytes_to_write - space_rem);
}
}
} /* (new_swp > bus->m_dwSizeSetRing) */
else {
dprintk(DBGLVL_BUS, "%s() tr6\n", __func__);
/* The ring buffer doesn't wrap, two simple copies */
memcpy_toio(bus->m_pdwSetRing + curr_swp, msg, sizeof(*msg));
memcpy_toio(bus->m_pdwSetRing + curr_swp + sizeof(*msg), buf,
size);
}
dprintk(DBGLVL_BUS, "%s() new_swp = %x\n", __func__, new_swp);
/* Update the bus write position */
saa7164_writel(bus->m_dwSetWritePos, new_swp);
/* Convert back to cpu after writing the msg to the ringbuffer. */
msg->size = le16_to_cpu((__force __le16)msg->size);
msg->command = le32_to_cpu((__force __le32)msg->command);
msg->controlselector = le16_to_cpu((__force __le16)msg->controlselector);
ret = SAA_OK;
out:
saa7164_bus_dump(dev);
mutex_unlock(&bus->lock);
saa7164_bus_verify(dev);
return ret;
}
/*
* Receive a command or a response from the bus. The implementation does not
* know if it is a command or a response it simply dequeues the data,
* depending on the bus information given in the struct tmComResBusInfo
* structure.
*
* Return Value:
* 0 The function executed successfully.
* < 0 One or more members are not initialized.
*/
int saa7164_bus_get(struct saa7164_dev *dev, struct tmComResInfo* msg,
void *buf, int peekonly)
{
struct tmComResBusInfo *bus = &dev->bus;
u32 bytes_to_read, write_distance, curr_grp, curr_gwp,
new_grp, buf_size, space_rem;
struct tmComResInfo msg_tmp;
int ret = SAA_ERR_BAD_PARAMETER;
saa7164_bus_verify(dev);
if (msg == NULL)
return ret;
if (msg->size > dev->bus.m_wMaxReqSize) {
printk(KERN_ERR "%s() Exceeded dev->bus.m_wMaxReqSize\n",
__func__);
return ret;
}
if ((peekonly == 0) && (msg->size > 0) && (buf == NULL)) {
printk(KERN_ERR
"%s() Missing msg buf, size should be %d bytes\n",
__func__, msg->size);
return ret;
}
mutex_lock(&bus->lock);
/* Peek the bus to see if a msg exists, if it's not what we're expecting
* then return cleanly else read the message from the bus.
*/
curr_gwp = saa7164_readl(bus->m_dwGetWritePos);
curr_grp = saa7164_readl(bus->m_dwGetReadPos);
if (curr_gwp == curr_grp) {
ret = SAA_ERR_EMPTY;
goto out;
}
bytes_to_read = sizeof(*msg);
/* Calculate write distance to current read position */
write_distance = 0;
if (curr_gwp >= curr_grp)
/* Write doesn't wrap around the ring */
write_distance = curr_gwp - curr_grp;
else
/* Write wraps around the ring */
write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp;
if (bytes_to_read > write_distance) {
printk(KERN_ERR "%s() No message/response found\n", __func__);
ret = SAA_ERR_INVALID_COMMAND;
goto out;
}
/* Calculate the new read position */
new_grp = curr_grp + bytes_to_read;
if (new_grp > bus->m_dwSizeGetRing) {
/* Ring wraps */
new_grp -= bus->m_dwSizeGetRing;
space_rem = bus->m_dwSizeGetRing - curr_grp;
memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, space_rem);
memcpy_fromio((u8 *)&msg_tmp + space_rem, bus->m_pdwGetRing,
bytes_to_read - space_rem);
} else {
/* No wrapping */
memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, bytes_to_read);
}
/* Convert from little endian to CPU */
msg_tmp.size = le16_to_cpu((__force __le16)msg_tmp.size);
msg_tmp.command = le32_to_cpu((__force __le32)msg_tmp.command);
msg_tmp.controlselector = le16_to_cpu((__force __le16)msg_tmp.controlselector);
/* No need to update the read positions, because this was a peek */
/* If the caller specifically want to peek, return */
if (peekonly) {
memcpy(msg, &msg_tmp, sizeof(*msg));
goto peekout;
}
/* Check if the command/response matches what is expected */
if ((msg_tmp.id != msg->id) || (msg_tmp.command != msg->command) ||
(msg_tmp.controlselector != msg->controlselector) ||
(msg_tmp.seqno != msg->seqno) || (msg_tmp.size != msg->size)) {
printk(KERN_ERR "%s() Unexpected msg miss-match\n", __func__);
saa7164_bus_dumpmsg(dev, msg, buf);
saa7164_bus_dumpmsg(dev, &msg_tmp, NULL);
ret = SAA_ERR_INVALID_COMMAND;
goto out;
}
/* Get the actual command and response from the bus */
buf_size = msg->size;
bytes_to_read = sizeof(*msg) + msg->size;
/* Calculate write distance to current read position */
write_distance = 0;
if (curr_gwp >= curr_grp)
/* Write doesn't wrap around the ring */
write_distance = curr_gwp - curr_grp;
else
/* Write wraps around the ring */
write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp;
if (bytes_to_read > write_distance) {
printk(KERN_ERR "%s() Invalid bus state, missing msg or mangled ring, faulty H/W / bad code?\n",
__func__);
ret = SAA_ERR_INVALID_COMMAND;
goto out;
}
/* Calculate the new read position */
new_grp = curr_grp + bytes_to_read;
if (new_grp > bus->m_dwSizeGetRing) {
/* Ring wraps */
new_grp -= bus->m_dwSizeGetRing;
space_rem = bus->m_dwSizeGetRing - curr_grp;
if (space_rem < sizeof(*msg)) {
/* msg wraps around the ring */
memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, space_rem);
memcpy_fromio((u8 *)msg + space_rem, bus->m_pdwGetRing,
sizeof(*msg) - space_rem);
if (buf)
memcpy_fromio(buf, bus->m_pdwGetRing + sizeof(*msg) -
space_rem, buf_size);
} else if (space_rem == sizeof(*msg)) {
memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));
if (buf)
memcpy_fromio(buf, bus->m_pdwGetRing, buf_size);
} else {
/* Additional data wraps around the ring */
memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));
if (buf) {
memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp +
sizeof(*msg), space_rem - sizeof(*msg));
memcpy_fromio(buf + space_rem - sizeof(*msg),
bus->m_pdwGetRing, bytes_to_read -
space_rem);
}
}
} else {
/* No wrapping */
memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));
if (buf)
memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg),
buf_size);
}
/* Convert from little endian to CPU */
msg->size = le16_to_cpu((__force __le16)msg->size);
msg->command = le32_to_cpu((__force __le32)msg->command);
msg->controlselector = le16_to_cpu((__force __le16)msg->controlselector);
/* Update the read positions, adjusting the ring */
saa7164_writel(bus->m_dwGetReadPos, new_grp);
peekout:
ret = SAA_OK;
out:
mutex_unlock(&bus->lock);
saa7164_bus_verify(dev);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3339_0 |
crossvul-cpp_data_good_1878_0 | /*
Conexant cx24116/cx24118 - DVBS/S2 Satellite demod/tuner driver
Copyright (C) 2006-2008 Steven Toth <stoth@hauppauge.com>
Copyright (C) 2006-2007 Georg Acher
Copyright (C) 2007-2008 Darron Broad
March 2007
Fixed some bugs.
Added diseqc support.
Added corrected signal strength support.
August 2007
Sync with legacy version.
Some clean ups.
Copyright (C) 2008 Igor Liplianin
September, 9th 2008
Fixed locking on high symbol rates (>30000).
Implement MPEG initialization parameter.
January, 17th 2009
Fill set_voltage with actually control voltage code.
Correct set tone to not affect voltage.
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/firmware.h>
#include "dvb_frontend.h"
#include "cx24116.h"
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Activates frontend debugging (default:0)");
#define dprintk(args...) \
do { \
if (debug) \
printk(KERN_INFO "cx24116: " args); \
} while (0)
#define CX24116_DEFAULT_FIRMWARE "dvb-fe-cx24116.fw"
#define CX24116_SEARCH_RANGE_KHZ 5000
/* known registers */
#define CX24116_REG_COMMAND (0x00) /* command args 0x00..0x1e */
#define CX24116_REG_EXECUTE (0x1f) /* execute command */
#define CX24116_REG_MAILBOX (0x96) /* FW or multipurpose mailbox? */
#define CX24116_REG_RESET (0x20) /* reset status > 0 */
#define CX24116_REG_SIGNAL (0x9e) /* signal low */
#define CX24116_REG_SSTATUS (0x9d) /* signal high / status */
#define CX24116_REG_QUALITY8 (0xa3)
#define CX24116_REG_QSTATUS (0xbc)
#define CX24116_REG_QUALITY0 (0xd5)
#define CX24116_REG_BER0 (0xc9)
#define CX24116_REG_BER8 (0xc8)
#define CX24116_REG_BER16 (0xc7)
#define CX24116_REG_BER24 (0xc6)
#define CX24116_REG_UCB0 (0xcb)
#define CX24116_REG_UCB8 (0xca)
#define CX24116_REG_CLKDIV (0xf3)
#define CX24116_REG_RATEDIV (0xf9)
/* configured fec (not tuned) or actual FEC (tuned) 1=1/2 2=2/3 etc */
#define CX24116_REG_FECSTATUS (0x9c)
/* FECSTATUS bits */
/* mask to determine configured fec (not tuned) or actual fec (tuned) */
#define CX24116_FEC_FECMASK (0x1f)
/* Select DVB-S demodulator, else DVB-S2 */
#define CX24116_FEC_DVBS (0x20)
#define CX24116_FEC_UNKNOWN (0x40) /* Unknown/unused */
/* Pilot mode requested when tuning else always reset when tuned */
#define CX24116_FEC_PILOT (0x80)
/* arg buffer size */
#define CX24116_ARGLEN (0x1e)
/* rolloff */
#define CX24116_ROLLOFF_020 (0x00)
#define CX24116_ROLLOFF_025 (0x01)
#define CX24116_ROLLOFF_035 (0x02)
/* pilot bit */
#define CX24116_PILOT_OFF (0x00)
#define CX24116_PILOT_ON (0x40)
/* signal status */
#define CX24116_HAS_SIGNAL (0x01)
#define CX24116_HAS_CARRIER (0x02)
#define CX24116_HAS_VITERBI (0x04)
#define CX24116_HAS_SYNCLOCK (0x08)
#define CX24116_HAS_UNKNOWN1 (0x10)
#define CX24116_HAS_UNKNOWN2 (0x20)
#define CX24116_STATUS_MASK (0x0f)
#define CX24116_SIGNAL_MASK (0xc0)
#define CX24116_DISEQC_TONEOFF (0) /* toneburst never sent */
#define CX24116_DISEQC_TONECACHE (1) /* toneburst cached */
#define CX24116_DISEQC_MESGCACHE (2) /* message cached */
/* arg offset for DiSEqC */
#define CX24116_DISEQC_BURST (1)
#define CX24116_DISEQC_ARG2_2 (2) /* unknown value=2 */
#define CX24116_DISEQC_ARG3_0 (3) /* unknown value=0 */
#define CX24116_DISEQC_ARG4_0 (4) /* unknown value=0 */
#define CX24116_DISEQC_MSGLEN (5)
#define CX24116_DISEQC_MSGOFS (6)
/* DiSEqC burst */
#define CX24116_DISEQC_MINI_A (0)
#define CX24116_DISEQC_MINI_B (1)
/* DiSEqC tone burst */
static int toneburst = 1;
module_param(toneburst, int, 0644);
MODULE_PARM_DESC(toneburst, "DiSEqC toneburst 0=OFF, 1=TONE CACHE, "\
"2=MESSAGE CACHE (default:1)");
/* SNR measurements */
static int esno_snr;
module_param(esno_snr, int, 0644);
MODULE_PARM_DESC(esno_snr, "SNR return units, 0=PERCENTAGE 0-100, "\
"1=ESNO(db * 10) (default:0)");
enum cmds {
CMD_SET_VCO = 0x10,
CMD_TUNEREQUEST = 0x11,
CMD_MPEGCONFIG = 0x13,
CMD_TUNERINIT = 0x14,
CMD_BANDWIDTH = 0x15,
CMD_GETAGC = 0x19,
CMD_LNBCONFIG = 0x20,
CMD_LNBSEND = 0x21, /* Formerly CMD_SEND_DISEQC */
CMD_LNBDCLEVEL = 0x22,
CMD_SET_TONE = 0x23,
CMD_UPDFWVERS = 0x35,
CMD_TUNERSLEEP = 0x36,
CMD_AGCCONTROL = 0x3b, /* Unknown */
};
/* The Demod/Tuner can't easily provide these, we cache them */
struct cx24116_tuning {
u32 frequency;
u32 symbol_rate;
fe_spectral_inversion_t inversion;
fe_code_rate_t fec;
fe_delivery_system_t delsys;
fe_modulation_t modulation;
fe_pilot_t pilot;
fe_rolloff_t rolloff;
/* Demod values */
u8 fec_val;
u8 fec_mask;
u8 inversion_val;
u8 pilot_val;
u8 rolloff_val;
};
/* Basic commands that are sent to the firmware */
struct cx24116_cmd {
u8 len;
u8 args[CX24116_ARGLEN];
};
struct cx24116_state {
struct i2c_adapter *i2c;
const struct cx24116_config *config;
struct dvb_frontend frontend;
struct cx24116_tuning dcur;
struct cx24116_tuning dnxt;
u8 skip_fw_load;
u8 burst;
struct cx24116_cmd dsec_cmd;
};
static int cx24116_writereg(struct cx24116_state *state, int reg, int data)
{
u8 buf[] = { reg, data };
struct i2c_msg msg = { .addr = state->config->demod_address,
.flags = 0, .buf = buf, .len = 2 };
int err;
if (debug > 1)
printk("cx24116: %s: write reg 0x%02x, value 0x%02x\n",
__func__, reg, data);
err = i2c_transfer(state->i2c, &msg, 1);
if (err != 1) {
printk(KERN_ERR "%s: writereg error(err == %i, reg == 0x%02x,"
" value == 0x%02x)\n", __func__, err, reg, data);
return -EREMOTEIO;
}
return 0;
}
/* Bulk byte writes to a single I2C address, for 32k firmware load */
static int cx24116_writeregN(struct cx24116_state *state, int reg,
const u8 *data, u16 len)
{
int ret = -EREMOTEIO;
struct i2c_msg msg;
u8 *buf;
buf = kmalloc(len + 1, GFP_KERNEL);
if (buf == NULL) {
printk("Unable to kmalloc\n");
ret = -ENOMEM;
goto error;
}
*(buf) = reg;
memcpy(buf + 1, data, len);
msg.addr = state->config->demod_address;
msg.flags = 0;
msg.buf = buf;
msg.len = len + 1;
if (debug > 1)
printk(KERN_INFO "cx24116: %s: write regN 0x%02x, len = %d\n",
__func__, reg, len);
ret = i2c_transfer(state->i2c, &msg, 1);
if (ret != 1) {
printk(KERN_ERR "%s: writereg error(err == %i, reg == 0x%02x\n",
__func__, ret, reg);
ret = -EREMOTEIO;
}
error:
kfree(buf);
return ret;
}
static int cx24116_readreg(struct cx24116_state *state, u8 reg)
{
int ret;
u8 b0[] = { reg };
u8 b1[] = { 0 };
struct i2c_msg msg[] = {
{ .addr = state->config->demod_address, .flags = 0,
.buf = b0, .len = 1 },
{ .addr = state->config->demod_address, .flags = I2C_M_RD,
.buf = b1, .len = 1 }
};
ret = i2c_transfer(state->i2c, msg, 2);
if (ret != 2) {
printk(KERN_ERR "%s: reg=0x%x (error=%d)\n",
__func__, reg, ret);
return ret;
}
if (debug > 1)
printk(KERN_INFO "cx24116: read reg 0x%02x, value 0x%02x\n",
reg, b1[0]);
return b1[0];
}
static int cx24116_set_inversion(struct cx24116_state *state,
fe_spectral_inversion_t inversion)
{
dprintk("%s(%d)\n", __func__, inversion);
switch (inversion) {
case INVERSION_OFF:
state->dnxt.inversion_val = 0x00;
break;
case INVERSION_ON:
state->dnxt.inversion_val = 0x04;
break;
case INVERSION_AUTO:
state->dnxt.inversion_val = 0x0C;
break;
default:
return -EINVAL;
}
state->dnxt.inversion = inversion;
return 0;
}
/*
* modfec (modulation and FEC)
* ===========================
*
* MOD FEC mask/val standard
* ---- -------- ----------- --------
* QPSK FEC_1_2 0x02 0x02+X DVB-S
* QPSK FEC_2_3 0x04 0x02+X DVB-S
* QPSK FEC_3_4 0x08 0x02+X DVB-S
* QPSK FEC_4_5 0x10 0x02+X DVB-S (?)
* QPSK FEC_5_6 0x20 0x02+X DVB-S
* QPSK FEC_6_7 0x40 0x02+X DVB-S
* QPSK FEC_7_8 0x80 0x02+X DVB-S
* QPSK FEC_8_9 0x01 0x02+X DVB-S (?) (NOT SUPPORTED?)
* QPSK AUTO 0xff 0x02+X DVB-S
*
* For DVB-S high byte probably represents FEC
* and low byte selects the modulator. The high
* byte is search range mask. Bit 5 may turn
* on DVB-S and remaining bits represent some
* kind of calibration (how/what i do not know).
*
* Eg.(2/3) szap "Zone Horror"
*
* mask/val = 0x04, 0x20
* status 1f | signal c3c0 | snr a333 | ber 00000098 | unc 0 | FE_HAS_LOCK
*
* mask/val = 0x04, 0x30
* status 1f | signal c3c0 | snr a333 | ber 00000000 | unc 0 | FE_HAS_LOCK
*
* After tuning FECSTATUS contains actual FEC
* in use numbered 1 through to 8 for 1/2 .. 2/3 etc
*
* NBC=NOT/NON BACKWARD COMPATIBLE WITH DVB-S (DVB-S2 only)
*
* NBC-QPSK FEC_1_2 0x00, 0x04 DVB-S2
* NBC-QPSK FEC_3_5 0x00, 0x05 DVB-S2
* NBC-QPSK FEC_2_3 0x00, 0x06 DVB-S2
* NBC-QPSK FEC_3_4 0x00, 0x07 DVB-S2
* NBC-QPSK FEC_4_5 0x00, 0x08 DVB-S2
* NBC-QPSK FEC_5_6 0x00, 0x09 DVB-S2
* NBC-QPSK FEC_8_9 0x00, 0x0a DVB-S2
* NBC-QPSK FEC_9_10 0x00, 0x0b DVB-S2
*
* NBC-8PSK FEC_3_5 0x00, 0x0c DVB-S2
* NBC-8PSK FEC_2_3 0x00, 0x0d DVB-S2
* NBC-8PSK FEC_3_4 0x00, 0x0e DVB-S2
* NBC-8PSK FEC_5_6 0x00, 0x0f DVB-S2
* NBC-8PSK FEC_8_9 0x00, 0x10 DVB-S2
* NBC-8PSK FEC_9_10 0x00, 0x11 DVB-S2
*
* For DVB-S2 low bytes selects both modulator
* and FEC. High byte is meaningless here. To
* set pilot, bit 6 (0x40) is set. When inspecting
* FECSTATUS bit 7 (0x80) represents the pilot
* selection whilst not tuned. When tuned, actual FEC
* in use is found in FECSTATUS as per above. Pilot
* value is reset.
*/
/* A table of modulation, fec and configuration bytes for the demod.
* Not all S2 mmodulation schemes are support and not all rates with
* a scheme are support. Especially, no auto detect when in S2 mode.
*/
static struct cx24116_modfec {
fe_delivery_system_t delivery_system;
fe_modulation_t modulation;
fe_code_rate_t fec;
u8 mask; /* In DVBS mode this is used to autodetect */
u8 val; /* Passed to the firmware to indicate mode selection */
} CX24116_MODFEC_MODES[] = {
/* QPSK. For unknown rates we set hardware to auto detect 0xfe 0x30 */
/*mod fec mask val */
{ SYS_DVBS, QPSK, FEC_NONE, 0xfe, 0x30 },
{ SYS_DVBS, QPSK, FEC_1_2, 0x02, 0x2e }, /* 00000010 00101110 */
{ SYS_DVBS, QPSK, FEC_2_3, 0x04, 0x2f }, /* 00000100 00101111 */
{ SYS_DVBS, QPSK, FEC_3_4, 0x08, 0x30 }, /* 00001000 00110000 */
{ SYS_DVBS, QPSK, FEC_4_5, 0xfe, 0x30 }, /* 000?0000 ? */
{ SYS_DVBS, QPSK, FEC_5_6, 0x20, 0x31 }, /* 00100000 00110001 */
{ SYS_DVBS, QPSK, FEC_6_7, 0xfe, 0x30 }, /* 0?000000 ? */
{ SYS_DVBS, QPSK, FEC_7_8, 0x80, 0x32 }, /* 10000000 00110010 */
{ SYS_DVBS, QPSK, FEC_8_9, 0xfe, 0x30 }, /* 0000000? ? */
{ SYS_DVBS, QPSK, FEC_AUTO, 0xfe, 0x30 },
/* NBC-QPSK */
{ SYS_DVBS2, QPSK, FEC_1_2, 0x00, 0x04 },
{ SYS_DVBS2, QPSK, FEC_3_5, 0x00, 0x05 },
{ SYS_DVBS2, QPSK, FEC_2_3, 0x00, 0x06 },
{ SYS_DVBS2, QPSK, FEC_3_4, 0x00, 0x07 },
{ SYS_DVBS2, QPSK, FEC_4_5, 0x00, 0x08 },
{ SYS_DVBS2, QPSK, FEC_5_6, 0x00, 0x09 },
{ SYS_DVBS2, QPSK, FEC_8_9, 0x00, 0x0a },
{ SYS_DVBS2, QPSK, FEC_9_10, 0x00, 0x0b },
/* 8PSK */
{ SYS_DVBS2, PSK_8, FEC_3_5, 0x00, 0x0c },
{ SYS_DVBS2, PSK_8, FEC_2_3, 0x00, 0x0d },
{ SYS_DVBS2, PSK_8, FEC_3_4, 0x00, 0x0e },
{ SYS_DVBS2, PSK_8, FEC_5_6, 0x00, 0x0f },
{ SYS_DVBS2, PSK_8, FEC_8_9, 0x00, 0x10 },
{ SYS_DVBS2, PSK_8, FEC_9_10, 0x00, 0x11 },
/*
* `val' can be found in the FECSTATUS register when tuning.
* FECSTATUS will give the actual FEC in use if tuning was successful.
*/
};
static int cx24116_lookup_fecmod(struct cx24116_state *state,
fe_delivery_system_t d, fe_modulation_t m, fe_code_rate_t f)
{
int i, ret = -EOPNOTSUPP;
dprintk("%s(0x%02x,0x%02x)\n", __func__, m, f);
for (i = 0; i < ARRAY_SIZE(CX24116_MODFEC_MODES); i++) {
if ((d == CX24116_MODFEC_MODES[i].delivery_system) &&
(m == CX24116_MODFEC_MODES[i].modulation) &&
(f == CX24116_MODFEC_MODES[i].fec)) {
ret = i;
break;
}
}
return ret;
}
static int cx24116_set_fec(struct cx24116_state *state,
fe_delivery_system_t delsys, fe_modulation_t mod, fe_code_rate_t fec)
{
int ret = 0;
dprintk("%s(0x%02x,0x%02x)\n", __func__, mod, fec);
ret = cx24116_lookup_fecmod(state, delsys, mod, fec);
if (ret < 0)
return ret;
state->dnxt.fec = fec;
state->dnxt.fec_val = CX24116_MODFEC_MODES[ret].val;
state->dnxt.fec_mask = CX24116_MODFEC_MODES[ret].mask;
dprintk("%s() mask/val = 0x%02x/0x%02x\n", __func__,
state->dnxt.fec_mask, state->dnxt.fec_val);
return 0;
}
static int cx24116_set_symbolrate(struct cx24116_state *state, u32 rate)
{
dprintk("%s(%d)\n", __func__, rate);
/* check if symbol rate is within limits */
if ((rate > state->frontend.ops.info.symbol_rate_max) ||
(rate < state->frontend.ops.info.symbol_rate_min)) {
dprintk("%s() unsupported symbol_rate = %d\n", __func__, rate);
return -EOPNOTSUPP;
}
state->dnxt.symbol_rate = rate;
dprintk("%s() symbol_rate = %d\n", __func__, rate);
return 0;
}
static int cx24116_load_firmware(struct dvb_frontend *fe,
const struct firmware *fw);
static int cx24116_firmware_ondemand(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
const struct firmware *fw;
int ret = 0;
dprintk("%s()\n", __func__);
if (cx24116_readreg(state, 0x20) > 0) {
if (state->skip_fw_load)
return 0;
/* Load firmware */
/* request the firmware, this will block until loaded */
printk(KERN_INFO "%s: Waiting for firmware upload (%s)...\n",
__func__, CX24116_DEFAULT_FIRMWARE);
ret = request_firmware(&fw, CX24116_DEFAULT_FIRMWARE,
state->i2c->dev.parent);
printk(KERN_INFO "%s: Waiting for firmware upload(2)...\n",
__func__);
if (ret) {
printk(KERN_ERR "%s: No firmware uploaded "
"(timeout or file not found?)\n", __func__);
return ret;
}
/* Make sure we don't recurse back through here
* during loading */
state->skip_fw_load = 1;
ret = cx24116_load_firmware(fe, fw);
if (ret)
printk(KERN_ERR "%s: Writing firmware to device failed\n",
__func__);
release_firmware(fw);
printk(KERN_INFO "%s: Firmware upload %s\n", __func__,
ret == 0 ? "complete" : "failed");
/* Ensure firmware is always loaded if required */
state->skip_fw_load = 0;
}
return ret;
}
/* Take a basic firmware command structure, format it
* and forward it for processing
*/
static int cx24116_cmd_execute(struct dvb_frontend *fe, struct cx24116_cmd *cmd)
{
struct cx24116_state *state = fe->demodulator_priv;
int i, ret;
dprintk("%s()\n", __func__);
/* Load the firmware if required */
ret = cx24116_firmware_ondemand(fe);
if (ret != 0) {
printk(KERN_ERR "%s(): Unable initialise the firmware\n",
__func__);
return ret;
}
/* Write the command */
for (i = 0; i < cmd->len ; i++) {
dprintk("%s: 0x%02x == 0x%02x\n", __func__, i, cmd->args[i]);
cx24116_writereg(state, i, cmd->args[i]);
}
/* Start execution and wait for cmd to terminate */
cx24116_writereg(state, CX24116_REG_EXECUTE, 0x01);
while (cx24116_readreg(state, CX24116_REG_EXECUTE)) {
msleep(10);
if (i++ > 64) {
/* Avoid looping forever if the firmware does
not respond */
printk(KERN_WARNING "%s() Firmware not responding\n",
__func__);
return -EREMOTEIO;
}
}
return 0;
}
static int cx24116_load_firmware(struct dvb_frontend *fe,
const struct firmware *fw)
{
struct cx24116_state *state = fe->demodulator_priv;
struct cx24116_cmd cmd;
int i, ret, len, max, remaining;
unsigned char vers[4];
dprintk("%s\n", __func__);
dprintk("Firmware is %zu bytes (%02x %02x .. %02x %02x)\n",
fw->size,
fw->data[0],
fw->data[1],
fw->data[fw->size-2],
fw->data[fw->size-1]);
/* Toggle 88x SRST pin to reset demod */
if (state->config->reset_device)
state->config->reset_device(fe);
/* Begin the firmware load process */
/* Prepare the demod, load the firmware, cleanup after load */
/* Init PLL */
cx24116_writereg(state, 0xE5, 0x00);
cx24116_writereg(state, 0xF1, 0x08);
cx24116_writereg(state, 0xF2, 0x13);
/* Start PLL */
cx24116_writereg(state, 0xe0, 0x03);
cx24116_writereg(state, 0xe0, 0x00);
/* Unknown */
cx24116_writereg(state, CX24116_REG_CLKDIV, 0x46);
cx24116_writereg(state, CX24116_REG_RATEDIV, 0x00);
/* Unknown */
cx24116_writereg(state, 0xF0, 0x03);
cx24116_writereg(state, 0xF4, 0x81);
cx24116_writereg(state, 0xF5, 0x00);
cx24116_writereg(state, 0xF6, 0x00);
/* Split firmware to the max I2C write len and write.
* Writes whole firmware as one write when i2c_wr_max is set to 0. */
if (state->config->i2c_wr_max)
max = state->config->i2c_wr_max;
else
max = INT_MAX; /* enough for 32k firmware */
for (remaining = fw->size; remaining > 0; remaining -= max - 1) {
len = remaining;
if (len > max - 1)
len = max - 1;
cx24116_writeregN(state, 0xF7, &fw->data[fw->size - remaining],
len);
}
cx24116_writereg(state, 0xF4, 0x10);
cx24116_writereg(state, 0xF0, 0x00);
cx24116_writereg(state, 0xF8, 0x06);
/* Firmware CMD 10: VCO config */
cmd.args[0x00] = CMD_SET_VCO;
cmd.args[0x01] = 0x05;
cmd.args[0x02] = 0xdc;
cmd.args[0x03] = 0xda;
cmd.args[0x04] = 0xae;
cmd.args[0x05] = 0xaa;
cmd.args[0x06] = 0x04;
cmd.args[0x07] = 0x9d;
cmd.args[0x08] = 0xfc;
cmd.args[0x09] = 0x06;
cmd.len = 0x0a;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
cx24116_writereg(state, CX24116_REG_SSTATUS, 0x00);
/* Firmware CMD 14: Tuner config */
cmd.args[0x00] = CMD_TUNERINIT;
cmd.args[0x01] = 0x00;
cmd.args[0x02] = 0x00;
cmd.len = 0x03;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
cx24116_writereg(state, 0xe5, 0x00);
/* Firmware CMD 13: MPEG config */
cmd.args[0x00] = CMD_MPEGCONFIG;
cmd.args[0x01] = 0x01;
cmd.args[0x02] = 0x75;
cmd.args[0x03] = 0x00;
if (state->config->mpg_clk_pos_pol)
cmd.args[0x04] = state->config->mpg_clk_pos_pol;
else
cmd.args[0x04] = 0x02;
cmd.args[0x05] = 0x00;
cmd.len = 0x06;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
/* Firmware CMD 35: Get firmware version */
cmd.args[0x00] = CMD_UPDFWVERS;
cmd.len = 0x02;
for (i = 0; i < 4; i++) {
cmd.args[0x01] = i;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
vers[i] = cx24116_readreg(state, CX24116_REG_MAILBOX);
}
printk(KERN_INFO "%s: FW version %i.%i.%i.%i\n", __func__,
vers[0], vers[1], vers[2], vers[3]);
return 0;
}
static int cx24116_read_status(struct dvb_frontend *fe, fe_status_t *status)
{
struct cx24116_state *state = fe->demodulator_priv;
int lock = cx24116_readreg(state, CX24116_REG_SSTATUS) &
CX24116_STATUS_MASK;
dprintk("%s: status = 0x%02x\n", __func__, lock);
*status = 0;
if (lock & CX24116_HAS_SIGNAL)
*status |= FE_HAS_SIGNAL;
if (lock & CX24116_HAS_CARRIER)
*status |= FE_HAS_CARRIER;
if (lock & CX24116_HAS_VITERBI)
*status |= FE_HAS_VITERBI;
if (lock & CX24116_HAS_SYNCLOCK)
*status |= FE_HAS_SYNC | FE_HAS_LOCK;
return 0;
}
static int cx24116_read_ber(struct dvb_frontend *fe, u32 *ber)
{
struct cx24116_state *state = fe->demodulator_priv;
dprintk("%s()\n", __func__);
*ber = (cx24116_readreg(state, CX24116_REG_BER24) << 24) |
(cx24116_readreg(state, CX24116_REG_BER16) << 16) |
(cx24116_readreg(state, CX24116_REG_BER8) << 8) |
cx24116_readreg(state, CX24116_REG_BER0);
return 0;
}
/* TODO Determine function and scale appropriately */
static int cx24116_read_signal_strength(struct dvb_frontend *fe,
u16 *signal_strength)
{
struct cx24116_state *state = fe->demodulator_priv;
struct cx24116_cmd cmd;
int ret;
u16 sig_reading;
dprintk("%s()\n", __func__);
/* Firmware CMD 19: Get AGC */
cmd.args[0x00] = CMD_GETAGC;
cmd.len = 0x01;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
sig_reading =
(cx24116_readreg(state,
CX24116_REG_SSTATUS) & CX24116_SIGNAL_MASK) |
(cx24116_readreg(state, CX24116_REG_SIGNAL) << 6);
*signal_strength = 0 - sig_reading;
dprintk("%s: raw / cooked = 0x%04x / 0x%04x\n",
__func__, sig_reading, *signal_strength);
return 0;
}
/* SNR (0..100)% = (sig & 0xf0) * 10 + (sig & 0x0f) * 10 / 16 */
static int cx24116_read_snr_pct(struct dvb_frontend *fe, u16 *snr)
{
struct cx24116_state *state = fe->demodulator_priv;
u8 snr_reading;
static const u32 snr_tab[] = { /* 10 x Table (rounded up) */
0x00000, 0x0199A, 0x03333, 0x04ccD, 0x06667,
0x08000, 0x0999A, 0x0b333, 0x0cccD, 0x0e667,
0x10000, 0x1199A, 0x13333, 0x14ccD, 0x16667,
0x18000 };
dprintk("%s()\n", __func__);
snr_reading = cx24116_readreg(state, CX24116_REG_QUALITY0);
if (snr_reading >= 0xa0 /* 100% */)
*snr = 0xffff;
else
*snr = snr_tab[(snr_reading & 0xf0) >> 4] +
(snr_tab[(snr_reading & 0x0f)] >> 4);
dprintk("%s: raw / cooked = 0x%02x / 0x%04x\n", __func__,
snr_reading, *snr);
return 0;
}
/* The reelbox patches show the value in the registers represents
* ESNO, from 0->30db (values 0->300). We provide this value by
* default.
*/
static int cx24116_read_snr_esno(struct dvb_frontend *fe, u16 *snr)
{
struct cx24116_state *state = fe->demodulator_priv;
dprintk("%s()\n", __func__);
*snr = cx24116_readreg(state, CX24116_REG_QUALITY8) << 8 |
cx24116_readreg(state, CX24116_REG_QUALITY0);
dprintk("%s: raw 0x%04x\n", __func__, *snr);
return 0;
}
static int cx24116_read_snr(struct dvb_frontend *fe, u16 *snr)
{
if (esno_snr == 1)
return cx24116_read_snr_esno(fe, snr);
else
return cx24116_read_snr_pct(fe, snr);
}
static int cx24116_read_ucblocks(struct dvb_frontend *fe, u32 *ucblocks)
{
struct cx24116_state *state = fe->demodulator_priv;
dprintk("%s()\n", __func__);
*ucblocks = (cx24116_readreg(state, CX24116_REG_UCB8) << 8) |
cx24116_readreg(state, CX24116_REG_UCB0);
return 0;
}
/* Overwrite the current tuning params, we are about to tune */
static void cx24116_clone_params(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
state->dcur = state->dnxt;
}
/* Wait for LNB */
static int cx24116_wait_for_lnb(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
int i;
dprintk("%s() qstatus = 0x%02x\n", __func__,
cx24116_readreg(state, CX24116_REG_QSTATUS));
/* Wait for up to 300 ms */
for (i = 0; i < 30 ; i++) {
if (cx24116_readreg(state, CX24116_REG_QSTATUS) & 0x20)
return 0;
msleep(10);
}
dprintk("%s(): LNB not ready\n", __func__);
return -ETIMEDOUT; /* -EBUSY ? */
}
static int cx24116_set_voltage(struct dvb_frontend *fe,
fe_sec_voltage_t voltage)
{
struct cx24116_cmd cmd;
int ret;
dprintk("%s: %s\n", __func__,
voltage == SEC_VOLTAGE_13 ? "SEC_VOLTAGE_13" :
voltage == SEC_VOLTAGE_18 ? "SEC_VOLTAGE_18" : "??");
/* Wait for LNB ready */
ret = cx24116_wait_for_lnb(fe);
if (ret != 0)
return ret;
/* Wait for voltage/min repeat delay */
msleep(100);
cmd.args[0x00] = CMD_LNBDCLEVEL;
cmd.args[0x01] = (voltage == SEC_VOLTAGE_18 ? 0x01 : 0x00);
cmd.len = 0x02;
/* Min delay time before DiSEqC send */
msleep(15);
return cx24116_cmd_execute(fe, &cmd);
}
static int cx24116_set_tone(struct dvb_frontend *fe,
fe_sec_tone_mode_t tone)
{
struct cx24116_cmd cmd;
int ret;
dprintk("%s(%d)\n", __func__, tone);
if ((tone != SEC_TONE_ON) && (tone != SEC_TONE_OFF)) {
printk(KERN_ERR "%s: Invalid, tone=%d\n", __func__, tone);
return -EINVAL;
}
/* Wait for LNB ready */
ret = cx24116_wait_for_lnb(fe);
if (ret != 0)
return ret;
/* Min delay time after DiSEqC send */
msleep(15); /* XXX determine is FW does this, see send_diseqc/burst */
/* Now we set the tone */
cmd.args[0x00] = CMD_SET_TONE;
cmd.args[0x01] = 0x00;
cmd.args[0x02] = 0x00;
switch (tone) {
case SEC_TONE_ON:
dprintk("%s: setting tone on\n", __func__);
cmd.args[0x03] = 0x01;
break;
case SEC_TONE_OFF:
dprintk("%s: setting tone off\n", __func__);
cmd.args[0x03] = 0x00;
break;
}
cmd.len = 0x04;
/* Min delay time before DiSEqC send */
msleep(15); /* XXX determine is FW does this, see send_diseqc/burst */
return cx24116_cmd_execute(fe, &cmd);
}
/* Initialise DiSEqC */
static int cx24116_diseqc_init(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
struct cx24116_cmd cmd;
int ret;
/* Firmware CMD 20: LNB/DiSEqC config */
cmd.args[0x00] = CMD_LNBCONFIG;
cmd.args[0x01] = 0x00;
cmd.args[0x02] = 0x10;
cmd.args[0x03] = 0x00;
cmd.args[0x04] = 0x8f;
cmd.args[0x05] = 0x28;
cmd.args[0x06] = (toneburst == CX24116_DISEQC_TONEOFF) ? 0x00 : 0x01;
cmd.args[0x07] = 0x01;
cmd.len = 0x08;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
/* Prepare a DiSEqC command */
state->dsec_cmd.args[0x00] = CMD_LNBSEND;
/* DiSEqC burst */
state->dsec_cmd.args[CX24116_DISEQC_BURST] = CX24116_DISEQC_MINI_A;
/* Unknown */
state->dsec_cmd.args[CX24116_DISEQC_ARG2_2] = 0x02;
state->dsec_cmd.args[CX24116_DISEQC_ARG3_0] = 0x00;
/* Continuation flag? */
state->dsec_cmd.args[CX24116_DISEQC_ARG4_0] = 0x00;
/* DiSEqC message length */
state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = 0x00;
/* Command length */
state->dsec_cmd.len = CX24116_DISEQC_MSGOFS;
return 0;
}
/* Send DiSEqC message with derived burst (hack) || previous burst */
static int cx24116_send_diseqc_msg(struct dvb_frontend *fe,
struct dvb_diseqc_master_cmd *d)
{
struct cx24116_state *state = fe->demodulator_priv;
int i, ret;
/* Validate length */
if (d->msg_len > sizeof(d->msg))
return -EINVAL;
/* Dump DiSEqC message */
if (debug) {
printk(KERN_INFO "cx24116: %s(", __func__);
for (i = 0 ; i < d->msg_len ;) {
printk(KERN_INFO "0x%02x", d->msg[i]);
if (++i < d->msg_len)
printk(KERN_INFO ", ");
}
printk(") toneburst=%d\n", toneburst);
}
/* DiSEqC message */
for (i = 0; i < d->msg_len; i++)
state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i];
/* DiSEqC message length */
state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len;
/* Command length */
state->dsec_cmd.len = CX24116_DISEQC_MSGOFS +
state->dsec_cmd.args[CX24116_DISEQC_MSGLEN];
/* DiSEqC toneburst */
if (toneburst == CX24116_DISEQC_MESGCACHE)
/* Message is cached */
return 0;
else if (toneburst == CX24116_DISEQC_TONEOFF)
/* Message is sent without burst */
state->dsec_cmd.args[CX24116_DISEQC_BURST] = 0;
else if (toneburst == CX24116_DISEQC_TONECACHE) {
/*
* Message is sent with derived else cached burst
*
* WRITE PORT GROUP COMMAND 38
*
* 0/A/A: E0 10 38 F0..F3
* 1/B/B: E0 10 38 F4..F7
* 2/C/A: E0 10 38 F8..FB
* 3/D/B: E0 10 38 FC..FF
*
* databyte[3]= 8421:8421
* ABCD:WXYZ
* CLR :SET
*
* WX= PORT SELECT 0..3 (X=TONEBURST)
* Y = VOLTAGE (0=13V, 1=18V)
* Z = BAND (0=LOW, 1=HIGH(22K))
*/
if (d->msg_len >= 4 && d->msg[2] == 0x38)
state->dsec_cmd.args[CX24116_DISEQC_BURST] =
((d->msg[3] & 4) >> 2);
if (debug)
dprintk("%s burst=%d\n", __func__,
state->dsec_cmd.args[CX24116_DISEQC_BURST]);
}
/* Wait for LNB ready */
ret = cx24116_wait_for_lnb(fe);
if (ret != 0)
return ret;
/* Wait for voltage/min repeat delay */
msleep(100);
/* Command */
ret = cx24116_cmd_execute(fe, &state->dsec_cmd);
if (ret != 0)
return ret;
/*
* Wait for send
*
* Eutelsat spec:
* >15ms delay + (XXX determine if FW does this, see set_tone)
* 13.5ms per byte +
* >15ms delay +
* 12.5ms burst +
* >15ms delay (XXX determine if FW does this, see set_tone)
*/
msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) +
((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60));
return 0;
}
/* Send DiSEqC burst */
static int cx24116_diseqc_send_burst(struct dvb_frontend *fe,
fe_sec_mini_cmd_t burst)
{
struct cx24116_state *state = fe->demodulator_priv;
int ret;
dprintk("%s(%d) toneburst=%d\n", __func__, burst, toneburst);
/* DiSEqC burst */
if (burst == SEC_MINI_A)
state->dsec_cmd.args[CX24116_DISEQC_BURST] =
CX24116_DISEQC_MINI_A;
else if (burst == SEC_MINI_B)
state->dsec_cmd.args[CX24116_DISEQC_BURST] =
CX24116_DISEQC_MINI_B;
else
return -EINVAL;
/* DiSEqC toneburst */
if (toneburst != CX24116_DISEQC_MESGCACHE)
/* Burst is cached */
return 0;
/* Burst is to be sent with cached message */
/* Wait for LNB ready */
ret = cx24116_wait_for_lnb(fe);
if (ret != 0)
return ret;
/* Wait for voltage/min repeat delay */
msleep(100);
/* Command */
ret = cx24116_cmd_execute(fe, &state->dsec_cmd);
if (ret != 0)
return ret;
/*
* Wait for send
*
* Eutelsat spec:
* >15ms delay + (XXX determine if FW does this, see set_tone)
* 13.5ms per byte +
* >15ms delay +
* 12.5ms burst +
* >15ms delay (XXX determine if FW does this, see set_tone)
*/
msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) + 60);
return 0;
}
static void cx24116_release(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
dprintk("%s\n", __func__);
kfree(state);
}
static struct dvb_frontend_ops cx24116_ops;
struct dvb_frontend *cx24116_attach(const struct cx24116_config *config,
struct i2c_adapter *i2c)
{
struct cx24116_state *state = NULL;
int ret;
dprintk("%s\n", __func__);
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct cx24116_state), GFP_KERNEL);
if (state == NULL)
goto error1;
state->config = config;
state->i2c = i2c;
/* check if the demod is present */
ret = (cx24116_readreg(state, 0xFF) << 8) |
cx24116_readreg(state, 0xFE);
if (ret != 0x0501) {
printk(KERN_INFO "Invalid probe, probably not a CX24116 device\n");
goto error2;
}
/* create dvb_frontend */
memcpy(&state->frontend.ops, &cx24116_ops,
sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
return &state->frontend;
error2: kfree(state);
error1: return NULL;
}
EXPORT_SYMBOL(cx24116_attach);
/*
* Initialise or wake up device
*
* Power config will reset and load initial firmware if required
*/
static int cx24116_initfe(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
struct cx24116_cmd cmd;
int ret;
dprintk("%s()\n", __func__);
/* Power on */
cx24116_writereg(state, 0xe0, 0);
cx24116_writereg(state, 0xe1, 0);
cx24116_writereg(state, 0xea, 0);
/* Firmware CMD 36: Power config */
cmd.args[0x00] = CMD_TUNERSLEEP;
cmd.args[0x01] = 0;
cmd.len = 0x02;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
ret = cx24116_diseqc_init(fe);
if (ret != 0)
return ret;
/* HVR-4000 needs this */
return cx24116_set_voltage(fe, SEC_VOLTAGE_13);
}
/*
* Put device to sleep
*/
static int cx24116_sleep(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
struct cx24116_cmd cmd;
int ret;
dprintk("%s()\n", __func__);
/* Firmware CMD 36: Power config */
cmd.args[0x00] = CMD_TUNERSLEEP;
cmd.args[0x01] = 1;
cmd.len = 0x02;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
/* Power off (Shutdown clocks) */
cx24116_writereg(state, 0xea, 0xff);
cx24116_writereg(state, 0xe1, 1);
cx24116_writereg(state, 0xe0, 1);
return 0;
}
/* dvb-core told us to tune, the tv property cache will be complete,
* it's safe for is to pull values and use them for tuning purposes.
*/
static int cx24116_set_frontend(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
struct cx24116_cmd cmd;
fe_status_t tunerstat;
int i, status, ret, retune = 1;
dprintk("%s()\n", __func__);
switch (c->delivery_system) {
case SYS_DVBS:
dprintk("%s: DVB-S delivery system selected\n", __func__);
/* Only QPSK is supported for DVB-S */
if (c->modulation != QPSK) {
dprintk("%s: unsupported modulation selected (%d)\n",
__func__, c->modulation);
return -EOPNOTSUPP;
}
/* Pilot doesn't exist in DVB-S, turn bit off */
state->dnxt.pilot_val = CX24116_PILOT_OFF;
/* DVB-S only supports 0.35 */
if (c->rolloff != ROLLOFF_35) {
dprintk("%s: unsupported rolloff selected (%d)\n",
__func__, c->rolloff);
return -EOPNOTSUPP;
}
state->dnxt.rolloff_val = CX24116_ROLLOFF_035;
break;
case SYS_DVBS2:
dprintk("%s: DVB-S2 delivery system selected\n", __func__);
/*
* NBC 8PSK/QPSK with DVB-S is supported for DVB-S2,
* but not hardware auto detection
*/
if (c->modulation != PSK_8 && c->modulation != QPSK) {
dprintk("%s: unsupported modulation selected (%d)\n",
__func__, c->modulation);
return -EOPNOTSUPP;
}
switch (c->pilot) {
case PILOT_AUTO: /* Not supported but emulated */
state->dnxt.pilot_val = (c->modulation == QPSK)
? CX24116_PILOT_OFF : CX24116_PILOT_ON;
retune++;
break;
case PILOT_OFF:
state->dnxt.pilot_val = CX24116_PILOT_OFF;
break;
case PILOT_ON:
state->dnxt.pilot_val = CX24116_PILOT_ON;
break;
default:
dprintk("%s: unsupported pilot mode selected (%d)\n",
__func__, c->pilot);
return -EOPNOTSUPP;
}
switch (c->rolloff) {
case ROLLOFF_20:
state->dnxt.rolloff_val = CX24116_ROLLOFF_020;
break;
case ROLLOFF_25:
state->dnxt.rolloff_val = CX24116_ROLLOFF_025;
break;
case ROLLOFF_35:
state->dnxt.rolloff_val = CX24116_ROLLOFF_035;
break;
case ROLLOFF_AUTO: /* Rolloff must be explicit */
default:
dprintk("%s: unsupported rolloff selected (%d)\n",
__func__, c->rolloff);
return -EOPNOTSUPP;
}
break;
default:
dprintk("%s: unsupported delivery system selected (%d)\n",
__func__, c->delivery_system);
return -EOPNOTSUPP;
}
state->dnxt.delsys = c->delivery_system;
state->dnxt.modulation = c->modulation;
state->dnxt.frequency = c->frequency;
state->dnxt.pilot = c->pilot;
state->dnxt.rolloff = c->rolloff;
ret = cx24116_set_inversion(state, c->inversion);
if (ret != 0)
return ret;
/* FEC_NONE/AUTO for DVB-S2 is not supported and detected here */
ret = cx24116_set_fec(state, c->delivery_system, c->modulation, c->fec_inner);
if (ret != 0)
return ret;
ret = cx24116_set_symbolrate(state, c->symbol_rate);
if (ret != 0)
return ret;
/* discard the 'current' tuning parameters and prepare to tune */
cx24116_clone_params(fe);
dprintk("%s: delsys = %d\n", __func__, state->dcur.delsys);
dprintk("%s: modulation = %d\n", __func__, state->dcur.modulation);
dprintk("%s: frequency = %d\n", __func__, state->dcur.frequency);
dprintk("%s: pilot = %d (val = 0x%02x)\n", __func__,
state->dcur.pilot, state->dcur.pilot_val);
dprintk("%s: retune = %d\n", __func__, retune);
dprintk("%s: rolloff = %d (val = 0x%02x)\n", __func__,
state->dcur.rolloff, state->dcur.rolloff_val);
dprintk("%s: symbol_rate = %d\n", __func__, state->dcur.symbol_rate);
dprintk("%s: FEC = %d (mask/val = 0x%02x/0x%02x)\n", __func__,
state->dcur.fec, state->dcur.fec_mask, state->dcur.fec_val);
dprintk("%s: Inversion = %d (val = 0x%02x)\n", __func__,
state->dcur.inversion, state->dcur.inversion_val);
/* This is also done in advise/acquire on HVR4000 but not on LITE */
if (state->config->set_ts_params)
state->config->set_ts_params(fe, 0);
/* Set/Reset B/W */
cmd.args[0x00] = CMD_BANDWIDTH;
cmd.args[0x01] = 0x01;
cmd.len = 0x02;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
/* Prepare a tune request */
cmd.args[0x00] = CMD_TUNEREQUEST;
/* Frequency */
cmd.args[0x01] = (state->dcur.frequency & 0xff0000) >> 16;
cmd.args[0x02] = (state->dcur.frequency & 0x00ff00) >> 8;
cmd.args[0x03] = (state->dcur.frequency & 0x0000ff);
/* Symbol Rate */
cmd.args[0x04] = ((state->dcur.symbol_rate / 1000) & 0xff00) >> 8;
cmd.args[0x05] = ((state->dcur.symbol_rate / 1000) & 0x00ff);
/* Automatic Inversion */
cmd.args[0x06] = state->dcur.inversion_val;
/* Modulation / FEC / Pilot */
cmd.args[0x07] = state->dcur.fec_val | state->dcur.pilot_val;
cmd.args[0x08] = CX24116_SEARCH_RANGE_KHZ >> 8;
cmd.args[0x09] = CX24116_SEARCH_RANGE_KHZ & 0xff;
cmd.args[0x0a] = 0x00;
cmd.args[0x0b] = 0x00;
cmd.args[0x0c] = state->dcur.rolloff_val;
cmd.args[0x0d] = state->dcur.fec_mask;
if (state->dcur.symbol_rate > 30000000) {
cmd.args[0x0e] = 0x04;
cmd.args[0x0f] = 0x00;
cmd.args[0x10] = 0x01;
cmd.args[0x11] = 0x77;
cmd.args[0x12] = 0x36;
cx24116_writereg(state, CX24116_REG_CLKDIV, 0x44);
cx24116_writereg(state, CX24116_REG_RATEDIV, 0x01);
} else {
cmd.args[0x0e] = 0x06;
cmd.args[0x0f] = 0x00;
cmd.args[0x10] = 0x00;
cmd.args[0x11] = 0xFA;
cmd.args[0x12] = 0x24;
cx24116_writereg(state, CX24116_REG_CLKDIV, 0x46);
cx24116_writereg(state, CX24116_REG_RATEDIV, 0x00);
}
cmd.len = 0x13;
/* We need to support pilot and non-pilot tuning in the
* driver automatically. This is a workaround for because
* the demod does not support autodetect.
*/
do {
/* Reset status register */
status = cx24116_readreg(state, CX24116_REG_SSTATUS)
& CX24116_SIGNAL_MASK;
cx24116_writereg(state, CX24116_REG_SSTATUS, status);
/* Tune */
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
break;
/*
* Wait for up to 500 ms before retrying
*
* If we are able to tune then generally it occurs within 100ms.
* If it takes longer, try a different toneburst setting.
*/
for (i = 0; i < 50 ; i++) {
cx24116_read_status(fe, &tunerstat);
status = tunerstat & (FE_HAS_SIGNAL | FE_HAS_SYNC);
if (status == (FE_HAS_SIGNAL | FE_HAS_SYNC)) {
dprintk("%s: Tuned\n", __func__);
goto tuned;
}
msleep(10);
}
dprintk("%s: Not tuned\n", __func__);
/* Toggle pilot bit when in auto-pilot */
if (state->dcur.pilot == PILOT_AUTO)
cmd.args[0x07] ^= CX24116_PILOT_ON;
} while (--retune);
tuned: /* Set/Reset B/W */
cmd.args[0x00] = CMD_BANDWIDTH;
cmd.args[0x01] = 0x00;
cmd.len = 0x02;
return cx24116_cmd_execute(fe, &cmd);
}
static int cx24116_tune(struct dvb_frontend *fe, bool re_tune,
unsigned int mode_flags, unsigned int *delay, fe_status_t *status)
{
/*
* It is safe to discard "params" here, as the DVB core will sync
* fe->dtv_property_cache with fepriv->parameters_in, where the
* DVBv3 params are stored. The only practical usage for it indicate
* that re-tuning is needed, e. g. (fepriv->state & FESTATE_RETUNE) is
* true.
*/
*delay = HZ / 5;
if (re_tune) {
int ret = cx24116_set_frontend(fe);
if (ret)
return ret;
}
return cx24116_read_status(fe, status);
}
static int cx24116_get_algo(struct dvb_frontend *fe)
{
return DVBFE_ALGO_HW;
}
static struct dvb_frontend_ops cx24116_ops = {
.delsys = { SYS_DVBS, SYS_DVBS2 },
.info = {
.name = "Conexant CX24116/CX24118",
.frequency_min = 950000,
.frequency_max = 2150000,
.frequency_stepsize = 1011, /* kHz for QPSK frontends */
.frequency_tolerance = 5000,
.symbol_rate_min = 1000000,
.symbol_rate_max = 45000000,
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_4_5 | FE_CAN_FEC_5_6 | FE_CAN_FEC_6_7 |
FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
FE_CAN_2G_MODULATION |
FE_CAN_QPSK | FE_CAN_RECOVER
},
.release = cx24116_release,
.init = cx24116_initfe,
.sleep = cx24116_sleep,
.read_status = cx24116_read_status,
.read_ber = cx24116_read_ber,
.read_signal_strength = cx24116_read_signal_strength,
.read_snr = cx24116_read_snr,
.read_ucblocks = cx24116_read_ucblocks,
.set_tone = cx24116_set_tone,
.set_voltage = cx24116_set_voltage,
.diseqc_send_master_cmd = cx24116_send_diseqc_msg,
.diseqc_send_burst = cx24116_diseqc_send_burst,
.get_frontend_algo = cx24116_get_algo,
.tune = cx24116_tune,
.set_frontend = cx24116_set_frontend,
};
MODULE_DESCRIPTION("DVB Frontend module for Conexant cx24116/cx24118 hardware");
MODULE_AUTHOR("Steven Toth");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1878_0 |
crossvul-cpp_data_good_3954_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Glyph Cache
*
* 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 <winpr/stream.h>
#include <freerdp/log.h>
#include <freerdp/cache/glyph.h>
#include "glyph.h"
#define TAG FREERDP_TAG("cache.glyph")
static rdpGlyph* glyph_cache_get(rdpGlyphCache* glyph_cache, UINT32 id, UINT32 index);
static BOOL glyph_cache_put(rdpGlyphCache* glyph_cache, UINT32 id, UINT32 index, rdpGlyph* entry);
static const void* glyph_cache_fragment_get(rdpGlyphCache* glyph, UINT32 index, UINT32* count);
static BOOL glyph_cache_fragment_put(rdpGlyphCache* glyph, UINT32 index, UINT32 count,
const void* entry);
static UINT32 update_glyph_offset(const BYTE* data, size_t length, UINT32 index, INT32* x, INT32* y,
UINT32 ulCharInc, UINT32 flAccel)
{
if ((ulCharInc == 0) && (!(flAccel & SO_CHAR_INC_EQUAL_BM_BASE)))
{
UINT32 offset = data[index++];
if (offset & 0x80)
{
if (index + 1 < length)
{
offset = data[index++];
offset |= ((UINT32)data[index++]) << 8;
}
else
WLog_WARN(TAG, "[%s] glyph index out of bound %" PRIu32 " [max %" PRIuz "]", index,
length);
}
if (flAccel & SO_VERTICAL)
*y += offset;
if (flAccel & SO_HORIZONTAL)
*x += offset;
}
return index;
}
static BOOL update_process_glyph(rdpContext* context, const BYTE* data, UINT32 cacheIndex, INT32* x,
INT32* y, UINT32 cacheId, UINT32 flAccel, BOOL fOpRedundant,
const RDP_RECT* bound)
{
INT32 sx = 0, sy = 0;
INT32 dx, dy;
rdpGlyph* glyph;
rdpGlyphCache* glyph_cache;
if (!context || !data || !x || !y || !context->graphics || !context->cache ||
!context->cache->glyph)
return FALSE;
glyph_cache = context->cache->glyph;
glyph = glyph_cache_get(glyph_cache, cacheId, cacheIndex);
if (!glyph)
return FALSE;
dx = glyph->x + *x;
dy = glyph->y + *y;
if (dx < bound->x)
{
sx = bound->x - dx;
dx = bound->x;
}
if (dy < bound->y)
{
sy = bound->y - dy;
dy = bound->y;
}
if ((dx <= (bound->x + bound->width)) && (dy <= (bound->y + bound->height)))
{
INT32 dw = glyph->cx - sx;
INT32 dh = glyph->cy - sy;
if ((dw + dx) > (bound->x + bound->width))
dw = (bound->x + bound->width) - (dw + dx);
if ((dh + dy) > (bound->y + bound->height))
dh = (bound->y + bound->height) - (dh + dy);
if ((dh > 0) && (dw > 0))
{
if (!glyph->Draw(context, glyph, dx, dy, dw, dh, sx, sy, fOpRedundant))
return FALSE;
}
}
if (flAccel & SO_CHAR_INC_EQUAL_BM_BASE)
*x += glyph->cx;
return TRUE;
}
static BOOL update_process_glyph_fragments(rdpContext* context, const BYTE* data, UINT32 length,
UINT32 cacheId, UINT32 ulCharInc, UINT32 flAccel,
UINT32 bgcolor, UINT32 fgcolor, INT32 x, INT32 y,
INT32 bkX, INT32 bkY, INT32 bkWidth, INT32 bkHeight,
INT32 opX, INT32 opY, INT32 opWidth, INT32 opHeight,
BOOL fOpRedundant)
{
UINT32 n;
UINT32 id;
UINT32 size;
UINT32 index = 0;
BYTE* fragments;
rdpGraphics* graphics;
rdpGlyphCache* glyph_cache;
rdpGlyph* glyph;
RDP_RECT bound;
if (!context || !data || !context->graphics || !context->cache || !context->cache->glyph)
return FALSE;
graphics = context->graphics;
glyph_cache = context->cache->glyph;
glyph = graphics->Glyph_Prototype;
if (!glyph)
return FALSE;
/* Limit op rectangle to visible screen. */
if (opX < 0)
{
opWidth += opX;
opX = 0;
}
if (opY < 0)
{
opHeight += opY;
opY = 0;
}
if (opWidth < 0)
opWidth = 0;
if (opHeight < 0)
opHeight = 0;
/* Limit bk rectangle to visible screen. */
if (bkX < 0)
{
bkWidth += bkX;
bkX = 0;
}
if (bkY < 0)
{
bkHeight += bkY;
bkY = 0;
}
if (bkWidth < 0)
bkWidth = 0;
if (bkHeight < 0)
bkHeight = 0;
if (opX + opWidth > (INT64)context->settings->DesktopWidth)
{
/**
* Some Microsoft servers send erroneous high values close to the
* sint16 maximum in the OpRight field of the GlyphIndex, FastIndex and
* FastGlyph drawing orders, probably a result of applications trying to
* clear the text line to the very right end.
* One example where this can be seen is typing in notepad.exe within
* a RDP session to Windows XP Professional SP3.
* This workaround prevents resulting problems in the UI callbacks.
*/
opWidth = context->settings->DesktopWidth - opX;
}
if (bkX + bkWidth > (INT64)context->settings->DesktopWidth)
{
/**
* Some Microsoft servers send erroneous high values close to the
* sint16 maximum in the OpRight field of the GlyphIndex, FastIndex and
* FastGlyph drawing orders, probably a result of applications trying to
* clear the text line to the very right end.
* One example where this can be seen is typing in notepad.exe within
* a RDP session to Windows XP Professional SP3.
* This workaround prevents resulting problems in the UI callbacks.
*/
bkWidth = context->settings->DesktopWidth - bkX;
}
bound.x = bkX;
bound.y = bkY;
bound.width = bkWidth;
bound.height = bkHeight;
if (!glyph->BeginDraw(context, opX, opY, opWidth, opHeight, bgcolor, fgcolor, fOpRedundant))
return FALSE;
if (!IFCALLRESULT(TRUE, glyph->SetBounds, context, bkX, bkY, bkWidth, bkHeight))
return FALSE;
while (index < length)
{
const UINT32 op = data[index++];
switch (op)
{
case GLYPH_FRAGMENT_USE:
if (index + 1 >= length)
return FALSE;
id = data[index++];
fragments = (BYTE*)glyph_cache_fragment_get(glyph_cache, id, &size);
if (fragments == NULL)
return FALSE;
for (n = 0; n < size;)
{
const UINT32 fop = fragments[n++];
n = update_glyph_offset(fragments, size, n, &x, &y, ulCharInc, flAccel);
if (!update_process_glyph(context, fragments, fop, &x, &y, cacheId, flAccel,
fOpRedundant, &bound))
return FALSE;
}
break;
case GLYPH_FRAGMENT_ADD:
if (index + 2 > length)
return FALSE;
id = data[index++];
size = data[index++];
glyph_cache_fragment_put(glyph_cache, id, size, data);
break;
default:
index = update_glyph_offset(data, length, index, &x, &y, ulCharInc, flAccel);
if (!update_process_glyph(context, data, op, &x, &y, cacheId, flAccel, fOpRedundant,
&bound))
return FALSE;
break;
}
}
return glyph->EndDraw(context, opX, opY, opWidth, opHeight, bgcolor, fgcolor);
}
static BOOL update_gdi_glyph_index(rdpContext* context, GLYPH_INDEX_ORDER* glyphIndex)
{
INT32 bkWidth = 0, bkHeight = 0, opWidth = 0, opHeight = 0;
if (!context || !glyphIndex || !context->cache)
return FALSE;
if (glyphIndex->bkRight > glyphIndex->bkLeft)
bkWidth = glyphIndex->bkRight - glyphIndex->bkLeft + 1;
if (glyphIndex->opRight > glyphIndex->opLeft)
opWidth = glyphIndex->opRight - glyphIndex->opLeft + 1;
if (glyphIndex->bkBottom > glyphIndex->bkTop)
bkHeight = glyphIndex->bkBottom - glyphIndex->bkTop + 1;
if (glyphIndex->opBottom > glyphIndex->opTop)
opHeight = glyphIndex->opBottom - glyphIndex->opTop + 1;
return update_process_glyph_fragments(
context, glyphIndex->data, glyphIndex->cbData, glyphIndex->cacheId, glyphIndex->ulCharInc,
glyphIndex->flAccel, glyphIndex->backColor, glyphIndex->foreColor, glyphIndex->x,
glyphIndex->y, glyphIndex->bkLeft, glyphIndex->bkTop, bkWidth, bkHeight, glyphIndex->opLeft,
glyphIndex->opTop, opWidth, opHeight, glyphIndex->fOpRedundant);
}
static BOOL update_gdi_fast_index(rdpContext* context, const FAST_INDEX_ORDER* fastIndex)
{
INT32 x, y;
INT32 opLeft, opTop;
INT32 opRight, opBottom;
INT32 opWidth = 0, opHeight = 0;
INT32 bkWidth = 0, bkHeight = 0;
if (!context || !fastIndex || !context->cache)
return FALSE;
opLeft = fastIndex->opLeft;
opTop = fastIndex->opTop;
opRight = fastIndex->opRight;
opBottom = fastIndex->opBottom;
x = fastIndex->x;
y = fastIndex->y;
if (opBottom == -32768)
{
BYTE flags = (BYTE)(opTop & 0x0F);
if (flags & 0x01)
opBottom = fastIndex->bkBottom;
if (flags & 0x02)
opRight = fastIndex->bkRight;
if (flags & 0x04)
opTop = fastIndex->bkTop;
if (flags & 0x08)
opLeft = fastIndex->bkLeft;
}
if (opLeft == 0)
opLeft = fastIndex->bkLeft;
if (opRight == 0)
opRight = fastIndex->bkRight;
/* Server can send a massive number (32766) which appears to be
* undocumented special behavior for "Erase all the way right".
* X11 has nondeterministic results asking for a draw that wide. */
if (opRight > (INT64)context->instance->settings->DesktopWidth)
opRight = (int)context->instance->settings->DesktopWidth;
if (x == -32768)
x = fastIndex->bkLeft;
if (y == -32768)
y = fastIndex->bkTop;
if (fastIndex->bkRight > fastIndex->bkLeft)
bkWidth = fastIndex->bkRight - fastIndex->bkLeft + 1;
if (fastIndex->bkBottom > fastIndex->bkTop)
bkHeight = fastIndex->bkBottom - fastIndex->bkTop + 1;
if (opRight > opLeft)
opWidth = opRight - opLeft + 1;
if (opBottom > opTop)
opHeight = opBottom - opTop + 1;
return update_process_glyph_fragments(
context, fastIndex->data, fastIndex->cbData, fastIndex->cacheId, fastIndex->ulCharInc,
fastIndex->flAccel, fastIndex->backColor, fastIndex->foreColor, x, y, fastIndex->bkLeft,
fastIndex->bkTop, bkWidth, bkHeight, opLeft, opTop, opWidth, opHeight, FALSE);
}
static BOOL update_gdi_fast_glyph(rdpContext* context, const FAST_GLYPH_ORDER* fastGlyph)
{
INT32 x, y;
BYTE text_data[4] = { 0 };
INT32 opLeft, opTop;
INT32 opRight, opBottom;
INT32 opWidth = 0, opHeight = 0;
INT32 bkWidth = 0, bkHeight = 0;
rdpCache* cache;
if (!context || !fastGlyph || !context->cache)
return FALSE;
cache = context->cache;
opLeft = fastGlyph->opLeft;
opTop = fastGlyph->opTop;
opRight = fastGlyph->opRight;
opBottom = fastGlyph->opBottom;
x = fastGlyph->x;
y = fastGlyph->y;
if (opBottom == -32768)
{
BYTE flags = (BYTE)(opTop & 0x0F);
if (flags & 0x01)
opBottom = fastGlyph->bkBottom;
if (flags & 0x02)
opRight = fastGlyph->bkRight;
if (flags & 0x04)
opTop = fastGlyph->bkTop;
if (flags & 0x08)
opLeft = fastGlyph->bkLeft;
}
if (opLeft == 0)
opLeft = fastGlyph->bkLeft;
if (opRight == 0)
opRight = fastGlyph->bkRight;
/* See update_gdi_fast_index opRight comment. */
if (opRight > (INT64)context->instance->settings->DesktopWidth)
opRight = (int)context->instance->settings->DesktopWidth;
if (x == -32768)
x = fastGlyph->bkLeft;
if (y == -32768)
y = fastGlyph->bkTop;
if ((fastGlyph->cbData > 1) && (fastGlyph->glyphData.aj))
{
/* got option font that needs to go into cache */
rdpGlyph* glyph;
const GLYPH_DATA_V2* glyphData = &fastGlyph->glyphData;
glyph = Glyph_Alloc(context, glyphData->x, glyphData->y, glyphData->cx, glyphData->cy,
glyphData->cb, glyphData->aj);
if (!glyph)
return FALSE;
if (!glyph_cache_put(cache->glyph, fastGlyph->cacheId, fastGlyph->data[0], glyph))
{
glyph->Free(context, glyph);
return FALSE;
}
}
text_data[0] = fastGlyph->data[0];
text_data[1] = 0;
if (fastGlyph->bkRight > fastGlyph->bkLeft)
bkWidth = fastGlyph->bkRight - fastGlyph->bkLeft + 1;
if (fastGlyph->bkBottom > fastGlyph->bkTop)
bkHeight = fastGlyph->bkBottom - fastGlyph->bkTop + 1;
if (opRight > opLeft)
opWidth = opRight - opLeft + 1;
if (opBottom > opTop)
opHeight = opBottom - opTop + 1;
return update_process_glyph_fragments(
context, text_data, sizeof(text_data), fastGlyph->cacheId, fastGlyph->ulCharInc,
fastGlyph->flAccel, fastGlyph->backColor, fastGlyph->foreColor, x, y, fastGlyph->bkLeft,
fastGlyph->bkTop, bkWidth, bkHeight, opLeft, opTop, opWidth, opHeight, FALSE);
}
static BOOL update_gdi_cache_glyph(rdpContext* context, const CACHE_GLYPH_ORDER* cacheGlyph)
{
UINT32 i;
rdpCache* cache;
if (!context || !cacheGlyph || !context->cache)
return FALSE;
cache = context->cache;
for (i = 0; i < cacheGlyph->cGlyphs; i++)
{
const GLYPH_DATA* glyph_data = &cacheGlyph->glyphData[i];
rdpGlyph* glyph;
if (!glyph_data)
return FALSE;
if (!(glyph = Glyph_Alloc(context, glyph_data->x, glyph_data->y, glyph_data->cx,
glyph_data->cy, glyph_data->cb, glyph_data->aj)))
return FALSE;
if (!glyph_cache_put(cache->glyph, cacheGlyph->cacheId, glyph_data->cacheIndex, glyph))
{
glyph->Free(context, glyph);
return FALSE;
}
}
return TRUE;
}
static BOOL update_gdi_cache_glyph_v2(rdpContext* context, const CACHE_GLYPH_V2_ORDER* cacheGlyphV2)
{
UINT32 i;
rdpCache* cache;
if (!context || !cacheGlyphV2 || !context->cache)
return FALSE;
cache = context->cache;
for (i = 0; i < cacheGlyphV2->cGlyphs; i++)
{
const GLYPH_DATA_V2* glyphData = &cacheGlyphV2->glyphData[i];
rdpGlyph* glyph;
if (!glyphData)
return FALSE;
glyph = Glyph_Alloc(context, glyphData->x, glyphData->y, glyphData->cx, glyphData->cy,
glyphData->cb, glyphData->aj);
if (!glyph)
return FALSE;
if (!glyph_cache_put(cache->glyph, cacheGlyphV2->cacheId, glyphData->cacheIndex, glyph))
{
glyph->Free(context, glyph);
return FALSE;
}
}
return TRUE;
}
rdpGlyph* glyph_cache_get(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index)
{
rdpGlyph* glyph;
WLog_Print(glyphCache->log, WLOG_DEBUG, "GlyphCacheGet: id: %" PRIu32 " index: %" PRIu32 "", id,
index);
if (id > 9)
{
WLog_ERR(TAG, "invalid glyph cache id: %" PRIu32 "", id);
return NULL;
}
if (index > glyphCache->glyphCache[id].number)
{
WLog_ERR(TAG, "index %" PRIu32 " out of range for cache id: %" PRIu32 "", index, id);
return NULL;
}
glyph = glyphCache->glyphCache[id].entries[index];
if (!glyph)
WLog_ERR(TAG, "no glyph found at cache index: %" PRIu32 " in cache id: %" PRIu32 "", index,
id);
return glyph;
}
BOOL glyph_cache_put(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index, rdpGlyph* glyph)
{
rdpGlyph* prevGlyph;
if (id > 9)
{
WLog_ERR(TAG, "invalid glyph cache id: %" PRIu32 "", id);
return FALSE;
}
if (index >= glyphCache->glyphCache[id].number)
{
WLog_ERR(TAG, "invalid glyph cache index: %" PRIu32 " in cache id: %" PRIu32 "", index, id);
return FALSE;
}
WLog_Print(glyphCache->log, WLOG_DEBUG, "GlyphCachePut: id: %" PRIu32 " index: %" PRIu32 "", id,
index);
prevGlyph = glyphCache->glyphCache[id].entries[index];
if (prevGlyph)
prevGlyph->Free(glyphCache->context, prevGlyph);
glyphCache->glyphCache[id].entries[index] = glyph;
return TRUE;
}
const void* glyph_cache_fragment_get(rdpGlyphCache* glyphCache, UINT32 index, UINT32* size)
{
void* fragment;
if (index > 255)
{
WLog_ERR(TAG, "invalid glyph cache fragment index: %" PRIu32 "", index);
return NULL;
}
fragment = glyphCache->fragCache.entries[index].fragment;
*size = (BYTE)glyphCache->fragCache.entries[index].size;
WLog_Print(glyphCache->log, WLOG_DEBUG,
"GlyphCacheFragmentGet: index: %" PRIu32 " size: %" PRIu32 "", index, *size);
if (!fragment)
WLog_ERR(TAG, "invalid glyph fragment at index:%" PRIu32 "", index);
return fragment;
}
BOOL glyph_cache_fragment_put(rdpGlyphCache* glyphCache, UINT32 index, UINT32 size,
const void* fragment)
{
void* prevFragment;
void* copy;
if (index > 255)
{
WLog_ERR(TAG, "invalid glyph cache fragment index: %" PRIu32 "", index);
return FALSE;
}
copy = malloc(size);
if (!copy)
return FALSE;
WLog_Print(glyphCache->log, WLOG_DEBUG,
"GlyphCacheFragmentPut: index: %" PRIu32 " size: %" PRIu32 "", index, size);
CopyMemory(copy, fragment, size);
prevFragment = glyphCache->fragCache.entries[index].fragment;
glyphCache->fragCache.entries[index].fragment = copy;
glyphCache->fragCache.entries[index].size = size;
free(prevFragment);
return TRUE;
}
void glyph_cache_register_callbacks(rdpUpdate* update)
{
update->primary->GlyphIndex = update_gdi_glyph_index;
update->primary->FastIndex = update_gdi_fast_index;
update->primary->FastGlyph = update_gdi_fast_glyph;
update->secondary->CacheGlyph = update_gdi_cache_glyph;
update->secondary->CacheGlyphV2 = update_gdi_cache_glyph_v2;
}
rdpGlyphCache* glyph_cache_new(rdpSettings* settings)
{
int i;
rdpGlyphCache* glyphCache;
glyphCache = (rdpGlyphCache*)calloc(1, sizeof(rdpGlyphCache));
if (!glyphCache)
return NULL;
glyphCache->log = WLog_Get("com.freerdp.cache.glyph");
glyphCache->settings = settings;
glyphCache->context = ((freerdp*)settings->instance)->update->context;
for (i = 0; i < 10; i++)
{
glyphCache->glyphCache[i].number = settings->GlyphCache[i].cacheEntries;
glyphCache->glyphCache[i].maxCellSize = settings->GlyphCache[i].cacheMaximumCellSize;
glyphCache->glyphCache[i].entries =
(rdpGlyph**)calloc(glyphCache->glyphCache[i].number, sizeof(rdpGlyph*));
if (!glyphCache->glyphCache[i].entries)
goto fail;
}
glyphCache->fragCache.entries = calloc(256, sizeof(FRAGMENT_CACHE_ENTRY));
if (!glyphCache->fragCache.entries)
goto fail;
return glyphCache;
fail:
glyph_cache_free(glyphCache);
return NULL;
}
void glyph_cache_free(rdpGlyphCache* glyphCache)
{
if (glyphCache)
{
int i;
GLYPH_CACHE* cache = glyphCache->glyphCache;
for (i = 0; i < 10; i++)
{
UINT32 j;
rdpGlyph** entries = cache[i].entries;
if (!entries)
continue;
for (j = 0; j < cache[i].number; j++)
{
rdpGlyph* glyph = entries[j];
if (glyph)
{
glyph->Free(glyphCache->context, glyph);
entries[j] = NULL;
}
}
free(entries);
cache[i].entries = NULL;
}
if (glyphCache->fragCache.entries)
{
for (i = 0; i < 256; i++)
{
free(glyphCache->fragCache.entries[i].fragment);
glyphCache->fragCache.entries[i].fragment = NULL;
}
}
free(glyphCache->fragCache.entries);
free(glyphCache);
}
}
CACHE_GLYPH_ORDER* copy_cache_glyph_order(rdpContext* context, const CACHE_GLYPH_ORDER* glyph)
{
size_t x;
CACHE_GLYPH_ORDER* dst = calloc(1, sizeof(CACHE_GLYPH_ORDER));
if (!dst || !glyph)
goto fail;
*dst = *glyph;
for (x = 0; x < glyph->cGlyphs; x++)
{
const GLYPH_DATA* src = &glyph->glyphData[x];
GLYPH_DATA* data = &dst->glyphData[x];
if (src->aj)
{
const size_t size = src->cb;
data->aj = malloc(size);
if (!data->aj)
goto fail;
memcpy(data->aj, src->aj, size);
}
}
if (glyph->unicodeCharacters)
{
if (glyph->cGlyphs == 0)
goto fail;
dst->unicodeCharacters = calloc(glyph->cGlyphs, sizeof(WCHAR));
if (!dst->unicodeCharacters)
goto fail;
memcpy(dst->unicodeCharacters, glyph->unicodeCharacters, sizeof(WCHAR) * glyph->cGlyphs);
}
return dst;
fail:
free_cache_glyph_order(context, dst);
return NULL;
}
void free_cache_glyph_order(rdpContext* context, CACHE_GLYPH_ORDER* glyph)
{
if (glyph)
{
size_t x;
for (x = 0; x < ARRAYSIZE(glyph->glyphData); x++)
free(glyph->glyphData[x].aj);
free(glyph->unicodeCharacters);
}
free(glyph);
}
CACHE_GLYPH_V2_ORDER* copy_cache_glyph_v2_order(rdpContext* context,
const CACHE_GLYPH_V2_ORDER* glyph)
{
size_t x;
CACHE_GLYPH_V2_ORDER* dst = calloc(1, sizeof(CACHE_GLYPH_V2_ORDER));
if (!dst || !glyph)
goto fail;
*dst = *glyph;
for (x = 0; x < glyph->cGlyphs; x++)
{
const GLYPH_DATA_V2* src = &glyph->glyphData[x];
GLYPH_DATA_V2* data = &dst->glyphData[x];
if (src->aj)
{
const size_t size = src->cb;
data->aj = malloc(size);
if (!data->aj)
goto fail;
memcpy(data->aj, src->aj, size);
}
}
if (glyph->unicodeCharacters)
{
if (glyph->cGlyphs == 0)
goto fail;
dst->unicodeCharacters = calloc(glyph->cGlyphs, sizeof(WCHAR));
if (!dst->unicodeCharacters)
goto fail;
memcpy(dst->unicodeCharacters, glyph->unicodeCharacters, sizeof(WCHAR) * glyph->cGlyphs);
}
return dst;
fail:
free_cache_glyph_v2_order(context, dst);
return NULL;
}
void free_cache_glyph_v2_order(rdpContext* context, CACHE_GLYPH_V2_ORDER* glyph)
{
if (glyph)
{
size_t x;
for (x = 0; x < ARRAYSIZE(glyph->glyphData); x++)
free(glyph->glyphData[x].aj);
free(glyph->unicodeCharacters);
}
free(glyph);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3954_0 |
crossvul-cpp_data_bad_2724_0 | /*
* Copyright (c) 1998-2007 The TCPDUMP project
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Original code by Hannes Gredler (hannes@gredler.at)
*/
/* \summary: Resource ReSerVation Protocol (RSVP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "ethertype.h"
#include "gmpls.h"
#include "af.h"
#include "signature.h"
static const char tstr[] = " [|rsvp]";
/*
* RFC 2205 common header
*
* 0 1 2 3
* +-------------+-------------+-------------+-------------+
* | Vers | Flags| Msg Type | RSVP Checksum |
* +-------------+-------------+-------------+-------------+
* | Send_TTL | (Reserved) | RSVP Length |
* +-------------+-------------+-------------+-------------+
*
*/
struct rsvp_common_header {
uint8_t version_flags;
uint8_t msg_type;
uint8_t checksum[2];
uint8_t ttl;
uint8_t reserved;
uint8_t length[2];
};
/*
* RFC2205 object header
*
*
* 0 1 2 3
* +-------------+-------------+-------------+-------------+
* | Length (bytes) | Class-Num | C-Type |
* +-------------+-------------+-------------+-------------+
* | |
* // (Object contents) //
* | |
* +-------------+-------------+-------------+-------------+
*/
struct rsvp_object_header {
uint8_t length[2];
uint8_t class_num;
uint8_t ctype;
};
#define RSVP_VERSION 1
#define RSVP_EXTRACT_VERSION(x) (((x)&0xf0)>>4)
#define RSVP_EXTRACT_FLAGS(x) ((x)&0x0f)
#define RSVP_MSGTYPE_PATH 1
#define RSVP_MSGTYPE_RESV 2
#define RSVP_MSGTYPE_PATHERR 3
#define RSVP_MSGTYPE_RESVERR 4
#define RSVP_MSGTYPE_PATHTEAR 5
#define RSVP_MSGTYPE_RESVTEAR 6
#define RSVP_MSGTYPE_RESVCONF 7
#define RSVP_MSGTYPE_BUNDLE 12
#define RSVP_MSGTYPE_ACK 13
#define RSVP_MSGTYPE_HELLO_OLD 14 /* ancient Hellos */
#define RSVP_MSGTYPE_SREFRESH 15
#define RSVP_MSGTYPE_HELLO 20
static const struct tok rsvp_msg_type_values[] = {
{ RSVP_MSGTYPE_PATH, "Path" },
{ RSVP_MSGTYPE_RESV, "Resv" },
{ RSVP_MSGTYPE_PATHERR, "PathErr" },
{ RSVP_MSGTYPE_RESVERR, "ResvErr" },
{ RSVP_MSGTYPE_PATHTEAR, "PathTear" },
{ RSVP_MSGTYPE_RESVTEAR, "ResvTear" },
{ RSVP_MSGTYPE_RESVCONF, "ResvConf" },
{ RSVP_MSGTYPE_BUNDLE, "Bundle" },
{ RSVP_MSGTYPE_ACK, "Acknowledgement" },
{ RSVP_MSGTYPE_HELLO_OLD, "Hello (Old)" },
{ RSVP_MSGTYPE_SREFRESH, "Refresh" },
{ RSVP_MSGTYPE_HELLO, "Hello" },
{ 0, NULL}
};
static const struct tok rsvp_header_flag_values[] = {
{ 0x01, "Refresh reduction capable" }, /* rfc2961 */
{ 0, NULL}
};
#define RSVP_OBJ_SESSION 1 /* rfc2205 */
#define RSVP_OBJ_RSVP_HOP 3 /* rfc2205, rfc3473 */
#define RSVP_OBJ_INTEGRITY 4 /* rfc2747 */
#define RSVP_OBJ_TIME_VALUES 5 /* rfc2205 */
#define RSVP_OBJ_ERROR_SPEC 6
#define RSVP_OBJ_SCOPE 7
#define RSVP_OBJ_STYLE 8 /* rfc2205 */
#define RSVP_OBJ_FLOWSPEC 9 /* rfc2215 */
#define RSVP_OBJ_FILTERSPEC 10 /* rfc2215 */
#define RSVP_OBJ_SENDER_TEMPLATE 11
#define RSVP_OBJ_SENDER_TSPEC 12 /* rfc2215 */
#define RSVP_OBJ_ADSPEC 13 /* rfc2215 */
#define RSVP_OBJ_POLICY_DATA 14
#define RSVP_OBJ_CONFIRM 15 /* rfc2205 */
#define RSVP_OBJ_LABEL 16 /* rfc3209 */
#define RSVP_OBJ_LABEL_REQ 19 /* rfc3209 */
#define RSVP_OBJ_ERO 20 /* rfc3209 */
#define RSVP_OBJ_RRO 21 /* rfc3209 */
#define RSVP_OBJ_HELLO 22 /* rfc3209 */
#define RSVP_OBJ_MESSAGE_ID 23 /* rfc2961 */
#define RSVP_OBJ_MESSAGE_ID_ACK 24 /* rfc2961 */
#define RSVP_OBJ_MESSAGE_ID_LIST 25 /* rfc2961 */
#define RSVP_OBJ_RECOVERY_LABEL 34 /* rfc3473 */
#define RSVP_OBJ_UPSTREAM_LABEL 35 /* rfc3473 */
#define RSVP_OBJ_LABEL_SET 36 /* rfc3473 */
#define RSVP_OBJ_PROTECTION 37 /* rfc3473 */
#define RSVP_OBJ_S2L 50 /* rfc4875 */
#define RSVP_OBJ_DETOUR 63 /* draft-ietf-mpls-rsvp-lsp-fastreroute-07 */
#define RSVP_OBJ_CLASSTYPE 66 /* rfc4124 */
#define RSVP_OBJ_CLASSTYPE_OLD 125 /* draft-ietf-tewg-diff-te-proto-07 */
#define RSVP_OBJ_SUGGESTED_LABEL 129 /* rfc3473 */
#define RSVP_OBJ_ACCEPT_LABEL_SET 130 /* rfc3473 */
#define RSVP_OBJ_RESTART_CAPABILITY 131 /* rfc3473 */
#define RSVP_OBJ_NOTIFY_REQ 195 /* rfc3473 */
#define RSVP_OBJ_ADMIN_STATUS 196 /* rfc3473 */
#define RSVP_OBJ_PROPERTIES 204 /* juniper proprietary */
#define RSVP_OBJ_FASTREROUTE 205 /* draft-ietf-mpls-rsvp-lsp-fastreroute-07 */
#define RSVP_OBJ_SESSION_ATTRIBUTE 207 /* rfc3209 */
#define RSVP_OBJ_GENERALIZED_UNI 229 /* OIF RSVP extensions UNI 1.0 Signaling, Rel. 2 */
#define RSVP_OBJ_CALL_ID 230 /* rfc3474 */
#define RSVP_OBJ_CALL_OPS 236 /* rfc3474 */
static const struct tok rsvp_obj_values[] = {
{ RSVP_OBJ_SESSION, "Session" },
{ RSVP_OBJ_RSVP_HOP, "RSVP Hop" },
{ RSVP_OBJ_INTEGRITY, "Integrity" },
{ RSVP_OBJ_TIME_VALUES, "Time Values" },
{ RSVP_OBJ_ERROR_SPEC, "Error Spec" },
{ RSVP_OBJ_SCOPE, "Scope" },
{ RSVP_OBJ_STYLE, "Style" },
{ RSVP_OBJ_FLOWSPEC, "Flowspec" },
{ RSVP_OBJ_FILTERSPEC, "FilterSpec" },
{ RSVP_OBJ_SENDER_TEMPLATE, "Sender Template" },
{ RSVP_OBJ_SENDER_TSPEC, "Sender TSpec" },
{ RSVP_OBJ_ADSPEC, "Adspec" },
{ RSVP_OBJ_POLICY_DATA, "Policy Data" },
{ RSVP_OBJ_CONFIRM, "Confirm" },
{ RSVP_OBJ_LABEL, "Label" },
{ RSVP_OBJ_LABEL_REQ, "Label Request" },
{ RSVP_OBJ_ERO, "ERO" },
{ RSVP_OBJ_RRO, "RRO" },
{ RSVP_OBJ_HELLO, "Hello" },
{ RSVP_OBJ_MESSAGE_ID, "Message ID" },
{ RSVP_OBJ_MESSAGE_ID_ACK, "Message ID Ack" },
{ RSVP_OBJ_MESSAGE_ID_LIST, "Message ID List" },
{ RSVP_OBJ_RECOVERY_LABEL, "Recovery Label" },
{ RSVP_OBJ_UPSTREAM_LABEL, "Upstream Label" },
{ RSVP_OBJ_LABEL_SET, "Label Set" },
{ RSVP_OBJ_ACCEPT_LABEL_SET, "Acceptable Label Set" },
{ RSVP_OBJ_DETOUR, "Detour" },
{ RSVP_OBJ_CLASSTYPE, "Class Type" },
{ RSVP_OBJ_CLASSTYPE_OLD, "Class Type (old)" },
{ RSVP_OBJ_SUGGESTED_LABEL, "Suggested Label" },
{ RSVP_OBJ_PROPERTIES, "Properties" },
{ RSVP_OBJ_FASTREROUTE, "Fast Re-Route" },
{ RSVP_OBJ_SESSION_ATTRIBUTE, "Session Attribute" },
{ RSVP_OBJ_GENERALIZED_UNI, "Generalized UNI" },
{ RSVP_OBJ_CALL_ID, "Call-ID" },
{ RSVP_OBJ_CALL_OPS, "Call Capability" },
{ RSVP_OBJ_RESTART_CAPABILITY, "Restart Capability" },
{ RSVP_OBJ_NOTIFY_REQ, "Notify Request" },
{ RSVP_OBJ_PROTECTION, "Protection" },
{ RSVP_OBJ_ADMIN_STATUS, "Administrative Status" },
{ RSVP_OBJ_S2L, "Sub-LSP to LSP" },
{ 0, NULL}
};
#define RSVP_CTYPE_IPV4 1
#define RSVP_CTYPE_IPV6 2
#define RSVP_CTYPE_TUNNEL_IPV4 7
#define RSVP_CTYPE_TUNNEL_IPV6 8
#define RSVP_CTYPE_UNI_IPV4 11 /* OIF RSVP extensions UNI 1.0 Signaling Rel. 2 */
#define RSVP_CTYPE_1 1
#define RSVP_CTYPE_2 2
#define RSVP_CTYPE_3 3
#define RSVP_CTYPE_4 4
#define RSVP_CTYPE_12 12
#define RSVP_CTYPE_13 13
#define RSVP_CTYPE_14 14
/*
* the ctypes are not globally unique so for
* translating it to strings we build a table based
* on objects offsetted by the ctype
*/
static const struct tok rsvp_ctype_values[] = {
{ 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_3, "IPv4 plus opt. TLVs" },
{ 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_4, "IPv6 plus opt. TLVs" },
{ 256*RSVP_OBJ_NOTIFY_REQ+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_NOTIFY_REQ+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_CONFIRM+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_CONFIRM+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_TIME_VALUES+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_FLOWSPEC+RSVP_CTYPE_1, "obsolete" },
{ 256*RSVP_OBJ_FLOWSPEC+RSVP_CTYPE_2, "IntServ" },
{ 256*RSVP_OBJ_SENDER_TSPEC+RSVP_CTYPE_2, "IntServ" },
{ 256*RSVP_OBJ_ADSPEC+RSVP_CTYPE_2, "IntServ" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_3, "IPv6 Flow-label" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_12, "IPv4 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_13, "IPv6 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_UNI_IPV4, "UNI IPv4" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_13, "IPv4 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_14, "IPv6 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_12, "IPv4 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_13, "IPv6 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_MESSAGE_ID+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_MESSAGE_ID_ACK+RSVP_CTYPE_1, "Message id ack" },
{ 256*RSVP_OBJ_MESSAGE_ID_ACK+RSVP_CTYPE_2, "Message id nack" },
{ 256*RSVP_OBJ_MESSAGE_ID_LIST+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_STYLE+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_HELLO+RSVP_CTYPE_1, "Hello Request" },
{ 256*RSVP_OBJ_HELLO+RSVP_CTYPE_2, "Hello Ack" },
{ 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_1, "without label range" },
{ 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_2, "with ATM label range" },
{ 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_3, "with FR label range" },
{ 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_4, "Generalized Label" },
{ 256*RSVP_OBJ_LABEL+RSVP_CTYPE_1, "Label" },
{ 256*RSVP_OBJ_LABEL+RSVP_CTYPE_2, "Generalized Label" },
{ 256*RSVP_OBJ_LABEL+RSVP_CTYPE_3, "Waveband Switching" },
{ 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_1, "Label" },
{ 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_2, "Generalized Label" },
{ 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_3, "Waveband Switching" },
{ 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_1, "Label" },
{ 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_2, "Generalized Label" },
{ 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_3, "Waveband Switching" },
{ 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_1, "Label" },
{ 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_2, "Generalized Label" },
{ 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_3, "Waveband Switching" },
{ 256*RSVP_OBJ_ERO+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_RRO+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_3, "IPv4 plus opt. TLVs" },
{ 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_4, "IPv6 plus opt. TLVs" },
{ 256*RSVP_OBJ_RESTART_CAPABILITY+RSVP_CTYPE_1, "IPv4" },
{ 256*RSVP_OBJ_SESSION_ATTRIBUTE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_FASTREROUTE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, /* old style*/
{ 256*RSVP_OBJ_FASTREROUTE+RSVP_CTYPE_1, "1" }, /* new style */
{ 256*RSVP_OBJ_DETOUR+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_PROPERTIES+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_ADMIN_STATUS+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_CLASSTYPE+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_CLASSTYPE_OLD+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_LABEL_SET+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_GENERALIZED_UNI+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_S2L+RSVP_CTYPE_IPV4, "IPv4 sub-LSP" },
{ 256*RSVP_OBJ_S2L+RSVP_CTYPE_IPV6, "IPv6 sub-LSP" },
{ 0, NULL}
};
struct rsvp_obj_integrity_t {
uint8_t flags;
uint8_t res;
uint8_t key_id[6];
uint8_t sequence[8];
uint8_t digest[16];
};
static const struct tok rsvp_obj_integrity_flag_values[] = {
{ 0x80, "Handshake" },
{ 0, NULL}
};
struct rsvp_obj_frr_t {
uint8_t setup_prio;
uint8_t hold_prio;
uint8_t hop_limit;
uint8_t flags;
uint8_t bandwidth[4];
uint8_t include_any[4];
uint8_t exclude_any[4];
uint8_t include_all[4];
};
#define RSVP_OBJ_XRO_MASK_SUBOBJ(x) ((x)&0x7f)
#define RSVP_OBJ_XRO_MASK_LOOSE(x) ((x)&0x80)
#define RSVP_OBJ_XRO_RES 0
#define RSVP_OBJ_XRO_IPV4 1
#define RSVP_OBJ_XRO_IPV6 2
#define RSVP_OBJ_XRO_LABEL 3
#define RSVP_OBJ_XRO_ASN 32
#define RSVP_OBJ_XRO_MPLS 64
static const struct tok rsvp_obj_xro_values[] = {
{ RSVP_OBJ_XRO_RES, "Reserved" },
{ RSVP_OBJ_XRO_IPV4, "IPv4 prefix" },
{ RSVP_OBJ_XRO_IPV6, "IPv6 prefix" },
{ RSVP_OBJ_XRO_LABEL, "Label" },
{ RSVP_OBJ_XRO_ASN, "Autonomous system number" },
{ RSVP_OBJ_XRO_MPLS, "MPLS label switched path termination" },
{ 0, NULL}
};
/* draft-ietf-mpls-rsvp-lsp-fastreroute-07.txt */
static const struct tok rsvp_obj_rro_flag_values[] = {
{ 0x01, "Local protection available" },
{ 0x02, "Local protection in use" },
{ 0x04, "Bandwidth protection" },
{ 0x08, "Node protection" },
{ 0, NULL}
};
/* RFC3209 */
static const struct tok rsvp_obj_rro_label_flag_values[] = {
{ 0x01, "Global" },
{ 0, NULL}
};
static const struct tok rsvp_resstyle_values[] = {
{ 17, "Wildcard Filter" },
{ 10, "Fixed Filter" },
{ 18, "Shared Explicit" },
{ 0, NULL}
};
#define RSVP_OBJ_INTSERV_GUARANTEED_SERV 2
#define RSVP_OBJ_INTSERV_CONTROLLED_LOAD 5
static const struct tok rsvp_intserv_service_type_values[] = {
{ 1, "Default/Global Information" },
{ RSVP_OBJ_INTSERV_GUARANTEED_SERV, "Guaranteed Service" },
{ RSVP_OBJ_INTSERV_CONTROLLED_LOAD, "Controlled Load" },
{ 0, NULL}
};
static const struct tok rsvp_intserv_parameter_id_values[] = {
{ 4, "IS hop cnt" },
{ 6, "Path b/w estimate" },
{ 8, "Minimum path latency" },
{ 10, "Composed MTU" },
{ 127, "Token Bucket TSpec" },
{ 130, "Guaranteed Service RSpec" },
{ 133, "End-to-end composed value for C" },
{ 134, "End-to-end composed value for D" },
{ 135, "Since-last-reshaping point composed C" },
{ 136, "Since-last-reshaping point composed D" },
{ 0, NULL}
};
static const struct tok rsvp_session_attribute_flag_values[] = {
{ 0x01, "Local Protection" },
{ 0x02, "Label Recording" },
{ 0x04, "SE Style" },
{ 0x08, "Bandwidth protection" }, /* RFC4090 */
{ 0x10, "Node protection" }, /* RFC4090 */
{ 0, NULL}
};
static const struct tok rsvp_obj_prop_tlv_values[] = {
{ 0x01, "Cos" },
{ 0x02, "Metric 1" },
{ 0x04, "Metric 2" },
{ 0x08, "CCC Status" },
{ 0x10, "Path Type" },
{ 0, NULL}
};
#define RSVP_OBJ_ERROR_SPEC_CODE_ROUTING 24
#define RSVP_OBJ_ERROR_SPEC_CODE_NOTIFY 25
#define RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE 28
#define RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD 125
static const struct tok rsvp_obj_error_code_values[] = {
{ RSVP_OBJ_ERROR_SPEC_CODE_ROUTING, "Routing Problem" },
{ RSVP_OBJ_ERROR_SPEC_CODE_NOTIFY, "Notify Error" },
{ RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE, "Diffserv TE Error" },
{ RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD, "Diffserv TE Error (Old)" },
{ 0, NULL}
};
static const struct tok rsvp_obj_error_code_routing_values[] = {
{ 1, "Bad EXPLICIT_ROUTE object" },
{ 2, "Bad strict node" },
{ 3, "Bad loose node" },
{ 4, "Bad initial subobject" },
{ 5, "No route available toward destination" },
{ 6, "Unacceptable label value" },
{ 7, "RRO indicated routing loops" },
{ 8, "non-RSVP-capable router in the path" },
{ 9, "MPLS label allocation failure" },
{ 10, "Unsupported L3PID" },
{ 0, NULL}
};
static const struct tok rsvp_obj_error_code_diffserv_te_values[] = {
{ 1, "Unexpected CT object" },
{ 2, "Unsupported CT" },
{ 3, "Invalid CT value" },
{ 4, "CT/setup priority do not form a configured TE-Class" },
{ 5, "CT/holding priority do not form a configured TE-Class" },
{ 6, "CT/setup priority and CT/holding priority do not form a configured TE-Class" },
{ 7, "Inconsistency between signaled PSC and signaled CT" },
{ 8, "Inconsistency between signaled PHBs and signaled CT" },
{ 0, NULL}
};
/* rfc3473 / rfc 3471 */
static const struct tok rsvp_obj_admin_status_flag_values[] = {
{ 0x80000000, "Reflect" },
{ 0x00000004, "Testing" },
{ 0x00000002, "Admin-down" },
{ 0x00000001, "Delete-in-progress" },
{ 0, NULL}
};
/* label set actions - rfc3471 */
#define LABEL_SET_INCLUSIVE_LIST 0
#define LABEL_SET_EXCLUSIVE_LIST 1
#define LABEL_SET_INCLUSIVE_RANGE 2
#define LABEL_SET_EXCLUSIVE_RANGE 3
static const struct tok rsvp_obj_label_set_action_values[] = {
{ LABEL_SET_INCLUSIVE_LIST, "Inclusive list" },
{ LABEL_SET_EXCLUSIVE_LIST, "Exclusive list" },
{ LABEL_SET_INCLUSIVE_RANGE, "Inclusive range" },
{ LABEL_SET_EXCLUSIVE_RANGE, "Exclusive range" },
{ 0, NULL}
};
/* OIF RSVP extensions UNI 1.0 Signaling, release 2 */
#define RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS 1
#define RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS 2
#define RSVP_GEN_UNI_SUBOBJ_DIVERSITY 3
#define RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL 4
#define RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL 5
static const struct tok rsvp_obj_generalized_uni_values[] = {
{ RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS, "Source TNA address" },
{ RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS, "Destination TNA address" },
{ RSVP_GEN_UNI_SUBOBJ_DIVERSITY, "Diversity" },
{ RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL, "Egress label" },
{ RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL, "Service level" },
{ 0, NULL}
};
/*
* this is a dissector for all the intserv defined
* specs as defined per rfc2215
* it is called from various rsvp objects;
* returns the amount of bytes being processed
*/
static int
rsvp_intserv_print(netdissect_options *ndo,
const u_char *tptr, u_short obj_tlen)
{
int parameter_id,parameter_length;
union {
float f;
uint32_t i;
} bw;
if (obj_tlen < 4)
return 0;
parameter_id = *(tptr);
ND_TCHECK2(*(tptr + 2), 2);
parameter_length = EXTRACT_16BITS(tptr+2)<<2; /* convert wordcount to bytecount */
ND_PRINT((ndo, "\n\t Parameter ID: %s (%u), length: %u, Flags: [0x%02x]",
tok2str(rsvp_intserv_parameter_id_values,"unknown",parameter_id),
parameter_id,
parameter_length,
*(tptr + 1)));
if (obj_tlen < parameter_length+4)
return 0;
switch(parameter_id) { /* parameter_id */
case 4:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 4 (e) | (f) | 1 (g) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IS hop cnt (32-bit unsigned integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, "\n\t\tIS hop count: %u", EXTRACT_32BITS(tptr + 4)));
}
break;
case 6:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 6 (h) | (i) | 1 (j) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Path b/w estimate (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
bw.i = EXTRACT_32BITS(tptr+4);
ND_PRINT((ndo, "\n\t\tPath b/w estimate: %.10g Mbps", bw.f / 125000));
}
break;
case 8:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 8 (k) | (l) | 1 (m) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Minimum path latency (32-bit integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, "\n\t\tMinimum path latency: "));
if (EXTRACT_32BITS(tptr+4) == 0xffffffff)
ND_PRINT((ndo, "don't care"));
else
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr + 4)));
}
break;
case 10:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 10 (n) | (o) | 1 (p) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Composed MTU (32-bit unsigned integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, "\n\t\tComposed MTU: %u bytes", EXTRACT_32BITS(tptr + 4)));
}
break;
case 127:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 127 (e) | 0 (f) | 5 (g) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Token Bucket Rate [r] (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Token Bucket Size [b] (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Peak Data Rate [p] (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Minimum Policed Unit [m] (32-bit integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Maximum Packet Size [M] (32-bit integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 20) {
ND_TCHECK2(*(tptr + 4), 20);
bw.i = EXTRACT_32BITS(tptr+4);
ND_PRINT((ndo, "\n\t\tToken Bucket Rate: %.10g Mbps", bw.f / 125000));
bw.i = EXTRACT_32BITS(tptr+8);
ND_PRINT((ndo, "\n\t\tToken Bucket Size: %.10g bytes", bw.f));
bw.i = EXTRACT_32BITS(tptr+12);
ND_PRINT((ndo, "\n\t\tPeak Data Rate: %.10g Mbps", bw.f / 125000));
ND_PRINT((ndo, "\n\t\tMinimum Policed Unit: %u bytes", EXTRACT_32BITS(tptr + 16)));
ND_PRINT((ndo, "\n\t\tMaximum Packet Size: %u bytes", EXTRACT_32BITS(tptr + 20)));
}
break;
case 130:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 130 (h) | 0 (i) | 2 (j) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Rate [R] (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Slack Term [S] (32-bit integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 8) {
ND_TCHECK2(*(tptr + 4), 8);
bw.i = EXTRACT_32BITS(tptr+4);
ND_PRINT((ndo, "\n\t\tRate: %.10g Mbps", bw.f / 125000));
ND_PRINT((ndo, "\n\t\tSlack Term: %u", EXTRACT_32BITS(tptr + 8)));
}
break;
case 133:
case 134:
case 135:
case 136:
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, "\n\t\tValue: %u", EXTRACT_32BITS(tptr + 4)));
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr + 4, "\n\t\t", parameter_length);
}
return (parameter_length+4); /* header length 4 bytes */
trunc:
ND_PRINT((ndo, "%s", tstr));
return 0;
}
/*
* Clear checksum prior to signature verification.
*/
static void
rsvp_clear_checksum(void *header)
{
struct rsvp_common_header *rsvp_com_header = (struct rsvp_common_header *) header;
rsvp_com_header->checksum[0] = 0;
rsvp_com_header->checksum[1] = 0;
}
static int
rsvp_obj_print(netdissect_options *ndo,
const u_char *pptr, u_int plen, const u_char *tptr,
const char *ident, u_int tlen,
const struct rsvp_common_header *rsvp_com_header)
{
const struct rsvp_object_header *rsvp_obj_header;
const u_char *obj_tptr;
union {
const struct rsvp_obj_integrity_t *rsvp_obj_integrity;
const struct rsvp_obj_frr_t *rsvp_obj_frr;
} obj_ptr;
u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen;
int hexdump,processed,padbytes,error_code,error_value,i,sigcheck;
union {
float f;
uint32_t i;
} bw;
uint8_t namelen;
u_int action, subchannel;
while(tlen>=sizeof(struct rsvp_object_header)) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header));
rsvp_obj_header = (const struct rsvp_object_header *)tptr;
rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length);
rsvp_obj_ctype=rsvp_obj_header->ctype;
if(rsvp_obj_len % 4) {
ND_PRINT((ndo, "%sERROR: object header size %u not a multiple of 4", ident, rsvp_obj_len));
return -1;
}
if(rsvp_obj_len < sizeof(struct rsvp_object_header)) {
ND_PRINT((ndo, "%sERROR: object header too short %u < %lu", ident, rsvp_obj_len,
(unsigned long)sizeof(const struct rsvp_object_header)));
return -1;
}
ND_PRINT((ndo, "%s%s Object (%u) Flags: [%s",
ident,
tok2str(rsvp_obj_values,
"Unknown",
rsvp_obj_header->class_num),
rsvp_obj_header->class_num,
((rsvp_obj_header->class_num) & 0x80) ? "ignore" : "reject"));
if (rsvp_obj_header->class_num > 128)
ND_PRINT((ndo, " %s",
((rsvp_obj_header->class_num) & 0x40) ? "and forward" : "silently"));
ND_PRINT((ndo, " if unknown], Class-Type: %s (%u), length: %u",
tok2str(rsvp_ctype_values,
"Unknown",
((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype),
rsvp_obj_ctype,
rsvp_obj_len));
if(tlen < rsvp_obj_len) {
ND_PRINT((ndo, "%sERROR: object goes past end of objects TLV", ident));
return -1;
}
obj_tptr=tptr+sizeof(struct rsvp_object_header);
obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header);
/* did we capture enough for fully decoding the object ? */
if (!ND_TTEST2(*tptr, rsvp_obj_len))
return -1;
hexdump=FALSE;
switch(rsvp_obj_header->class_num) {
case RSVP_OBJ_SESSION:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return -1;
ND_PRINT((ndo, "%s IPv4 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+5),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return -1;
ND_PRINT((ndo, "%s IPv6 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in6_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+sizeof(struct in6_addr)+1),
EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 36)
return -1;
ND_PRINT((ndo, "%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ip6addr_string(ndo, obj_tptr + 20)));
obj_tlen-=36;
obj_tptr+=36;
break;
case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */
if (obj_tlen < 26)
return -1;
ND_PRINT((ndo, "%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ip6addr_string(ndo, obj_tptr + 8)));
obj_tlen-=26;
obj_tptr+=26;
break;
case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
case RSVP_CTYPE_UNI_IPV4:
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CONFIRM:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Receiver Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return -1;
ND_PRINT((ndo, "%s IPv6 Receiver Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_NOTIFY_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Notify Node Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return-1;
ND_PRINT((ndo, "%s IPv6 Notify Node Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */
case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */
case RSVP_OBJ_RECOVERY_LABEL: /* fall through */
case RSVP_OBJ_LABEL:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Label: %u", ident, EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Generalized Label: %u",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s Waveband ID: %u%s Start Label: %u, Stop Label: %u",
ident,
EXTRACT_32BITS(obj_tptr),
ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_STYLE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Reservation Style: %s, Flags: [0x%02x]",
ident,
tok2str(rsvp_resstyle_values,
"Unknown",
EXTRACT_24BITS(obj_tptr+1)),
*(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SENDER_TEMPLATE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, ",%s merge capability",((*(obj_tptr + 4)) & 0x80) ? "no" : "" ));
ND_PRINT((ndo, "%s Minimum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+4))&0xfff,
(EXTRACT_16BITS(obj_tptr + 6)) & 0xfff));
ND_PRINT((ndo, "%s Maximum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+8))&0xfff,
(EXTRACT_16BITS(obj_tptr + 10)) & 0xfff));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, "%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI",
ident,
(EXTRACT_32BITS(obj_tptr+4))&0x7fffff,
(EXTRACT_32BITS(obj_tptr+8))&0x7fffff,
(((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? "10" : "",
(((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? "23" : ""));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s LSP Encoding Type: %s (%u)",
ident,
tok2str(gmpls_encoding_values,
"Unknown",
*obj_tptr),
*obj_tptr));
ND_PRINT((ndo, "%s Switching Type: %s (%u), Payload ID: %s (0x%04x)",
ident,
tok2str(gmpls_switch_cap_values,
"Unknown",
*(obj_tptr+1)),
*(obj_tptr+1),
tok2str(gmpls_payload_values,
"Unknown",
EXTRACT_16BITS(obj_tptr+2)),
EXTRACT_16BITS(obj_tptr + 2)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RRO:
case RSVP_OBJ_ERO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
while(obj_tlen >= 4 ) {
u_char length;
ND_TCHECK2(*obj_tptr, 4);
length = *(obj_tptr + 1);
ND_PRINT((ndo, "%s Subobject Type: %s, length %u",
ident,
tok2str(rsvp_obj_xro_values,
"Unknown %u",
RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)),
length));
if (length == 0) { /* prevent infinite loops */
ND_PRINT((ndo, "%s ERROR: zero length ERO subtype", ident));
break;
}
switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) {
u_char prefix_length;
case RSVP_OBJ_XRO_IPV4:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
prefix_length = *(obj_tptr+6);
if (prefix_length != 32) {
ND_PRINT((ndo, " ERROR: Prefix length %u != 32",
prefix_length));
goto invalid;
}
ND_PRINT((ndo, ", %s, %s/%u, Flags: [%s]",
RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? "Loose" : "Strict",
ipaddr_string(ndo, obj_tptr+2),
*(obj_tptr+6),
bittok2str(rsvp_obj_rro_flag_values,
"none",
*(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */
break;
case RSVP_OBJ_XRO_LABEL:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
ND_PRINT((ndo, ", Flags: [%s] (%#x), Class-Type: %s (%u), %u",
bittok2str(rsvp_obj_rro_label_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr+2),
tok2str(rsvp_ctype_values,
"Unknown",
*(obj_tptr+3) + 256*RSVP_OBJ_RRO),
*(obj_tptr+3),
EXTRACT_32BITS(obj_tptr + 4)));
}
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_HELLO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Instance: 0x%08x, Destination Instance: 0x%08x",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RESTART_CAPABILITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Restart Time: %ums, Recovery Time: %ums",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SESSION_ATTRIBUTE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 4)
return-1;
namelen = *(obj_tptr+3);
if (obj_tlen < 4+namelen)
return-1;
ND_PRINT((ndo, "%s Session Name: ", ident));
for (i = 0; i < namelen; i++)
safeputchar(ndo, *(obj_tptr + 4 + i));
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)",
ident,
(int)*obj_tptr,
(int)*(obj_tptr+1),
bittok2str(rsvp_session_attribute_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr + 2)));
obj_tlen-=4+*(obj_tptr+3);
obj_tptr+=4+*(obj_tptr+3);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_GENERALIZED_UNI:
switch(rsvp_obj_ctype) {
int subobj_type,af,subobj_len,total_subobj_len;
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
/* read variable length subobjects */
total_subobj_len = obj_tlen;
while(total_subobj_len > 0) {
subobj_len = EXTRACT_16BITS(obj_tptr);
subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8;
af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF;
ND_PRINT((ndo, "%s Subobject Type: %s (%u), AF: %s (%u), length: %u",
ident,
tok2str(rsvp_obj_generalized_uni_values, "Unknown", subobj_type),
subobj_type,
tok2str(af_values, "Unknown", af), af,
subobj_len));
if(subobj_len == 0)
goto invalid;
switch(subobj_type) {
case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS:
case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS:
switch(af) {
case AFNUM_INET:
if (subobj_len < 8)
return -1;
ND_PRINT((ndo, "%s UNI IPv4 TNA address: %s",
ident, ipaddr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_INET6:
if (subobj_len < 20)
return -1;
ND_PRINT((ndo, "%s UNI IPv6 TNA address: %s",
ident, ip6addr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_NSAP:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
}
break;
case RSVP_GEN_UNI_SUBOBJ_DIVERSITY:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL:
if (subobj_len < 16) {
return -1;
}
ND_PRINT((ndo, "%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u",
ident,
((EXTRACT_32BITS(obj_tptr+4))>>31),
((EXTRACT_32BITS(obj_tptr+4))&0xFF),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr + 12)));
break;
case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL:
if (subobj_len < 8) {
return -1;
}
ND_PRINT((ndo, "%s Service level: %u",
ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24));
break;
default:
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
obj_tptr+=subobj_len;
obj_tlen+=subobj_len;
}
if (total_subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RSVP_HOP:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
if (obj_tlen)
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 16)));
obj_tlen-=20;
obj_tptr+=20;
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_TIME_VALUES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Refresh Period: %ums",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
/* those three objects do share the same semantics */
case RSVP_OBJ_SENDER_TSPEC:
case RSVP_OBJ_ADSPEC:
case RSVP_OBJ_FLOWSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Msg-Version: %u, length: %u",
ident,
(*obj_tptr & 0xf0) >> 4,
EXTRACT_16BITS(obj_tptr + 2) << 2));
obj_tptr+=4; /* get to the start of the service header */
obj_tlen-=4;
while (obj_tlen >= 4) {
intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2;
ND_PRINT((ndo, "%s Service Type: %s (%u), break bit %s set, Service length: %u",
ident,
tok2str(rsvp_intserv_service_type_values,"unknown",*(obj_tptr)),
*(obj_tptr),
(*(obj_tptr+1)&0x80) ? "" : "not",
intserv_serv_tlen));
obj_tptr+=4; /* get to the start of the parameter list */
obj_tlen-=4;
while (intserv_serv_tlen>=4) {
processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen);
if (processed == 0)
break;
obj_tlen-=processed;
intserv_serv_tlen-=processed;
obj_tptr+=processed;
}
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FILTERSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Flow Label: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_24BITS(obj_tptr + 17)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FASTREROUTE:
/* the differences between c-type 1 and 7 are minor */
obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1: /* new style */
if (obj_tlen < sizeof(struct rsvp_obj_frr_t))
return-1;
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;
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include Colors: 0x%08x, Exclude Colors: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_DETOUR:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
while(obj_tlen >= 8) {
ND_PRINT((ndo, "%s PLR-ID: %s, Avoid-Node-ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
ipaddr_string(ndo, obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CLASSTYPE:
case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
ND_PRINT((ndo, "%s CT: %u",
ident,
EXTRACT_32BITS(obj_tptr) & 0x7));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ERROR_SPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
error_code=*(obj_tptr+5);
error_value=EXTRACT_16BITS(obj_tptr+6);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr+4),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_diffserv_te_values,"unknown",error_value),
error_value));
break;
default:
ND_PRINT((ndo, ", Unknown Error Value (%u)", error_value));
break;
}
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
error_code=*(obj_tptr+17);
error_value=EXTRACT_16BITS(obj_tptr+18);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr+16),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
default:
break;
}
obj_tlen-=20;
obj_tptr+=20;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_PROPERTIES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
padbytes = EXTRACT_16BITS(obj_tptr+2);
ND_PRINT((ndo, "%s TLV count: %u, padding bytes: %u",
ident,
EXTRACT_16BITS(obj_tptr),
padbytes));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there is anything longer than the TLV header (2) */
while(obj_tlen >= 2 + padbytes) {
ND_PRINT((ndo, "%s %s TLV (0x%02x), length: %u", /* length includes header */
ident,
tok2str(rsvp_obj_prop_tlv_values,"unknown",*obj_tptr),
*obj_tptr,
*(obj_tptr + 1)));
if (obj_tlen < *(obj_tptr+1))
return-1;
if (*(obj_tptr+1) < 2)
return -1;
print_unknown_data(ndo, obj_tptr + 2, "\n\t\t", *(obj_tptr + 1) - 2);
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_MESSAGE_ID: /* fall through */
case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */
case RSVP_OBJ_MESSAGE_ID_LIST:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Flags [0x%02x], epoch: %u",
ident,
*obj_tptr,
EXTRACT_24BITS(obj_tptr + 1)));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there are no messages left */
while(obj_tlen >= 4) {
ND_PRINT((ndo, "%s Message-ID 0x%08x (%u)",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_INTEGRITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < sizeof(struct rsvp_obj_integrity_t))
return-1;
obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr;
ND_PRINT((ndo, "%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]",
ident,
EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4),
bittok2str(rsvp_obj_integrity_flag_values,
"none",
obj_ptr.rsvp_obj_integrity->flags)));
ND_PRINT((ndo, "%s MD5-sum 0x%08x%08x%08x%08x ",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12)));
sigcheck = signature_verify(ndo, pptr, plen,
obj_ptr.rsvp_obj_integrity->digest,
rsvp_clear_checksum,
rsvp_com_header);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
obj_tlen+=sizeof(struct rsvp_obj_integrity_t);
obj_tptr+=sizeof(struct rsvp_obj_integrity_t);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ADMIN_STATUS:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Flags [%s]", ident,
bittok2str(rsvp_obj_admin_status_flag_values, "none",
EXTRACT_32BITS(obj_tptr))));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_SET:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
action = (EXTRACT_16BITS(obj_tptr)>>8);
ND_PRINT((ndo, "%s Action: %s (%u), Label type: %u", ident,
tok2str(rsvp_obj_label_set_action_values, "Unknown", action),
action, ((EXTRACT_32BITS(obj_tptr) & 0x7F))));
switch (action) {
case LABEL_SET_INCLUSIVE_RANGE:
case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */
/* only a couple of subchannels are expected */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s Start range: %u, End range: %u", ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
obj_tlen-=4;
obj_tptr+=4;
subchannel = 1;
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Subchannel #%u: %u", ident, subchannel,
EXTRACT_32BITS(obj_tptr)));
obj_tptr+=4;
obj_tlen-=4;
subchannel++;
}
break;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_S2L:
switch (rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ipaddr_string(ndo, obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ip6addr_string(ndo, obj_tptr)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case RSVP_OBJ_SCOPE:
case RSVP_OBJ_POLICY_DATA:
case RSVP_OBJ_ACCEPT_LABEL_SET:
case RSVP_OBJ_PROTECTION:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); /* FIXME indentation */
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || hexdump == TRUE)
print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), "\n\t ", /* FIXME indentation */
rsvp_obj_len - sizeof(struct rsvp_object_header));
tptr+=rsvp_obj_len;
tlen-=rsvp_obj_len;
}
return 0;
invalid:
ND_PRINT((ndo, "%s", istr));
return -1;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return -1;
}
void
rsvp_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
const struct rsvp_common_header *rsvp_com_header;
const u_char *tptr;
u_short plen, tlen;
tptr=pptr;
rsvp_com_header = (const struct rsvp_common_header *)pptr;
ND_TCHECK(*rsvp_com_header);
/*
* Sanity checking of the header.
*/
if (RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags) != RSVP_VERSION) {
ND_PRINT((ndo, "ERROR: RSVP version %u packet not supported",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags)));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "RSVPv%u %s Message, length: %u",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags),
tok2str(rsvp_msg_type_values, "unknown (%u)",rsvp_com_header->msg_type),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
plen = tlen = EXTRACT_16BITS(rsvp_com_header->length);
ND_PRINT((ndo, "\n\tRSVPv%u %s Message (%u), Flags: [%s], length: %u, ttl: %u, checksum: 0x%04x",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags),
tok2str(rsvp_msg_type_values, "unknown, type: %u",rsvp_com_header->msg_type),
rsvp_com_header->msg_type,
bittok2str(rsvp_header_flag_values,"none",RSVP_EXTRACT_FLAGS(rsvp_com_header->version_flags)),
tlen,
rsvp_com_header->ttl,
EXTRACT_16BITS(rsvp_com_header->checksum)));
if (tlen < sizeof(const struct rsvp_common_header)) {
ND_PRINT((ndo, "ERROR: common header too short %u < %lu", tlen,
(unsigned long)sizeof(const struct rsvp_common_header)));
return;
}
tptr+=sizeof(const struct rsvp_common_header);
tlen-=sizeof(const struct rsvp_common_header);
switch(rsvp_com_header->msg_type) {
case RSVP_MSGTYPE_BUNDLE:
/*
* Process each submessage in the bundle message.
* Bundle messages may not contain bundle submessages, so we don't
* need to handle bundle submessages specially.
*/
while(tlen > 0) {
const u_char *subpptr=tptr, *subtptr;
u_short subplen, subtlen;
subtptr=subpptr;
rsvp_com_header = (const struct rsvp_common_header *)subpptr;
ND_TCHECK(*rsvp_com_header);
/*
* Sanity checking of the header.
*/
if (RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags) != RSVP_VERSION) {
ND_PRINT((ndo, "ERROR: RSVP version %u packet not supported",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags)));
return;
}
subplen = subtlen = EXTRACT_16BITS(rsvp_com_header->length);
ND_PRINT((ndo, "\n\t RSVPv%u %s Message (%u), Flags: [%s], length: %u, ttl: %u, checksum: 0x%04x",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags),
tok2str(rsvp_msg_type_values, "unknown, type: %u",rsvp_com_header->msg_type),
rsvp_com_header->msg_type,
bittok2str(rsvp_header_flag_values,"none",RSVP_EXTRACT_FLAGS(rsvp_com_header->version_flags)),
subtlen,
rsvp_com_header->ttl,
EXTRACT_16BITS(rsvp_com_header->checksum)));
if (subtlen < sizeof(const struct rsvp_common_header)) {
ND_PRINT((ndo, "ERROR: common header too short %u < %lu", subtlen,
(unsigned long)sizeof(const struct rsvp_common_header)));
return;
}
if (tlen < subtlen) {
ND_PRINT((ndo, "ERROR: common header too large %u > %u", subtlen,
tlen));
return;
}
subtptr+=sizeof(const struct rsvp_common_header);
subtlen-=sizeof(const struct rsvp_common_header);
/*
* Print all objects in the submessage.
*/
if (rsvp_obj_print(ndo, subpptr, subplen, subtptr, "\n\t ", subtlen, rsvp_com_header) == -1)
return;
tptr+=subtlen+sizeof(const struct rsvp_common_header);
tlen-=subtlen+sizeof(const struct rsvp_common_header);
}
break;
case RSVP_MSGTYPE_PATH:
case RSVP_MSGTYPE_RESV:
case RSVP_MSGTYPE_PATHERR:
case RSVP_MSGTYPE_RESVERR:
case RSVP_MSGTYPE_PATHTEAR:
case RSVP_MSGTYPE_RESVTEAR:
case RSVP_MSGTYPE_RESVCONF:
case RSVP_MSGTYPE_HELLO_OLD:
case RSVP_MSGTYPE_HELLO:
case RSVP_MSGTYPE_ACK:
case RSVP_MSGTYPE_SREFRESH:
/*
* Print all objects in the message.
*/
if (rsvp_obj_print(ndo, pptr, plen, tptr, "\n\t ", tlen, rsvp_com_header) == -1)
return;
break;
default:
print_unknown_data(ndo, tptr, "\n\t ", tlen);
break;
}
return;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2724_0 |
crossvul-cpp_data_good_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->fc, 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/good_467_0 |
crossvul-cpp_data_good_351_0 | /*
* asn1.c: ASN.1 decoding functions (DER)
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <assert.h>
#include <ctype.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "internal.h"
#include "asn1.h"
static int asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *len_left,
int choice, int depth);
static int asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1,
u8 **ptr, size_t *size, int depth);
static int asn1_write_element(sc_context_t *ctx, unsigned int tag,
const u8 * data, size_t datalen, u8 ** out, size_t * outlen);
static const char *tag2str(unsigned int tag)
{
static const char *tags[] = {
"EOC", "BOOLEAN", "INTEGER", "BIT STRING", "OCTET STRING", /* 0-4 */
"NULL", "OBJECT IDENTIFIER", "OBJECT DESCRIPTOR", "EXTERNAL", "REAL", /* 5-9 */
"ENUMERATED", "Universal 11", "UTF8String", "Universal 13", /* 10-13 */
"Universal 14", "Universal 15", "SEQUENCE", "SET", /* 15-17 */
"NumericString", "PrintableString", "T61String", /* 18-20 */
"VideotexString", "IA5String", "UTCTIME", "GENERALIZEDTIME", /* 21-24 */
"GraphicString", "VisibleString", "GeneralString", /* 25-27 */
"UniversalString", "Universal 29", "BMPString" /* 28-30 */
};
if (tag > 30)
return "(unknown)";
return tags[tag];
}
int sc_asn1_read_tag(const u8 ** buf, size_t buflen, unsigned int *cla_out,
unsigned int *tag_out, size_t *taglen)
{
const u8 *p = *buf;
size_t left = buflen, len;
unsigned int cla, tag, i;
if (left < 2)
return SC_ERROR_INVALID_ASN1_OBJECT;
*buf = NULL;
if (*p == 0xff || *p == 0) {
/* end of data reached */
*taglen = 0;
*tag_out = SC_ASN1_TAG_EOC;
return SC_SUCCESS;
}
/* parse tag byte(s)
* Resulted tag is presented by integer that has not to be
* confused with the 'tag number' part of ASN.1 tag.
*/
cla = (*p & SC_ASN1_TAG_CLASS) | (*p & SC_ASN1_TAG_CONSTRUCTED);
tag = *p & SC_ASN1_TAG_PRIMITIVE;
p++;
left--;
if (tag == SC_ASN1_TAG_PRIMITIVE) {
/* high tag number */
size_t n = SC_ASN1_TAGNUM_SIZE - 1;
/* search the last tag octet */
while (left-- != 0 && n != 0) {
tag <<= 8;
tag |= *p;
if ((*p++ & 0x80) == 0)
break;
n--;
}
if (left == 0 || n == 0)
/* either an invalid tag or it doesn't fit in
* unsigned int */
return SC_ERROR_INVALID_ASN1_OBJECT;
}
/* parse length byte(s) */
len = *p & 0x7f;
if (*p++ & 0x80) {
unsigned int a = 0;
left--;
if (len > 4 || len > left)
return SC_ERROR_INVALID_ASN1_OBJECT;
left -= len;
for (i = 0; i < len; i++) {
a <<= 8;
a |= *p;
p++;
}
len = a;
}
*cla_out = cla;
*tag_out = tag;
*taglen = len;
*buf = p;
if (len > left)
return SC_ERROR_ASN1_END_OF_CONTENTS;
return SC_SUCCESS;
}
void sc_format_asn1_entry(struct sc_asn1_entry *entry, void *parm, void *arg,
int set_present)
{
entry->parm = parm;
entry->arg = arg;
if (set_present)
entry->flags |= SC_ASN1_PRESENT;
}
void sc_copy_asn1_entry(const struct sc_asn1_entry *src,
struct sc_asn1_entry *dest)
{
while (src->name != NULL) {
*dest = *src;
dest++;
src++;
}
dest->name = NULL;
}
static void print_indent(size_t depth)
{
for (; depth > 0; depth--) {
putchar(' ');
}
}
static void print_hex(const u8 * buf, size_t buflen, size_t depth)
{
size_t lines_len = buflen * 5 + 128;
char *lines = malloc(lines_len);
char *line = lines;
if (buf == NULL || buflen == 0 || lines == NULL) {
free(lines);
return;
}
sc_hex_dump(buf, buflen, lines, lines_len);
while (*line != '\0') {
char *line_end = strchr(line, '\n');
ptrdiff_t width = line_end - line;
if (!line_end || width <= 1) {
/* don't print empty lines */
break;
}
if (buflen > 8) {
putchar('\n');
print_indent(depth);
} else {
printf(": ");
}
printf("%.*s", (int) width, line);
line = line_end + 1;
}
free(lines);
}
static void print_ascii(const u8 * buf, size_t buflen)
{
for (; 0 < buflen; buflen--, buf++) {
if (isprint(*buf))
printf("%c", *buf);
else
putchar('.');
}
}
static void sc_asn1_print_octet_string(const u8 * buf, size_t buflen, size_t depth)
{
print_hex(buf, buflen, depth);
}
static void sc_asn1_print_utf8string(const u8 * buf, size_t buflen)
{
/* FIXME UTF-8 is not ASCII */
print_ascii(buf, buflen);
}
static void sc_asn1_print_integer(const u8 * buf, size_t buflen)
{
size_t a = 0;
if (buflen > sizeof(a)) {
printf("0x%s", sc_dump_hex(buf, buflen));
} else {
size_t i;
for (i = 0; i < buflen; i++) {
a <<= 8;
a |= buf[i];
}
printf("%"SC_FORMAT_LEN_SIZE_T"u", a);
}
}
static void sc_asn1_print_boolean(const u8 * buf, size_t buflen)
{
if (!buflen)
return;
if (buf[0])
printf("true");
else
printf("false");
}
static void sc_asn1_print_bit_string(const u8 * buf, size_t buflen, size_t depth)
{
#ifndef _WIN32
long long a = 0;
#else
__int64 a = 0;
#endif
int r, i;
if (buflen > sizeof(a) + 1) {
print_hex(buf, buflen, depth);
} else {
r = sc_asn1_decode_bit_string(buf, buflen, &a, sizeof(a));
if (r < 0) {
printf("decode error");
return;
}
for (i = r - 1; i >= 0; i--) {
printf("%c", ((a >> i) & 1) ? '1' : '0');
}
}
}
#ifdef ENABLE_OPENSSL
#include <openssl/objects.h>
static void openssl_print_object_sn(const char *s)
{
ASN1_OBJECT *obj = OBJ_txt2obj(s, 0);
if (obj) {
int nid = OBJ_obj2nid(obj);
if (nid != NID_undef) {
printf(", %s", OBJ_nid2sn(nid));
}
ASN1_OBJECT_free(obj);
}
}
#else
static void openssl_print_object_sn(const char *s)
{
}
#endif
static void sc_asn1_print_object_id(const u8 * buf, size_t buflen)
{
struct sc_object_id oid;
const char *sbuf;
if (sc_asn1_decode_object_id(buf, buflen, &oid)) {
printf("decode error");
return;
}
sbuf = sc_dump_oid(&oid);
printf(" %s", sbuf);
openssl_print_object_sn(sbuf);
}
static void sc_asn1_print_utctime(const u8 * buf, size_t buflen)
{
if (buflen < 8) {
printf("Error in decoding.\n");
return;
}
print_ascii(buf, 2); /* YY */
putchar('-');
print_ascii(buf+2, 2); /* MM */
putchar('-');
print_ascii(buf+4, 2); /* DD */
putchar(' ');
print_ascii(buf+6, 2); /* hh */
buf += 8;
buflen -= 8;
if (buflen >= 2 && isdigit(buf[0]) && isdigit(buf[1])) {
putchar(':');
print_ascii(buf, 2); /* mm */
buf += 2;
buflen -= 2;
}
if (buflen >= 2 && isdigit(buf[0]) && isdigit(buf[1])) {
putchar(':');
print_ascii(buf, 2); /* ss */
buf += 2;
buflen -= 2;
}
if (buflen >= 4 && '.' == buf[0]) {
print_ascii(buf, 4); /* fff */
buf += 4;
buflen -= 4;
}
if (buflen >= 1 && 'Z' == buf[0]) {
printf(" UTC");
} else if (buflen >= 5 && ('-' == buf[0] || '+' == buf[0])) {
putchar(' ');
print_ascii(buf, 3); /* +/-hh */
putchar(':');
print_ascii(buf+3, 2); /* mm */
}
}
static void sc_asn1_print_generalizedtime(const u8 * buf, size_t buflen)
{
if (buflen < 8) {
printf("Error in decoding.\n");
return;
}
print_ascii(buf, 2);
sc_asn1_print_utctime(buf + 2, buflen - 2);
}
static void print_tags_recursive(const u8 * buf0, const u8 * buf,
size_t buflen, size_t depth)
{
int r;
size_t i;
size_t bytesleft = buflen;
const char *classes[4] = {
"Universal",
"Application",
"Context",
"Private"
};
const u8 *p = buf;
while (bytesleft >= 2) {
unsigned int cla = 0, tag = 0, hlen;
const u8 *tagp = p;
size_t len;
r = sc_asn1_read_tag(&tagp, bytesleft, &cla, &tag, &len);
if (r != SC_SUCCESS || tagp == NULL) {
printf("Error in decoding.\n");
return;
}
hlen = tagp - p;
if (cla == 0 && tag == 0) {
printf("Zero tag, finishing\n");
break;
}
print_indent(depth);
/* let i be the length of the tag in bytes */
for (i = 1; i < sizeof tag - 1; i++) {
if (!(tag >> 8*i))
break;
}
printf("%02X", cla<<(i-1)*8 | tag);
if ((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_UNIVERSAL) {
printf(" %s", tag2str(tag));
} else {
printf(" %s %-2u",
classes[cla >> 6],
i == 1 ? tag & SC_ASN1_TAG_PRIMITIVE : tag & (((unsigned int) ~0) >> (i + 1) * 8));
}
if (!((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_UNIVERSAL
&& tag == SC_ASN1_TAG_NULL && len == 0)) {
printf(" (%"SC_FORMAT_LEN_SIZE_T"u byte%s)",
len,
len != 1 ? "s" : "");
}
if (len + hlen > bytesleft) {
printf(" Illegal length!\n");
return;
}
p += hlen + len;
bytesleft -= hlen + len;
if (cla & SC_ASN1_TAG_CONSTRUCTED) {
putchar('\n');
print_tags_recursive(buf0, tagp, len, depth + 2*i + 1);
continue;
}
switch (tag) {
case SC_ASN1_TAG_BIT_STRING:
printf(": ");
sc_asn1_print_bit_string(tagp, len, depth + 2*i + 1);
break;
case SC_ASN1_TAG_OCTET_STRING:
sc_asn1_print_octet_string(tagp, len, depth + 2*i + 1);
break;
case SC_ASN1_TAG_OBJECT:
printf(": ");
sc_asn1_print_object_id(tagp, len);
break;
case SC_ASN1_TAG_INTEGER:
case SC_ASN1_TAG_ENUMERATED:
printf(": ");
sc_asn1_print_integer(tagp, len);
break;
case SC_ASN1_TAG_IA5STRING:
case SC_ASN1_TAG_PRINTABLESTRING:
case SC_ASN1_TAG_T61STRING:
case SC_ASN1_TAG_UTF8STRING:
printf(": ");
sc_asn1_print_utf8string(tagp, len);
break;
case SC_ASN1_TAG_BOOLEAN:
printf(": ");
sc_asn1_print_boolean(tagp, len);
break;
case SC_ASN1_GENERALIZEDTIME:
printf(": ");
sc_asn1_print_generalizedtime(tagp, len);
break;
case SC_ASN1_UTCTIME:
printf(": ");
sc_asn1_print_utctime(tagp, len);
break;
}
if ((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_APPLICATION) {
print_hex(tagp, len, depth + 2*i + 1);
}
if ((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_CONTEXT) {
print_hex(tagp, len, depth + 2*i + 1);
}
putchar('\n');
}
}
void sc_asn1_print_tags(const u8 * buf, size_t buflen)
{
print_tags_recursive(buf, buf, buflen, 0);
}
const u8 *sc_asn1_find_tag(sc_context_t *ctx, const u8 * buf,
size_t buflen, unsigned int tag_in, size_t *taglen_in)
{
size_t left = buflen, taglen;
const u8 *p = buf;
*taglen_in = 0;
while (left >= 2) {
unsigned int cla = 0, tag, mask = 0xff00;
buf = p;
/* read a tag */
if (sc_asn1_read_tag(&p, left, &cla, &tag, &taglen) != SC_SUCCESS
|| p == NULL)
return NULL;
left -= (p - buf);
/* we need to shift the class byte to the leftmost
* byte of the tag */
while ((tag & mask) != 0) {
cla <<= 8;
mask <<= 8;
}
/* compare the read tag with the given tag */
if ((tag | cla) == tag_in) {
/* we have a match => return length and value part */
if (taglen > left)
return NULL;
*taglen_in = taglen;
return p;
}
/* otherwise continue reading tags */
left -= taglen;
p += taglen;
}
return NULL;
}
const u8 *sc_asn1_skip_tag(sc_context_t *ctx, const u8 ** buf, size_t *buflen,
unsigned int tag_in, size_t *taglen_out)
{
const u8 *p = *buf;
size_t len = *buflen, taglen;
unsigned int cla = 0, tag;
if (sc_asn1_read_tag((const u8 **) &p, len, &cla, &tag, &taglen) != SC_SUCCESS
|| p == NULL)
return NULL;
switch (cla & 0xC0) {
case SC_ASN1_TAG_UNIVERSAL:
if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_UNI)
return NULL;
break;
case SC_ASN1_TAG_APPLICATION:
if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_APP)
return NULL;
break;
case SC_ASN1_TAG_CONTEXT:
if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_CTX)
return NULL;
break;
case SC_ASN1_TAG_PRIVATE:
if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_PRV)
return NULL;
break;
}
if (cla & SC_ASN1_TAG_CONSTRUCTED) {
if ((tag_in & SC_ASN1_CONS) == 0)
return NULL;
} else
if (tag_in & SC_ASN1_CONS)
return NULL;
if ((tag_in & SC_ASN1_TAG_MASK) != tag)
return NULL;
len -= (p - *buf); /* header size */
if (taglen > len) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"too long ASN.1 object (size %"SC_FORMAT_LEN_SIZE_T"u while only %"SC_FORMAT_LEN_SIZE_T"u available)\n",
taglen, len);
return NULL;
}
*buflen -= (p - *buf) + taglen;
*buf = p + taglen; /* point to next tag */
*taglen_out = taglen;
return p;
}
const u8 *sc_asn1_verify_tag(sc_context_t *ctx, const u8 * buf, size_t buflen,
unsigned int tag_in, size_t *taglen_out)
{
return sc_asn1_skip_tag(ctx, &buf, &buflen, tag_in, taglen_out);
}
static int decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf,
size_t outlen, int invert)
{
const u8 *in = inbuf;
u8 *out = (u8 *) outbuf;
int zero_bits = *in & 0x07;
size_t octets_left = inlen - 1;
int i, count = 0;
memset(outbuf, 0, outlen);
in++;
if (outlen < octets_left)
return SC_ERROR_BUFFER_TOO_SMALL;
if (inlen < 1)
return SC_ERROR_INVALID_ASN1_OBJECT;
while (octets_left) {
/* 1st octet of input: ABCDEFGH, where A is the MSB */
/* 1st octet of output: HGFEDCBA, where A is the LSB */
/* first bit in bit string is the LSB in first resulting octet */
int bits_to_go;
*out = 0;
if (octets_left == 1)
bits_to_go = 8 - zero_bits;
else
bits_to_go = 8;
if (invert)
for (i = 0; i < bits_to_go; i++) {
*out |= ((*in >> (7 - i)) & 1) << i;
}
else {
*out = *in;
}
out++;
in++;
octets_left--;
count++;
}
return (count * 8) - zero_bits;
}
int sc_asn1_decode_bit_string(const u8 * inbuf, size_t inlen,
void *outbuf, size_t outlen)
{
return decode_bit_string(inbuf, inlen, outbuf, outlen, 1);
}
int sc_asn1_decode_bit_string_ni(const u8 * inbuf, size_t inlen,
void *outbuf, size_t outlen)
{
return decode_bit_string(inbuf, inlen, outbuf, outlen, 0);
}
static int encode_bit_string(const u8 * inbuf, size_t bits_left, u8 **outbuf,
size_t *outlen, int invert)
{
const u8 *in = inbuf;
u8 *out;
size_t bytes;
int skipped = 0;
bytes = (bits_left + 7)/8 + 1;
*outbuf = out = malloc(bytes);
if (out == NULL)
return SC_ERROR_OUT_OF_MEMORY;
*outlen = bytes;
out += 1;
while (bits_left) {
int i, bits_to_go = 8;
*out = 0;
if (bits_left < 8) {
bits_to_go = bits_left;
skipped = 8 - bits_left;
}
if (invert) {
for (i = 0; i < bits_to_go; i++)
*out |= ((*in >> i) & 1) << (7 - i);
} else {
*out = *in;
if (bits_left < 8)
return SC_ERROR_NOT_SUPPORTED; /* FIXME */
}
bits_left -= bits_to_go;
out++, in++;
}
out = *outbuf;
out[0] = skipped;
return 0;
}
/*
* Bitfields are just bit strings, stored in an unsigned int
* (taking endianness into account)
*/
static int decode_bit_field(const u8 * inbuf, size_t inlen, void *outbuf, size_t outlen)
{
u8 data[sizeof(unsigned int)];
unsigned int field = 0;
int i, n;
if (outlen != sizeof(data))
return SC_ERROR_BUFFER_TOO_SMALL;
n = decode_bit_string(inbuf, inlen, data, sizeof(data), 1);
if (n < 0)
return n;
for (i = 0; i < n; i += 8) {
field |= (data[i/8] << i);
}
memcpy(outbuf, &field, outlen);
return 0;
}
static int encode_bit_field(const u8 *inbuf, size_t inlen,
u8 **outbuf, size_t *outlen)
{
u8 data[sizeof(unsigned int)];
unsigned int field = 0;
size_t i, bits;
if (inlen != sizeof(data))
return SC_ERROR_BUFFER_TOO_SMALL;
/* count the bits */
memcpy(&field, inbuf, inlen);
for (bits = 0; field; bits++)
field >>= 1;
memcpy(&field, inbuf, inlen);
for (i = 0; i < bits; i += 8)
data[i/8] = field >> i;
return encode_bit_string(data, bits, outbuf, outlen, 1);
}
int sc_asn1_decode_integer(const u8 * inbuf, size_t inlen, int *out)
{
int a = 0;
size_t i;
if (inlen > sizeof(int) || inlen == 0)
return SC_ERROR_INVALID_ASN1_OBJECT;
if (inbuf[0] & 0x80)
a = -1;
for (i = 0; i < inlen; i++) {
a <<= 8;
a |= *inbuf++;
}
*out = a;
return 0;
}
static int asn1_encode_integer(int in, u8 ** obj, size_t * objsize)
{
int i = sizeof(in) * 8, skip_zero, skip_sign;
u8 *p, b;
if (in < 0)
{
skip_sign = 1;
skip_zero= 0;
}
else
{
skip_sign = 0;
skip_zero= 1;
}
*obj = p = malloc(sizeof(in)+1);
if (*obj == NULL)
return SC_ERROR_OUT_OF_MEMORY;
do {
i -= 8;
b = in >> i;
if (skip_sign)
{
if (b != 0xff)
skip_sign = 0;
if (b & 0x80)
{
*p = b;
if (0xff == b)
continue;
}
else
{
p++;
skip_sign = 0;
}
}
if (b == 0 && skip_zero)
continue;
if (skip_zero) {
skip_zero = 0;
/* prepend 0x00 if MSb is 1 and integer positive */
if ((b & 0x80) != 0 && in > 0)
*p++ = 0;
}
*p++ = b;
} while (i > 0);
if (skip_sign)
p++;
*objsize = p - *obj;
if (*objsize == 0) {
*objsize = 1;
(*obj)[0] = 0;
}
return 0;
}
int
sc_asn1_decode_object_id(const u8 *inbuf, size_t inlen, struct sc_object_id *id)
{
int a;
const u8 *p = inbuf;
int *octet;
if (inlen == 0 || inbuf == NULL || id == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
sc_init_oid(id);
octet = id->value;
a = *p;
*octet++ = a / 40;
*octet++ = a % 40;
inlen--;
while (inlen) {
p++;
a = *p & 0x7F;
inlen--;
while (inlen && *p & 0x80) {
p++;
a <<= 7;
a |= *p & 0x7F;
inlen--;
}
*octet++ = a;
if (octet - id->value >= SC_MAX_OBJECT_ID_OCTETS) {
sc_init_oid(id);
return SC_ERROR_INVALID_ASN1_OBJECT;
}
};
return 0;
}
int
sc_asn1_encode_object_id(u8 **buf, size_t *buflen, const struct sc_object_id *id)
{
u8 temp[SC_MAX_OBJECT_ID_OCTETS*5], *p = temp;
int i;
if (!buflen || !id)
return SC_ERROR_INVALID_ARGUMENTS;
/* an OID must have at least two components */
if (id->value[0] == -1 || id->value[1] == -1)
return SC_ERROR_INVALID_ARGUMENTS;
for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) {
unsigned int k, shift;
if (id->value[i] == -1)
break;
k = id->value[i];
switch (i) {
case 0:
if (k > 2)
return SC_ERROR_INVALID_ARGUMENTS;
*p = k * 40;
break;
case 1:
if (k > 39)
return SC_ERROR_INVALID_ARGUMENTS;
*p++ += k;
break;
default:
shift = 28;
while (shift && (k >> shift) == 0)
shift -= 7;
while (shift) {
*p++ = 0x80 | ((k >> shift) & 0x7f);
shift -= 7;
}
*p++ = k & 0x7F;
break;
}
}
*buflen = p - temp;
if (buf) {
*buf = malloc(*buflen);
if (!*buf)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(*buf, temp, *buflen);
}
return 0;
}
static int sc_asn1_decode_utf8string(const u8 *inbuf, size_t inlen,
u8 *out, size_t *outlen)
{
if (inlen+1 > *outlen)
return SC_ERROR_BUFFER_TOO_SMALL;
*outlen = inlen+1;
memcpy(out, inbuf, inlen);
out[inlen] = 0;
return 0;
}
int sc_asn1_put_tag(unsigned int tag, const u8 * data, size_t datalen, u8 * out, size_t outlen, u8 **ptr)
{
size_t c = 0;
size_t tag_len;
size_t ii;
u8 *p = out;
u8 tag_char[4] = {0, 0, 0, 0};
/* Check tag */
if (tag == 0 || tag > 0xFFFFFFFF) {
/* A tag of 0x00 is not valid and at most 4-byte tag names are supported. */
return SC_ERROR_INVALID_DATA;
}
for (tag_len = 0; tag; tag >>= 8) {
/* Note: tag char will be reversed order. */
tag_char[tag_len++] = tag & 0xFF;
}
if (tag_len > 1) {
if ((tag_char[tag_len - 1] & SC_ASN1_TAG_PRIMITIVE) != SC_ASN1_TAG_ESCAPE_MARKER) {
/* First byte is not escape marker. */
return SC_ERROR_INVALID_DATA;
}
for (ii = 1; ii < tag_len - 1; ii++) {
if ((tag_char[ii] & 0x80) != 0x80) {
/* MS bit is not 'one'. */
return SC_ERROR_INVALID_DATA;
}
}
if ((tag_char[0] & 0x80) != 0x00) {
/* MS bit of the last byte is not 'zero'. */
return SC_ERROR_INVALID_DATA;
}
}
/* Calculate the number of additional bytes necessary to encode the length. */
/* c+1 is the size of the length field. */
if (datalen > 127) {
c = 1;
while (datalen >> (c << 3))
c++;
}
if (outlen == 0 || out == NULL) {
/* Caller only asks for the length that would be written. */
return tag_len + (c+1) + datalen;
}
/* We will write the tag, so check the length. */
if (outlen < tag_len + (c+1) + datalen)
return SC_ERROR_BUFFER_TOO_SMALL;
for (ii=0;ii<tag_len;ii++)
*p++ = tag_char[tag_len - ii - 1];
if (c > 0) {
*p++ = 0x80 | c;
while (c--)
*p++ = (datalen >> (c << 3)) & 0xFF;
}
else {
*p++ = datalen & 0x7F;
}
if(data && datalen > 0) {
memcpy(p, data, datalen);
p += datalen;
}
if (ptr != NULL)
*ptr = p;
return 0;
}
int sc_asn1_write_element(sc_context_t *ctx, unsigned int tag,
const u8 * data, size_t datalen, u8 ** out, size_t * outlen)
{
return asn1_write_element(ctx, tag, data, datalen, out, outlen);
}
static int asn1_write_element(sc_context_t *ctx, unsigned int tag,
const u8 * data, size_t datalen, u8 ** out, size_t * outlen)
{
unsigned char t;
unsigned char *buf, *p;
int c = 0;
unsigned short_tag;
unsigned char tag_char[3] = {0, 0, 0};
size_t tag_len, ii;
short_tag = tag & SC_ASN1_TAG_MASK;
for (tag_len = 0; short_tag >> (8 * tag_len); tag_len++)
tag_char[tag_len] = (short_tag >> (8 * tag_len)) & 0xFF;
if (!tag_len)
tag_len = 1;
if (tag_len > 1) {
if ((tag_char[tag_len - 1] & SC_ASN1_TAG_PRIMITIVE) != SC_ASN1_TAG_ESCAPE_MARKER)
SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "First byte of the long tag is not 'escape marker'");
for (ii = 1; ii < tag_len - 1; ii++)
if (!(tag_char[ii] & 0x80))
SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "MS bit expected to be 'one'");
if (tag_char[0] & 0x80)
SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "MS bit of the last byte expected to be 'zero'");
}
t = tag_char[tag_len - 1] & 0x1F;
switch (tag & SC_ASN1_CLASS_MASK) {
case SC_ASN1_UNI:
break;
case SC_ASN1_APP:
t |= SC_ASN1_TAG_APPLICATION;
break;
case SC_ASN1_CTX:
t |= SC_ASN1_TAG_CONTEXT;
break;
case SC_ASN1_PRV:
t |= SC_ASN1_TAG_PRIVATE;
break;
}
if (tag & SC_ASN1_CONS)
t |= SC_ASN1_TAG_CONSTRUCTED;
if (datalen > 127) {
c = 1;
while (datalen >> (c << 3))
c++;
}
*outlen = tag_len + 1 + c + datalen;
buf = malloc(*outlen);
if (buf == NULL)
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_OUT_OF_MEMORY);
*out = p = buf;
*p++ = t;
for (ii=1;ii<tag_len;ii++)
*p++ = tag_char[tag_len - ii - 1];
if (c) {
*p++ = 0x80 | c;
while (c--)
*p++ = (datalen >> (c << 3)) & 0xFF;
}
else {
*p++ = datalen & 0x7F;
}
memcpy(p, data, datalen);
return SC_SUCCESS;
}
static const struct sc_asn1_entry c_asn1_path_ext[3] = {
{ "aid", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x0F, 0, NULL, NULL },
{ "path", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_OCTET_STRING, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static const struct sc_asn1_entry c_asn1_path[5] = {
{ "path", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "index", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "length", SC_ASN1_INTEGER, SC_ASN1_CTX | 0, SC_ASN1_OPTIONAL, NULL, NULL },
/* For some multi-applications PKCS#15 card the ODF records can hold the references to
* the xDF files and objects placed elsewhere then under the application DF of the ODF itself.
* In such a case the 'path' ASN1 data includes also the ID of the target application (AID).
* This path extension do not make a part of PKCS#15 standard.
*/
{ "pathExtended", SC_ASN1_STRUCT, SC_ASN1_CTX | 1 | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static int asn1_decode_path(sc_context_t *ctx, const u8 *in, size_t len,
sc_path_t *path, int depth)
{
int idx, count, r;
struct sc_asn1_entry asn1_path_ext[3], asn1_path[5];
unsigned char path_value[SC_MAX_PATH_SIZE], aid_value[SC_MAX_AID_SIZE];
size_t path_len = sizeof(path_value), aid_len = sizeof(aid_value);
memset(path, 0, sizeof(struct sc_path));
sc_copy_asn1_entry(c_asn1_path_ext, asn1_path_ext);
sc_copy_asn1_entry(c_asn1_path, asn1_path);
sc_format_asn1_entry(asn1_path_ext + 0, aid_value, &aid_len, 0);
sc_format_asn1_entry(asn1_path_ext + 1, path_value, &path_len, 0);
sc_format_asn1_entry(asn1_path + 0, path_value, &path_len, 0);
sc_format_asn1_entry(asn1_path + 1, &idx, NULL, 0);
sc_format_asn1_entry(asn1_path + 2, &count, NULL, 0);
sc_format_asn1_entry(asn1_path + 3, asn1_path_ext, NULL, 0);
r = asn1_decode(ctx, asn1_path, in, len, NULL, NULL, 0, depth + 1);
if (r)
return r;
if (asn1_path[3].flags & SC_ASN1_PRESENT) {
/* extended path present: set 'path' and 'aid' */
memcpy(path->aid.value, aid_value, aid_len);
path->aid.len = aid_len;
memcpy(path->value, path_value, path_len);
path->len = path_len;
}
else if (asn1_path[0].flags & SC_ASN1_PRESENT) {
/* path present: set 'path' */
memcpy(path->value, path_value, path_len);
path->len = path_len;
}
else {
/* failed if both 'path' and 'pathExtended' are absent */
return SC_ERROR_ASN1_OBJECT_NOT_FOUND;
}
if (path->len == 2)
path->type = SC_PATH_TYPE_FILE_ID;
else if (path->aid.len && path->len > 2)
path->type = SC_PATH_TYPE_FROM_CURRENT;
else
path->type = SC_PATH_TYPE_PATH;
if ((asn1_path[1].flags & SC_ASN1_PRESENT) && (asn1_path[2].flags & SC_ASN1_PRESENT)) {
path->index = idx;
path->count = count;
}
else {
path->index = 0;
path->count = -1;
}
return SC_SUCCESS;
}
static int asn1_encode_path(sc_context_t *ctx, const sc_path_t *path,
u8 **buf, size_t *bufsize, int depth, unsigned int parent_flags)
{
int r;
struct sc_asn1_entry asn1_path[5];
sc_path_t tpath = *path;
sc_copy_asn1_entry(c_asn1_path, asn1_path);
sc_format_asn1_entry(asn1_path + 0, (void *) &tpath.value, (void *) &tpath.len, 1);
asn1_path[0].flags |= parent_flags;
if (path->count > 0) {
sc_format_asn1_entry(asn1_path + 1, (void *) &tpath.index, NULL, 1);
sc_format_asn1_entry(asn1_path + 2, (void *) &tpath.count, NULL, 1);
}
r = asn1_encode(ctx, asn1_path, buf, bufsize, depth + 1);
return r;
}
static const struct sc_asn1_entry c_asn1_se[2] = {
{ "seInfo", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static const struct sc_asn1_entry c_asn1_se_info[4] = {
{ "se", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, 0, NULL, NULL },
{ "owner",SC_ASN1_OBJECT, SC_ASN1_TAG_OBJECT, SC_ASN1_OPTIONAL, NULL, NULL },
{ "aid", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static int asn1_decode_se_info(sc_context_t *ctx, const u8 *obj, size_t objlen,
sc_pkcs15_sec_env_info_t ***se, size_t *num, int depth)
{
struct sc_pkcs15_sec_env_info **ses;
const unsigned char *ptr = obj;
size_t idx, ptrlen = objlen;
int ret;
ses = calloc(SC_MAX_SE_NUM, sizeof(sc_pkcs15_sec_env_info_t *));
if (ses == NULL)
return SC_ERROR_OUT_OF_MEMORY;
for (idx=0; idx < SC_MAX_SE_NUM && ptrlen; ) {
struct sc_asn1_entry asn1_se[2];
struct sc_asn1_entry asn1_se_info[4];
struct sc_pkcs15_sec_env_info si;
sc_copy_asn1_entry(c_asn1_se, asn1_se);
sc_copy_asn1_entry(c_asn1_se_info, asn1_se_info);
si.aid.len = sizeof(si.aid.value);
sc_format_asn1_entry(asn1_se_info + 0, &si.se, NULL, 0);
sc_format_asn1_entry(asn1_se_info + 1, &si.owner, NULL, 0);
sc_format_asn1_entry(asn1_se_info + 2, &si.aid.value, &si.aid.len, 0);
sc_format_asn1_entry(asn1_se + 0, asn1_se_info, NULL, 0);
ret = asn1_decode(ctx, asn1_se, ptr, ptrlen, &ptr, &ptrlen, 0, depth+1);
if (ret != SC_SUCCESS)
goto err;
if (!(asn1_se_info[1].flags & SC_ASN1_PRESENT))
sc_init_oid(&si.owner);
ses[idx] = calloc(1, sizeof(sc_pkcs15_sec_env_info_t));
if (ses[idx] == NULL) {
ret = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
memcpy(ses[idx], &si, sizeof(struct sc_pkcs15_sec_env_info));
idx++;
}
*se = ses;
*num = idx;
ret = SC_SUCCESS;
err:
if (ret != SC_SUCCESS) {
size_t i;
for (i = 0; i < idx; i++)
if (ses[i])
free(ses[i]);
free(ses);
}
return ret;
}
static int asn1_encode_se_info(sc_context_t *ctx,
struct sc_pkcs15_sec_env_info **se, size_t se_num,
unsigned char **buf, size_t *bufsize, int depth)
{
unsigned char *ptr = NULL, *out = NULL, *p;
size_t ptrlen = 0, outlen = 0, idx;
int ret;
for (idx=0; idx < se_num; idx++) {
struct sc_asn1_entry asn1_se[2];
struct sc_asn1_entry asn1_se_info[4];
sc_copy_asn1_entry(c_asn1_se, asn1_se);
sc_copy_asn1_entry(c_asn1_se_info, asn1_se_info);
sc_format_asn1_entry(asn1_se_info + 0, &se[idx]->se, NULL, 1);
if (sc_valid_oid(&se[idx]->owner))
sc_format_asn1_entry(asn1_se_info + 1, &se[idx]->owner, NULL, 1);
if (se[idx]->aid.len)
sc_format_asn1_entry(asn1_se_info + 2, &se[idx]->aid.value, &se[idx]->aid.len, 1);
sc_format_asn1_entry(asn1_se + 0, asn1_se_info, NULL, 1);
ret = sc_asn1_encode(ctx, asn1_se, &ptr, &ptrlen);
if (ret != SC_SUCCESS)
goto err;
p = (unsigned char *) realloc(out, outlen + ptrlen);
if (!p) {
ret = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
out = p;
memcpy(out + outlen, ptr, ptrlen);
outlen += ptrlen;
free(ptr);
ptr = NULL;
ptrlen = 0;
}
*buf = out;
*bufsize = outlen;
ret = SC_SUCCESS;
err:
if (ret != SC_SUCCESS && out != NULL)
free(out);
return ret;
}
/* TODO: According to specification type of 'SecurityCondition' is 'CHOICE'.
* Do it at least for SC_ASN1_PKCS15_ID(authId), SC_ASN1_STRUCT(authReference) and NULL(always). */
static const struct sc_asn1_entry c_asn1_access_control_rule[3] = {
{ "accessMode", SC_ASN1_BIT_FIELD, SC_ASN1_TAG_BIT_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "securityCondition", SC_ASN1_PKCS15_ID, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
/*
* in src/libopensc/pkcs15.h SC_PKCS15_MAX_ACCESS_RULES defined as 8
*/
static const struct sc_asn1_entry c_asn1_access_control_rules[SC_PKCS15_MAX_ACCESS_RULES + 1] = {
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static const struct sc_asn1_entry c_asn1_com_obj_attr[6] = {
{ "label", SC_ASN1_UTF8STRING, SC_ASN1_TAG_UTF8STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "flags", SC_ASN1_BIT_FIELD, SC_ASN1_TAG_BIT_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "authId", SC_ASN1_PKCS15_ID, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "userConsent", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRules", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static const struct sc_asn1_entry c_asn1_p15_obj[5] = {
{ "commonObjectAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ "classAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ "subClassAttributes", SC_ASN1_STRUCT, SC_ASN1_CTX | 0 | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "typeAttributes", SC_ASN1_STRUCT, SC_ASN1_CTX | 1 | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static int asn1_decode_p15_object(sc_context_t *ctx, const u8 *in,
size_t len, struct sc_asn1_pkcs15_object *obj,
int depth)
{
struct sc_pkcs15_object *p15_obj = obj->p15_obj;
struct sc_asn1_entry asn1_c_attr[6], asn1_p15_obj[5];
struct sc_asn1_entry asn1_ac_rules[SC_PKCS15_MAX_ACCESS_RULES + 1], asn1_ac_rule[SC_PKCS15_MAX_ACCESS_RULES][3];
size_t flags_len = sizeof(p15_obj->flags);
size_t label_len = sizeof(p15_obj->label);
size_t access_mode_len = sizeof(p15_obj->access_rules[0].access_mode);
int r, ii;
for (ii=0; ii<SC_PKCS15_MAX_ACCESS_RULES; ii++)
sc_copy_asn1_entry(c_asn1_access_control_rule, asn1_ac_rule[ii]);
sc_copy_asn1_entry(c_asn1_access_control_rules, asn1_ac_rules);
sc_copy_asn1_entry(c_asn1_com_obj_attr, asn1_c_attr);
sc_copy_asn1_entry(c_asn1_p15_obj, asn1_p15_obj);
sc_format_asn1_entry(asn1_c_attr + 0, p15_obj->label, &label_len, 0);
sc_format_asn1_entry(asn1_c_attr + 1, &p15_obj->flags, &flags_len, 0);
sc_format_asn1_entry(asn1_c_attr + 2, &p15_obj->auth_id, NULL, 0);
sc_format_asn1_entry(asn1_c_attr + 3, &p15_obj->user_consent, NULL, 0);
for (ii=0; ii<SC_PKCS15_MAX_ACCESS_RULES; ii++) {
sc_format_asn1_entry(asn1_ac_rule[ii] + 0, &p15_obj->access_rules[ii].access_mode, &access_mode_len, 0);
sc_format_asn1_entry(asn1_ac_rule[ii] + 1, &p15_obj->access_rules[ii].auth_id, NULL, 0);
sc_format_asn1_entry(asn1_ac_rules + ii, asn1_ac_rule[ii], NULL, 0);
}
sc_format_asn1_entry(asn1_c_attr + 4, asn1_ac_rules, NULL, 0);
sc_format_asn1_entry(asn1_p15_obj + 0, asn1_c_attr, NULL, 0);
sc_format_asn1_entry(asn1_p15_obj + 1, obj->asn1_class_attr, NULL, 0);
sc_format_asn1_entry(asn1_p15_obj + 2, obj->asn1_subclass_attr, NULL, 0);
sc_format_asn1_entry(asn1_p15_obj + 3, obj->asn1_type_attr, NULL, 0);
r = asn1_decode(ctx, asn1_p15_obj, in, len, NULL, NULL, 0, depth + 1);
return r;
}
static int asn1_encode_p15_object(sc_context_t *ctx, const struct sc_asn1_pkcs15_object *obj,
u8 **buf, size_t *bufsize, int depth)
{
struct sc_pkcs15_object p15_obj = *obj->p15_obj;
struct sc_asn1_entry asn1_c_attr[6], asn1_p15_obj[5];
struct sc_asn1_entry asn1_ac_rules[SC_PKCS15_MAX_ACCESS_RULES + 1], asn1_ac_rule[SC_PKCS15_MAX_ACCESS_RULES][3];
size_t label_len = strlen(p15_obj.label);
size_t flags_len;
size_t access_mode_len;
int r, ii;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "encode p15 obj(type:0x%X,access_mode:0x%X)", p15_obj.type, p15_obj.access_rules[0].access_mode);
if (p15_obj.access_rules[0].access_mode) {
for (ii=0; ii<SC_PKCS15_MAX_ACCESS_RULES; ii++) {
sc_copy_asn1_entry(c_asn1_access_control_rule, asn1_ac_rule[ii]);
if (p15_obj.access_rules[ii].auth_id.len == 0) {
asn1_ac_rule[ii][1].type = SC_ASN1_NULL;
asn1_ac_rule[ii][1].tag = SC_ASN1_TAG_NULL;
}
}
sc_copy_asn1_entry(c_asn1_access_control_rules, asn1_ac_rules);
}
sc_copy_asn1_entry(c_asn1_com_obj_attr, asn1_c_attr);
sc_copy_asn1_entry(c_asn1_p15_obj, asn1_p15_obj);
if (label_len != 0)
sc_format_asn1_entry(asn1_c_attr + 0, (void *) p15_obj.label, &label_len, 1);
if (p15_obj.flags) {
flags_len = sizeof(p15_obj.flags);
sc_format_asn1_entry(asn1_c_attr + 1, (void *) &p15_obj.flags, &flags_len, 1);
}
if (p15_obj.auth_id.len)
sc_format_asn1_entry(asn1_c_attr + 2, (void *) &p15_obj.auth_id, NULL, 1);
if (p15_obj.user_consent)
sc_format_asn1_entry(asn1_c_attr + 3, (void *) &p15_obj.user_consent, NULL, 1);
if (p15_obj.access_rules[0].access_mode) {
for (ii=0; p15_obj.access_rules[ii].access_mode; ii++) {
access_mode_len = sizeof(p15_obj.access_rules[ii].access_mode);
sc_format_asn1_entry(asn1_ac_rule[ii] + 0, (void *) &p15_obj.access_rules[ii].access_mode, &access_mode_len, 1);
sc_format_asn1_entry(asn1_ac_rule[ii] + 1, (void *) &p15_obj.access_rules[ii].auth_id, NULL, 1);
sc_format_asn1_entry(asn1_ac_rules + ii, asn1_ac_rule[ii], NULL, 1);
}
sc_format_asn1_entry(asn1_c_attr + 4, asn1_ac_rules, NULL, 1);
}
sc_format_asn1_entry(asn1_p15_obj + 0, asn1_c_attr, NULL, 1);
sc_format_asn1_entry(asn1_p15_obj + 1, obj->asn1_class_attr, NULL, 1);
if (obj->asn1_subclass_attr != NULL && obj->asn1_subclass_attr->name)
sc_format_asn1_entry(asn1_p15_obj + 2, obj->asn1_subclass_attr, NULL, 1);
sc_format_asn1_entry(asn1_p15_obj + 3, obj->asn1_type_attr, NULL, 1);
r = asn1_encode(ctx, asn1_p15_obj, buf, bufsize, depth + 1);
return r;
}
static int asn1_decode_entry(sc_context_t *ctx,struct sc_asn1_entry *entry,
const u8 *obj, size_t objlen, int depth)
{
void *parm = entry->parm;
int (*callback_func)(sc_context_t *nctx, void *arg, const u8 *nobj,
size_t nobjlen, int ndepth);
size_t *len = (size_t *) entry->arg;
int r = 0;
callback_func = parm;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s', raw data:%s%s\n",
depth, depth, "", entry->name,
sc_dump_hex(obj, objlen > 16 ? 16 : objlen),
objlen > 16 ? "..." : "");
switch (entry->type) {
case SC_ASN1_STRUCT:
if (parm != NULL)
r = asn1_decode(ctx, (struct sc_asn1_entry *) parm, obj,
objlen, NULL, NULL, 0, depth + 1);
break;
case SC_ASN1_NULL:
break;
case SC_ASN1_BOOLEAN:
if (parm != NULL) {
if (objlen != 1) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"invalid ASN.1 object length: %"SC_FORMAT_LEN_SIZE_T"u\n",
objlen);
r = SC_ERROR_INVALID_ASN1_OBJECT;
} else
*((int *) parm) = obj[0] ? 1 : 0;
}
break;
case SC_ASN1_INTEGER:
case SC_ASN1_ENUMERATED:
if (parm != NULL) {
r = sc_asn1_decode_integer(obj, objlen, (int *) entry->parm);
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s' returned %d\n", depth, depth, "",
entry->name, *((int *) entry->parm));
}
break;
case SC_ASN1_BIT_STRING_NI:
case SC_ASN1_BIT_STRING:
if (parm != NULL) {
int invert = entry->type == SC_ASN1_BIT_STRING ? 1 : 0;
assert(len != NULL);
if (objlen < 1) {
r = SC_ERROR_INVALID_ASN1_OBJECT;
break;
}
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen-1);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
*len = objlen-1;
parm = *buf;
}
r = decode_bit_string(obj, objlen, (u8 *) parm, *len, invert);
if (r >= 0) {
*len = r;
r = 0;
}
}
break;
case SC_ASN1_BIT_FIELD:
if (parm != NULL)
r = decode_bit_field(obj, objlen, (u8 *) parm, *len);
break;
case SC_ASN1_OCTET_STRING:
if (parm != NULL) {
size_t c;
assert(len != NULL);
/* Strip off padding zero */
if ((entry->flags & SC_ASN1_UNSIGNED)
&& obj[0] == 0x00 && objlen > 1) {
objlen--;
obj++;
}
/* Allocate buffer if needed */
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
c = *len = objlen;
parm = *buf;
} else
c = objlen > *len ? *len : objlen;
memcpy(parm, obj, c);
*len = c;
}
break;
case SC_ASN1_GENERALIZEDTIME:
if (parm != NULL) {
size_t c;
assert(len != NULL);
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
c = *len = objlen;
parm = *buf;
} else
c = objlen > *len ? *len : objlen;
memcpy(parm, obj, c);
*len = c;
}
break;
case SC_ASN1_OBJECT:
if (parm != NULL)
r = sc_asn1_decode_object_id(obj, objlen, (struct sc_object_id *) parm);
break;
case SC_ASN1_PRINTABLESTRING:
case SC_ASN1_UTF8STRING:
if (parm != NULL) {
assert(len != NULL);
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen+1);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
*len = objlen+1;
parm = *buf;
}
r = sc_asn1_decode_utf8string(obj, objlen, (u8 *) parm, len);
if (entry->flags & SC_ASN1_ALLOC) {
*len -= 1;
}
}
break;
case SC_ASN1_PATH:
if (entry->parm != NULL)
r = asn1_decode_path(ctx, obj, objlen, (sc_path_t *) parm, depth);
break;
case SC_ASN1_PKCS15_ID:
if (entry->parm != NULL) {
struct sc_pkcs15_id *id = (struct sc_pkcs15_id *) parm;
size_t c = objlen > sizeof(id->value) ? sizeof(id->value) : objlen;
memcpy(id->value, obj, c);
id->len = c;
}
break;
case SC_ASN1_PKCS15_OBJECT:
if (entry->parm != NULL)
r = asn1_decode_p15_object(ctx, obj, objlen, (struct sc_asn1_pkcs15_object *) parm, depth);
break;
case SC_ASN1_ALGORITHM_ID:
if (entry->parm != NULL)
r = sc_asn1_decode_algorithm_id(ctx, obj, objlen, (struct sc_algorithm_id *) parm, depth);
break;
case SC_ASN1_SE_INFO:
if (entry->parm != NULL)
r = asn1_decode_se_info(ctx, obj, objlen, (sc_pkcs15_sec_env_info_t ***)entry->parm, len, depth);
break;
case SC_ASN1_CALLBACK:
if (entry->parm != NULL)
r = callback_func(ctx, entry->arg, obj, objlen, depth);
break;
default:
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 type: %d\n", entry->type);
return SC_ERROR_INVALID_ASN1_OBJECT;
}
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "decoding of ASN.1 object '%s' failed: %s\n", entry->name,
sc_strerror(r));
return r;
}
entry->flags |= SC_ASN1_PRESENT;
return 0;
}
static int asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *len_left,
int choice, int depth)
{
int r, idx = 0;
const u8 *p = in, *obj;
struct sc_asn1_entry *entry = asn1;
size_t left = len, objlen;
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"%*.*scalled, left=%"SC_FORMAT_LEN_SIZE_T"u, depth %d%s\n",
depth, depth, "", left, depth, choice ? ", choice" : "");
if (!p)
return SC_ERROR_ASN1_OBJECT_NOT_FOUND;
if (left < 2) {
while (asn1->name && (asn1->flags & SC_ASN1_OPTIONAL))
asn1++;
/* If all elements were optional, there's nothing
* to complain about */
if (asn1->name == NULL)
return 0;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "End of ASN.1 stream, "
"non-optional field \"%s\" not found\n",
asn1->name);
return SC_ERROR_ASN1_OBJECT_NOT_FOUND;
}
if (p[0] == 0 || p[0] == 0xFF || len == 0)
return SC_ERROR_ASN1_END_OF_CONTENTS;
for (idx = 0; asn1[idx].name != NULL; idx++) {
entry = &asn1[idx];
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "Looking for '%s', tag 0x%x%s%s\n",
entry->name, entry->tag, choice? ", CHOICE" : "",
(entry->flags & SC_ASN1_OPTIONAL)? ", OPTIONAL": "");
/* Special case CHOICE has no tag */
if (entry->type == SC_ASN1_CHOICE) {
r = asn1_decode(ctx,
(struct sc_asn1_entry *) entry->parm,
p, left, &p, &left, 1, depth + 1);
if (r >= 0)
r = 0;
goto decode_ok;
}
obj = sc_asn1_skip_tag(ctx, &p, &left, entry->tag, &objlen);
if (obj == NULL) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "'%s' not present\n", entry->name);
if (choice)
continue;
if (entry->flags & SC_ASN1_OPTIONAL)
continue;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "mandatory ASN.1 object '%s' not found\n", entry->name);
if (left) {
u8 line[128], *linep = line;
size_t i;
line[0] = 0;
for (i = 0; i < 10 && i < left; i++) {
sprintf((char *) linep, "%02X ", p[i]);
linep += 3;
}
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "next tag: %s\n", line);
}
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_ASN1_OBJECT_NOT_FOUND);
}
r = asn1_decode_entry(ctx, entry, obj, objlen, depth);
decode_ok:
if (r)
return r;
if (choice)
break;
}
if (choice && asn1[idx].name == NULL) /* No match */
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_ASN1_OBJECT_NOT_FOUND);
if (newp != NULL)
*newp = p;
if (len_left != NULL)
*len_left = left;
if (choice)
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, idx);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, 0);
}
int sc_asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *len_left)
{
return asn1_decode(ctx, asn1, in, len, newp, len_left, 0, 0);
}
int sc_asn1_decode_choice(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *len_left)
{
return asn1_decode(ctx, asn1, in, len, newp, len_left, 1, 0);
}
static int asn1_encode_entry(sc_context_t *ctx, const struct sc_asn1_entry *entry,
u8 **obj, size_t *objlen, int depth)
{
void *parm = entry->parm;
int (*callback_func)(sc_context_t *nctx, void *arg, u8 **nobj,
size_t *nobjlen, int ndepth);
const size_t *len = (const size_t *) entry->arg;
int r = 0;
u8 * buf = NULL;
size_t buflen = 0;
callback_func = parm;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sencoding '%s'%s\n",
depth, depth, "", entry->name,
(entry->flags & SC_ASN1_PRESENT)? "" : " (not present)");
if (!(entry->flags & SC_ASN1_PRESENT))
goto no_object;
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"%*.*stype=%d, tag=0x%02x, parm=%p, len=%"SC_FORMAT_LEN_SIZE_T"u\n",
depth, depth, "", entry->type, entry->tag, parm,
len ? *len : 0);
if (entry->type == SC_ASN1_CHOICE) {
const struct sc_asn1_entry *list, *choice = NULL;
list = (const struct sc_asn1_entry *) parm;
while (list->name != NULL) {
if (list->flags & SC_ASN1_PRESENT) {
if (choice) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"ASN.1 problem: more than "
"one CHOICE when encoding %s: "
"%s and %s both present\n",
entry->name,
choice->name,
list->name);
return SC_ERROR_INVALID_ASN1_OBJECT;
}
choice = list;
}
list++;
}
if (choice == NULL)
goto no_object;
return asn1_encode_entry(ctx, choice, obj, objlen, depth + 1);
}
if (entry->type != SC_ASN1_NULL && parm == NULL) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "unexpected parm == NULL\n");
return SC_ERROR_INVALID_ASN1_OBJECT;
}
switch (entry->type) {
case SC_ASN1_STRUCT:
r = asn1_encode(ctx, (const struct sc_asn1_entry *) parm, &buf,
&buflen, depth + 1);
break;
case SC_ASN1_NULL:
buf = NULL;
buflen = 0;
break;
case SC_ASN1_BOOLEAN:
buf = malloc(1);
if (buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
buf[0] = *((int *) parm) ? 0xFF : 0;
buflen = 1;
break;
case SC_ASN1_INTEGER:
case SC_ASN1_ENUMERATED:
r = asn1_encode_integer(*((int *) entry->parm), &buf, &buflen);
break;
case SC_ASN1_BIT_STRING_NI:
case SC_ASN1_BIT_STRING:
if (len != NULL) {
if (entry->type == SC_ASN1_BIT_STRING)
r = encode_bit_string((const u8 *) parm, *len, &buf, &buflen, 1);
else
r = encode_bit_string((const u8 *) parm, *len, &buf, &buflen, 0);
} else {
r = SC_ERROR_INVALID_ARGUMENTS;
}
break;
case SC_ASN1_BIT_FIELD:
if (len != NULL) {
r = encode_bit_field((const u8 *) parm, *len, &buf, &buflen);
} else {
r = SC_ERROR_INVALID_ARGUMENTS;
}
break;
case SC_ASN1_PRINTABLESTRING:
case SC_ASN1_OCTET_STRING:
case SC_ASN1_UTF8STRING:
if (len != NULL) {
buf = malloc(*len + 1);
if (buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
buflen = 0;
/* If the integer is supposed to be unsigned, insert
* a padding byte if the MSB is one */
if ((entry->flags & SC_ASN1_UNSIGNED)
&& (((u8 *) parm)[0] & 0x80)) {
buf[buflen++] = 0x00;
}
memcpy(buf + buflen, parm, *len);
buflen += *len;
} else {
r = SC_ERROR_INVALID_ARGUMENTS;
}
break;
case SC_ASN1_GENERALIZEDTIME:
if (len != NULL) {
buf = malloc(*len);
if (buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
memcpy(buf, parm, *len);
buflen = *len;
} else {
r = SC_ERROR_INVALID_ARGUMENTS;
}
break;
case SC_ASN1_OBJECT:
r = sc_asn1_encode_object_id(&buf, &buflen, (struct sc_object_id *) parm);
break;
case SC_ASN1_PATH:
r = asn1_encode_path(ctx, (const sc_path_t *) parm, &buf, &buflen, depth, entry->flags);
break;
case SC_ASN1_PKCS15_ID:
{
const struct sc_pkcs15_id *id = (const struct sc_pkcs15_id *) parm;
buf = malloc(id->len);
if (buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
memcpy(buf, id->value, id->len);
buflen = id->len;
}
break;
case SC_ASN1_PKCS15_OBJECT:
r = asn1_encode_p15_object(ctx, (const struct sc_asn1_pkcs15_object *) parm, &buf, &buflen, depth);
break;
case SC_ASN1_ALGORITHM_ID:
r = sc_asn1_encode_algorithm_id(ctx, &buf, &buflen, (const struct sc_algorithm_id *) parm, depth);
break;
case SC_ASN1_SE_INFO:
if (!len)
return SC_ERROR_INVALID_ASN1_OBJECT;
r = asn1_encode_se_info(ctx, (struct sc_pkcs15_sec_env_info **)parm, *len, &buf, &buflen, depth);
break;
case SC_ASN1_CALLBACK:
r = callback_func(ctx, entry->arg, &buf, &buflen, depth);
break;
default:
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 type: %d\n", entry->type);
return SC_ERROR_INVALID_ASN1_OBJECT;
}
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "encoding of ASN.1 object '%s' failed: %s\n", entry->name,
sc_strerror(r));
if (buf)
free(buf);
return r;
}
/* Treatment of OPTIONAL elements:
* - if the encoding has 0 length, and the element is OPTIONAL,
* we don't write anything (unless it's an ASN1 NULL and the
* SC_ASN1_PRESENT flag is set).
* - if the encoding has 0 length, but the element is non-OPTIONAL,
* constructed, we write a empty element (e.g. a SEQUENCE of
* length 0). In case of an ASN1 NULL just write the tag and
* length (i.e. 0x05,0x00).
* - any other empty objects are considered bogus
*/
no_object:
if (!buflen && entry->flags & SC_ASN1_OPTIONAL && !(entry->flags & SC_ASN1_PRESENT)) {
/* This happens when we try to encode e.g. the
* subClassAttributes, which may be empty */
*obj = NULL;
*objlen = 0;
r = 0;
} else if (!buflen && (entry->flags & SC_ASN1_EMPTY_ALLOWED)) {
*obj = NULL;
*objlen = 0;
r = asn1_write_element(ctx, entry->tag, buf, buflen, obj, objlen);
if (r)
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "error writing ASN.1 tag and length: %s\n", sc_strerror(r));
} else if (buflen || entry->type == SC_ASN1_NULL || entry->tag & SC_ASN1_CONS) {
r = asn1_write_element(ctx, entry->tag, buf, buflen, obj, objlen);
if (r)
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "error writing ASN.1 tag and length: %s\n",
sc_strerror(r));
} else if (!(entry->flags & SC_ASN1_PRESENT)) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "cannot encode non-optional ASN.1 object: not given by caller\n");
r = SC_ERROR_INVALID_ASN1_OBJECT;
} else {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "cannot encode empty non-optional ASN.1 object\n");
r = SC_ERROR_INVALID_ASN1_OBJECT;
}
if (buf)
free(buf);
if (r >= 0)
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"%*.*slength of encoded item=%"SC_FORMAT_LEN_SIZE_T"u\n",
depth, depth, "", *objlen);
return r;
}
static int asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1,
u8 **ptr, size_t *size, int depth)
{
int r, idx = 0;
u8 *obj = NULL, *buf = NULL, *tmp;
size_t total = 0, objsize;
for (idx = 0; asn1[idx].name != NULL; idx++) {
r = asn1_encode_entry(ctx, &asn1[idx], &obj, &objsize, depth);
if (r) {
if (obj)
free(obj);
if (buf)
free(buf);
return r;
}
/* in case of an empty (optional) element continue with
* the next asn1 element */
if (!objsize)
continue;
tmp = (u8 *) realloc(buf, total + objsize);
if (!tmp) {
if (obj)
free(obj);
if (buf)
free(buf);
return SC_ERROR_OUT_OF_MEMORY;
}
buf = tmp;
memcpy(buf + total, obj, objsize);
free(obj);
obj = NULL;
total += objsize;
}
*ptr = buf;
*size = total;
return 0;
}
int sc_asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1,
u8 **ptr, size_t *size)
{
return asn1_encode(ctx, asn1, ptr, size, 0);
}
int _sc_asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1,
u8 **ptr, size_t *size, int depth)
{
return asn1_encode(ctx, asn1, ptr, size, depth);
}
int
_sc_asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *left,
int choice, int depth)
{
return asn1_decode(ctx, asn1, in, len, newp, left, choice, depth);
}
int
sc_der_copy(sc_pkcs15_der_t *dst, const sc_pkcs15_der_t *src)
{
if (!dst)
return SC_ERROR_INVALID_ARGUMENTS;
memset(dst, 0, sizeof(*dst));
if (src->len) {
dst->value = malloc(src->len);
if (!dst->value)
return SC_ERROR_OUT_OF_MEMORY;
dst->len = src->len;
memcpy(dst->value, src->value, src->len);
}
return SC_SUCCESS;
}
int
sc_encode_oid (struct sc_context *ctx, struct sc_object_id *id,
unsigned char **out, size_t *size)
{
static const struct sc_asn1_entry c_asn1_object_id[2] = {
{ "oid", SC_ASN1_OBJECT, SC_ASN1_TAG_OBJECT, SC_ASN1_ALLOC, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
struct sc_asn1_entry asn1_object_id[2];
int rv;
sc_copy_asn1_entry(c_asn1_object_id, asn1_object_id);
sc_format_asn1_entry(asn1_object_id + 0, id, NULL, 1);
rv = _sc_asn1_encode(ctx, asn1_object_id, out, size, 1);
LOG_TEST_RET(ctx, rv, "Cannot encode object ID");
return SC_SUCCESS;
}
#define C_ASN1_SIG_VALUE_SIZE 2
static struct sc_asn1_entry c_asn1_sig_value[C_ASN1_SIG_VALUE_SIZE] = {
{ "ECDSA-Sig-Value", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE 3
static struct sc_asn1_entry c_asn1_sig_value_coefficients[C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE] = {
{ "r", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_INTEGER, SC_ASN1_ALLOC|SC_ASN1_UNSIGNED, NULL, NULL },
{ "s", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_INTEGER, SC_ASN1_ALLOC|SC_ASN1_UNSIGNED, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
int
sc_asn1_sig_value_rs_to_sequence(struct sc_context *ctx, unsigned char *in, size_t inlen,
unsigned char **buf, size_t *buflen)
{
struct sc_asn1_entry asn1_sig_value[C_ASN1_SIG_VALUE_SIZE];
struct sc_asn1_entry asn1_sig_value_coefficients[C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE];
unsigned char *r = in, *s = in + inlen/2;
size_t r_len = inlen/2, s_len = inlen/2;
int rv;
LOG_FUNC_CALLED(ctx);
/* R/S are filled up with zeroes, we do not want that in sequence format */
while(r_len > 1 && *r == 0x00) {
r++;
r_len--;
}
while(s_len > 1 && *s == 0x00) {
s++;
s_len--;
}
sc_copy_asn1_entry(c_asn1_sig_value, asn1_sig_value);
sc_format_asn1_entry(asn1_sig_value + 0, asn1_sig_value_coefficients, NULL, 1);
sc_copy_asn1_entry(c_asn1_sig_value_coefficients, asn1_sig_value_coefficients);
sc_format_asn1_entry(asn1_sig_value_coefficients + 0, r, &r_len, 1);
sc_format_asn1_entry(asn1_sig_value_coefficients + 1, s, &s_len, 1);
rv = sc_asn1_encode(ctx, asn1_sig_value, buf, buflen);
LOG_TEST_RET(ctx, rv, "ASN.1 encoding ECDSA-SIg-Value failed");
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
int
sc_asn1_sig_value_sequence_to_rs(struct sc_context *ctx, unsigned char *in, size_t inlen,
unsigned char *buf, size_t buflen)
{
struct sc_asn1_entry asn1_sig_value[C_ASN1_SIG_VALUE_SIZE];
struct sc_asn1_entry asn1_sig_value_coefficients[C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE];
unsigned char *r, *s;
size_t r_len, s_len, halflen = buflen/2;
int rv;
LOG_FUNC_CALLED(ctx);
if (!buf || !buflen)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_copy_asn1_entry(c_asn1_sig_value, asn1_sig_value);
sc_format_asn1_entry(asn1_sig_value + 0, asn1_sig_value_coefficients, NULL, 0);
sc_copy_asn1_entry(c_asn1_sig_value_coefficients, asn1_sig_value_coefficients);
sc_format_asn1_entry(asn1_sig_value_coefficients + 0, &r, &r_len, 0);
sc_format_asn1_entry(asn1_sig_value_coefficients + 1, &s, &s_len, 0);
rv = sc_asn1_decode(ctx, asn1_sig_value, in, inlen, NULL, NULL);
LOG_TEST_RET(ctx, rv, "ASN.1 decoding ECDSA-Sig-Value failed");
if (halflen < r_len || halflen < s_len) {
rv = SC_ERROR_BUFFER_TOO_SMALL;
goto done;
}
memset(buf, 0, buflen);
memcpy(buf + (halflen - r_len), r, r_len);
memcpy(buf + (buflen - s_len), s, s_len);
sc_log(ctx, "r(%"SC_FORMAT_LEN_SIZE_T"u): %s", halflen,
sc_dump_hex(buf, halflen));
sc_log(ctx, "s(%"SC_FORMAT_LEN_SIZE_T"u): %s", halflen,
sc_dump_hex(buf + halflen, halflen));
rv = SC_SUCCESS;
done:
free(r);
free(s);
LOG_FUNC_RETURN(ctx, rv);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_351_0 |
crossvul-cpp_data_bad_706_0 | /*-
* Copyright (c) 2011 Michihiro NAKAJIMA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "archive_platform.h"
__FBSDID("$FreeBSD$");
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_BZLIB_H
#include <bzlib.h>
#endif
#ifdef HAVE_LZMA_H
#include <lzma.h>
#endif
#ifdef HAVE_ZLIB_H
#include <zlib.h>
#endif
#include "archive.h"
#include "archive_entry.h"
#include "archive_entry_locale.h"
#include "archive_ppmd7_private.h"
#include "archive_private.h"
#include "archive_read_private.h"
#include "archive_endian.h"
#ifndef HAVE_ZLIB_H
#include "archive_crc32.h"
#endif
#define _7ZIP_SIGNATURE "7z\xBC\xAF\x27\x1C"
#define SFX_MIN_ADDR 0x27000
#define SFX_MAX_ADDR 0x60000
/*
* Codec ID
*/
#define _7Z_COPY 0
#define _7Z_LZMA 0x030101
#define _7Z_LZMA2 0x21
#define _7Z_DEFLATE 0x040108
#define _7Z_BZ2 0x040202
#define _7Z_PPMD 0x030401
#define _7Z_DELTA 0x03
#define _7Z_CRYPTO_MAIN_ZIP 0x06F10101 /* Main Zip crypto algo */
#define _7Z_CRYPTO_RAR_29 0x06F10303 /* Rar29 AES-128 + (modified SHA-1) */
#define _7Z_CRYPTO_AES_256_SHA_256 0x06F10701 /* AES-256 + SHA-256 */
#define _7Z_X86 0x03030103
#define _7Z_X86_BCJ2 0x0303011B
#define _7Z_POWERPC 0x03030205
#define _7Z_IA64 0x03030401
#define _7Z_ARM 0x03030501
#define _7Z_ARMTHUMB 0x03030701
#define _7Z_SPARC 0x03030805
/*
* 7-Zip header property IDs.
*/
#define kEnd 0x00
#define kHeader 0x01
#define kArchiveProperties 0x02
#define kAdditionalStreamsInfo 0x03
#define kMainStreamsInfo 0x04
#define kFilesInfo 0x05
#define kPackInfo 0x06
#define kUnPackInfo 0x07
#define kSubStreamsInfo 0x08
#define kSize 0x09
#define kCRC 0x0A
#define kFolder 0x0B
#define kCodersUnPackSize 0x0C
#define kNumUnPackStream 0x0D
#define kEmptyStream 0x0E
#define kEmptyFile 0x0F
#define kAnti 0x10
#define kName 0x11
#define kCTime 0x12
#define kATime 0x13
#define kMTime 0x14
#define kAttributes 0x15
#define kEncodedHeader 0x17
#define kDummy 0x19
struct _7z_digests {
unsigned char *defineds;
uint32_t *digests;
};
struct _7z_folder {
uint64_t numCoders;
struct _7z_coder {
unsigned long codec;
uint64_t numInStreams;
uint64_t numOutStreams;
uint64_t propertiesSize;
unsigned char *properties;
} *coders;
uint64_t numBindPairs;
struct {
uint64_t inIndex;
uint64_t outIndex;
} *bindPairs;
uint64_t numPackedStreams;
uint64_t *packedStreams;
uint64_t numInStreams;
uint64_t numOutStreams;
uint64_t *unPackSize;
unsigned char digest_defined;
uint32_t digest;
uint64_t numUnpackStreams;
uint32_t packIndex;
/* Unoperated bytes. */
uint64_t skipped_bytes;
};
struct _7z_coders_info {
uint64_t numFolders;
struct _7z_folder *folders;
uint64_t dataStreamIndex;
};
struct _7z_pack_info {
uint64_t pos;
uint64_t numPackStreams;
uint64_t *sizes;
struct _7z_digests digest;
/* Calculated from pos and numPackStreams. */
uint64_t *positions;
};
struct _7z_substream_info {
size_t unpack_streams;
uint64_t *unpackSizes;
unsigned char *digestsDefined;
uint32_t *digests;
};
struct _7z_stream_info {
struct _7z_pack_info pi;
struct _7z_coders_info ci;
struct _7z_substream_info ss;
};
struct _7z_header_info {
uint64_t dataIndex;
unsigned char *emptyStreamBools;
unsigned char *emptyFileBools;
unsigned char *antiBools;
unsigned char *attrBools;
};
struct _7zip_entry {
size_t name_len;
unsigned char *utf16name;
#if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG)
const wchar_t *wname;
#endif
uint32_t folderIndex;
uint32_t ssIndex;
unsigned flg;
#define MTIME_IS_SET (1<<0)
#define ATIME_IS_SET (1<<1)
#define CTIME_IS_SET (1<<2)
#define CRC32_IS_SET (1<<3)
#define HAS_STREAM (1<<4)
time_t mtime;
time_t atime;
time_t ctime;
long mtime_ns;
long atime_ns;
long ctime_ns;
uint32_t mode;
uint32_t attr;
};
struct _7zip {
/* Structural information about the archive. */
struct _7z_stream_info si;
int header_is_being_read;
int header_is_encoded;
uint64_t header_bytes_remaining;
unsigned long header_crc32;
/* Header offset to check that reading points of the file contents
* will not exceed the header. */
uint64_t header_offset;
/* Base offset of the archive file for a seek in case reading SFX. */
uint64_t seek_base;
/* List of entries */
size_t entries_remaining;
uint64_t numFiles;
struct _7zip_entry *entries;
struct _7zip_entry *entry;
unsigned char *entry_names;
/* entry_bytes_remaining is the number of bytes we expect. */
int64_t entry_offset;
uint64_t entry_bytes_remaining;
/* Running CRC32 of the decompressed data */
unsigned long entry_crc32;
/* Flags to mark progress of decompression. */
char end_of_entry;
/* Uncompressed buffer control. */
#define UBUFF_SIZE (64 * 1024)
unsigned char *uncompressed_buffer;
unsigned char *uncompressed_buffer_pointer;
size_t uncompressed_buffer_size;
size_t uncompressed_buffer_bytes_remaining;
/* Offset of the compressed data. */
int64_t stream_offset;
/*
* Decompressing control data.
*/
unsigned folder_index;
uint64_t folder_outbytes_remaining;
unsigned pack_stream_index;
unsigned pack_stream_remaining;
uint64_t pack_stream_inbytes_remaining;
size_t pack_stream_bytes_unconsumed;
/* The codec information of a folder. */
unsigned long codec;
unsigned long codec2;
/*
* Decompressor controllers.
*/
/* Decoding LZMA1 and LZMA2 data. */
#ifdef HAVE_LZMA_H
lzma_stream lzstream;
int lzstream_valid;
#endif
/* Decoding bzip2 data. */
#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
bz_stream bzstream;
int bzstream_valid;
#endif
/* Decoding deflate data. */
#ifdef HAVE_ZLIB_H
z_stream stream;
int stream_valid;
#endif
/* Decoding PPMd data. */
int ppmd7_stat;
CPpmd7 ppmd7_context;
CPpmd7z_RangeDec range_dec;
IByteIn bytein;
struct {
const unsigned char *next_in;
int64_t avail_in;
int64_t total_in;
unsigned char *next_out;
int64_t avail_out;
int64_t total_out;
int overconsumed;
} ppstream;
int ppmd7_valid;
/* Decoding BCJ and BCJ2 data. */
uint32_t bcj_state;
size_t odd_bcj_size;
unsigned char odd_bcj[4];
/* Decoding BCJ data. */
size_t bcj_prevPosT;
uint32_t bcj_prevMask;
uint32_t bcj_ip;
/* Decoding BCJ2 data. */
size_t main_stream_bytes_remaining;
unsigned char *sub_stream_buff[3];
size_t sub_stream_size[3];
size_t sub_stream_bytes_remaining[3];
unsigned char *tmp_stream_buff;
size_t tmp_stream_buff_size;
size_t tmp_stream_bytes_avail;
size_t tmp_stream_bytes_remaining;
#ifdef _LZMA_PROB32
#define CProb uint32_t
#else
#define CProb uint16_t
#endif
CProb bcj2_p[256 + 2];
uint8_t bcj2_prevByte;
uint32_t bcj2_range;
uint32_t bcj2_code;
uint64_t bcj2_outPos;
/* Filename character-set conversion data. */
struct archive_string_conv *sconv;
char format_name[64];
/* Custom value that is non-zero if this archive contains encrypted entries. */
int has_encrypted_entries;
};
/* Maximum entry size. This limitation prevents reading intentional
* corrupted 7-zip files on assuming there are not so many entries in
* the files. */
#define UMAX_ENTRY ARCHIVE_LITERAL_ULL(100000000)
static int archive_read_format_7zip_has_encrypted_entries(struct archive_read *);
static int archive_read_support_format_7zip_capabilities(struct archive_read *a);
static int archive_read_format_7zip_bid(struct archive_read *, int);
static int archive_read_format_7zip_cleanup(struct archive_read *);
static int archive_read_format_7zip_read_data(struct archive_read *,
const void **, size_t *, int64_t *);
static int archive_read_format_7zip_read_data_skip(struct archive_read *);
static int archive_read_format_7zip_read_header(struct archive_read *,
struct archive_entry *);
static int check_7zip_header_in_sfx(const char *);
static unsigned long decode_codec_id(const unsigned char *, size_t);
static int decode_encoded_header_info(struct archive_read *,
struct _7z_stream_info *);
static int decompress(struct archive_read *, struct _7zip *,
void *, size_t *, const void *, size_t *);
static ssize_t extract_pack_stream(struct archive_read *, size_t);
static void fileTimeToUtc(uint64_t, time_t *, long *);
static uint64_t folder_uncompressed_size(struct _7z_folder *);
static void free_CodersInfo(struct _7z_coders_info *);
static void free_Digest(struct _7z_digests *);
static void free_Folder(struct _7z_folder *);
static void free_Header(struct _7z_header_info *);
static void free_PackInfo(struct _7z_pack_info *);
static void free_StreamsInfo(struct _7z_stream_info *);
static void free_SubStreamsInfo(struct _7z_substream_info *);
static int free_decompression(struct archive_read *, struct _7zip *);
static ssize_t get_uncompressed_data(struct archive_read *, const void **,
size_t, size_t);
static const unsigned char * header_bytes(struct archive_read *, size_t);
static int init_decompression(struct archive_read *, struct _7zip *,
const struct _7z_coder *, const struct _7z_coder *);
static int parse_7zip_uint64(struct archive_read *, uint64_t *);
static int read_Bools(struct archive_read *, unsigned char *, size_t);
static int read_CodersInfo(struct archive_read *,
struct _7z_coders_info *);
static int read_Digests(struct archive_read *, struct _7z_digests *,
size_t);
static int read_Folder(struct archive_read *, struct _7z_folder *);
static int read_Header(struct archive_read *, struct _7z_header_info *,
int);
static int read_PackInfo(struct archive_read *, struct _7z_pack_info *);
static int read_StreamsInfo(struct archive_read *,
struct _7z_stream_info *);
static int read_SubStreamsInfo(struct archive_read *,
struct _7z_substream_info *, struct _7z_folder *, size_t);
static int read_Times(struct archive_read *, struct _7z_header_info *,
int);
static void read_consume(struct archive_read *);
static ssize_t read_stream(struct archive_read *, const void **, size_t,
size_t);
static int seek_pack(struct archive_read *);
static int64_t skip_stream(struct archive_read *, size_t);
static int skip_sfx(struct archive_read *, ssize_t);
static int slurp_central_directory(struct archive_read *, struct _7zip *,
struct _7z_header_info *);
static int setup_decode_folder(struct archive_read *, struct _7z_folder *,
int);
static void x86_Init(struct _7zip *);
static size_t x86_Convert(struct _7zip *, uint8_t *, size_t);
static ssize_t Bcj2_Decode(struct _7zip *, uint8_t *, size_t);
int
archive_read_support_format_7zip(struct archive *_a)
{
struct archive_read *a = (struct archive_read *)_a;
struct _7zip *zip;
int r;
archive_check_magic(_a, ARCHIVE_READ_MAGIC,
ARCHIVE_STATE_NEW, "archive_read_support_format_7zip");
zip = calloc(1, sizeof(*zip));
if (zip == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate 7zip data");
return (ARCHIVE_FATAL);
}
/*
* Until enough data has been read, we cannot tell about
* any encrypted entries yet.
*/
zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
r = __archive_read_register_format(a,
zip,
"7zip",
archive_read_format_7zip_bid,
NULL,
archive_read_format_7zip_read_header,
archive_read_format_7zip_read_data,
archive_read_format_7zip_read_data_skip,
NULL,
archive_read_format_7zip_cleanup,
archive_read_support_format_7zip_capabilities,
archive_read_format_7zip_has_encrypted_entries);
if (r != ARCHIVE_OK)
free(zip);
return (ARCHIVE_OK);
}
static int
archive_read_support_format_7zip_capabilities(struct archive_read * a)
{
(void)a; /* UNUSED */
return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
}
static int
archive_read_format_7zip_has_encrypted_entries(struct archive_read *_a)
{
if (_a && _a->format) {
struct _7zip * zip = (struct _7zip *)_a->format->data;
if (zip) {
return zip->has_encrypted_entries;
}
}
return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
}
static int
archive_read_format_7zip_bid(struct archive_read *a, int best_bid)
{
const char *p;
/* If someone has already bid more than 32, then avoid
trashing the look-ahead buffers with a seek. */
if (best_bid > 32)
return (-1);
if ((p = __archive_read_ahead(a, 6, NULL)) == NULL)
return (0);
/* If first six bytes are the 7-Zip signature,
* return the bid right now. */
if (memcmp(p, _7ZIP_SIGNATURE, 6) == 0)
return (48);
/*
* It may a 7-Zip SFX archive file. If first two bytes are
* 'M' and 'Z' available on Windows or first four bytes are
* "\x7F\x45LF" available on posix like system, seek the 7-Zip
* signature. Although we will perform a seek when reading
* a header, what we do not use __archive_read_seek() here is
* due to a bidding performance.
*/
if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) {
ssize_t offset = SFX_MIN_ADDR;
ssize_t window = 4096;
ssize_t bytes_avail;
while (offset + window <= (SFX_MAX_ADDR)) {
const char *buff = __archive_read_ahead(a,
offset + window, &bytes_avail);
if (buff == NULL) {
/* Remaining bytes are less than window. */
window >>= 1;
if (window < 0x40)
return (0);
continue;
}
p = buff + offset;
while (p + 32 < buff + bytes_avail) {
int step = check_7zip_header_in_sfx(p);
if (step == 0)
return (48);
p += step;
}
offset = p - buff;
}
}
return (0);
}
static int
check_7zip_header_in_sfx(const char *p)
{
switch ((unsigned char)p[5]) {
case 0x1C:
if (memcmp(p, _7ZIP_SIGNATURE, 6) != 0)
return (6);
/*
* Test the CRC because its extraction code has 7-Zip
* Magic Code, so we should do this in order not to
* make a mis-detection.
*/
if (crc32(0, (const unsigned char *)p + 12, 20)
!= archive_le32dec(p + 8))
return (6);
/* Hit the header! */
return (0);
case 0x37: return (5);
case 0x7A: return (4);
case 0xBC: return (3);
case 0xAF: return (2);
case 0x27: return (1);
default: return (6);
}
}
static int
skip_sfx(struct archive_read *a, ssize_t bytes_avail)
{
const void *h;
const char *p, *q;
size_t skip, offset;
ssize_t bytes, window;
/*
* If bytes_avail > SFX_MIN_ADDR we do not have to call
* __archive_read_seek() at this time since we have
* already had enough data.
*/
if (bytes_avail > SFX_MIN_ADDR)
__archive_read_consume(a, SFX_MIN_ADDR);
else if (__archive_read_seek(a, SFX_MIN_ADDR, SEEK_SET) < 0)
return (ARCHIVE_FATAL);
offset = 0;
window = 1;
while (offset + window <= SFX_MAX_ADDR - SFX_MIN_ADDR) {
h = __archive_read_ahead(a, window, &bytes);
if (h == NULL) {
/* Remaining bytes are less than window. */
window >>= 1;
if (window < 0x40)
goto fatal;
continue;
}
if (bytes < 6) {
/* This case might happen when window == 1. */
window = 4096;
continue;
}
p = (const char *)h;
q = p + bytes;
/*
* Scan ahead until we find something that looks
* like the 7-Zip header.
*/
while (p + 32 < q) {
int step = check_7zip_header_in_sfx(p);
if (step == 0) {
struct _7zip *zip =
(struct _7zip *)a->format->data;
skip = p - (const char *)h;
__archive_read_consume(a, skip);
zip->seek_base = SFX_MIN_ADDR + offset + skip;
return (ARCHIVE_OK);
}
p += step;
}
skip = p - (const char *)h;
__archive_read_consume(a, skip);
offset += skip;
if (window == 1)
window = 4096;
}
fatal:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Couldn't find out 7-Zip header");
return (ARCHIVE_FATAL);
}
static int
archive_read_format_7zip_read_header(struct archive_read *a,
struct archive_entry *entry)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
struct _7zip_entry *zip_entry;
int r, ret = ARCHIVE_OK;
struct _7z_folder *folder = 0;
uint64_t fidx = 0;
/*
* It should be sufficient to call archive_read_next_header() for
* a reader to determine if an entry is encrypted or not. If the
* encryption of an entry is only detectable when calling
* archive_read_data(), so be it. We'll do the same check there
* as well.
*/
if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
zip->has_encrypted_entries = 0;
}
a->archive.archive_format = ARCHIVE_FORMAT_7ZIP;
if (a->archive.archive_format_name == NULL)
a->archive.archive_format_name = "7-Zip";
if (zip->entries == NULL) {
struct _7z_header_info header;
memset(&header, 0, sizeof(header));
r = slurp_central_directory(a, zip, &header);
free_Header(&header);
if (r != ARCHIVE_OK)
return (r);
zip->entries_remaining = (size_t)zip->numFiles;
zip->entry = zip->entries;
} else {
++zip->entry;
}
zip_entry = zip->entry;
if (zip->entries_remaining <= 0 || zip_entry == NULL)
return ARCHIVE_EOF;
--zip->entries_remaining;
zip->entry_offset = 0;
zip->end_of_entry = 0;
zip->entry_crc32 = crc32(0, NULL, 0);
/* Setup a string conversion for a filename. */
if (zip->sconv == NULL) {
zip->sconv = archive_string_conversion_from_charset(
&a->archive, "UTF-16LE", 1);
if (zip->sconv == NULL)
return (ARCHIVE_FATAL);
}
/* Figure out if the entry is encrypted by looking at the folder
that is associated to the current 7zip entry. If the folder
has a coder with a _7Z_CRYPTO codec then the folder is encrypted.
Hence the entry must also be encrypted. */
if (zip_entry && zip_entry->folderIndex < zip->si.ci.numFolders) {
folder = &(zip->si.ci.folders[zip_entry->folderIndex]);
for (fidx=0; folder && fidx<folder->numCoders; fidx++) {
switch(folder->coders[fidx].codec) {
case _7Z_CRYPTO_MAIN_ZIP:
case _7Z_CRYPTO_RAR_29:
case _7Z_CRYPTO_AES_256_SHA_256: {
archive_entry_set_is_data_encrypted(entry, 1);
zip->has_encrypted_entries = 1;
break;
}
}
}
}
/* Now that we've checked for encryption, if there were still no
* encrypted entries found we can say for sure that there are none.
*/
if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
zip->has_encrypted_entries = 0;
}
if (archive_entry_copy_pathname_l(entry,
(const char *)zip_entry->utf16name,
zip_entry->name_len, zip->sconv) != 0) {
if (errno == ENOMEM) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Pathname");
return (ARCHIVE_FATAL);
}
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Pathname cannot be converted "
"from %s to current locale.",
archive_string_conversion_charset_name(zip->sconv));
ret = ARCHIVE_WARN;
}
/* Populate some additional entry fields: */
archive_entry_set_mode(entry, zip_entry->mode);
if (zip_entry->flg & MTIME_IS_SET)
archive_entry_set_mtime(entry, zip_entry->mtime,
zip_entry->mtime_ns);
if (zip_entry->flg & CTIME_IS_SET)
archive_entry_set_ctime(entry, zip_entry->ctime,
zip_entry->ctime_ns);
if (zip_entry->flg & ATIME_IS_SET)
archive_entry_set_atime(entry, zip_entry->atime,
zip_entry->atime_ns);
if (zip_entry->ssIndex != (uint32_t)-1) {
zip->entry_bytes_remaining =
zip->si.ss.unpackSizes[zip_entry->ssIndex];
archive_entry_set_size(entry, zip->entry_bytes_remaining);
} else {
zip->entry_bytes_remaining = 0;
archive_entry_set_size(entry, 0);
}
/* If there's no body, force read_data() to return EOF immediately. */
if (zip->entry_bytes_remaining < 1)
zip->end_of_entry = 1;
if ((zip_entry->mode & AE_IFMT) == AE_IFLNK) {
unsigned char *symname = NULL;
size_t symsize = 0;
/*
* Symbolic-name is recorded as its contents. We have to
* read the contents at this time.
*/
while (zip->entry_bytes_remaining > 0) {
const void *buff;
unsigned char *mem;
size_t size;
int64_t offset;
r = archive_read_format_7zip_read_data(a, &buff,
&size, &offset);
if (r < ARCHIVE_WARN) {
free(symname);
return (r);
}
mem = realloc(symname, symsize + size + 1);
if (mem == NULL) {
free(symname);
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Symname");
return (ARCHIVE_FATAL);
}
symname = mem;
memcpy(symname+symsize, buff, size);
symsize += size;
}
if (symsize == 0) {
/* If there is no symname, handle it as a regular
* file. */
zip_entry->mode &= ~AE_IFMT;
zip_entry->mode |= AE_IFREG;
archive_entry_set_mode(entry, zip_entry->mode);
} else {
symname[symsize] = '\0';
archive_entry_copy_symlink(entry,
(const char *)symname);
}
free(symname);
archive_entry_set_size(entry, 0);
}
/* Set up a more descriptive format name. */
sprintf(zip->format_name, "7-Zip");
a->archive.archive_format_name = zip->format_name;
return (ret);
}
static int
archive_read_format_7zip_read_data(struct archive_read *a,
const void **buff, size_t *size, int64_t *offset)
{
struct _7zip *zip;
ssize_t bytes;
int ret = ARCHIVE_OK;
zip = (struct _7zip *)(a->format->data);
if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
zip->has_encrypted_entries = 0;
}
if (zip->pack_stream_bytes_unconsumed)
read_consume(a);
*offset = zip->entry_offset;
*size = 0;
*buff = NULL;
/*
* If we hit end-of-entry last time, clean up and return
* ARCHIVE_EOF this time.
*/
if (zip->end_of_entry)
return (ARCHIVE_EOF);
bytes = read_stream(a, buff,
(size_t)zip->entry_bytes_remaining, 0);
if (bytes < 0)
return ((int)bytes);
if (bytes == 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file body");
return (ARCHIVE_FATAL);
}
zip->entry_bytes_remaining -= bytes;
if (zip->entry_bytes_remaining == 0)
zip->end_of_entry = 1;
/* Update checksum */
if ((zip->entry->flg & CRC32_IS_SET) && bytes)
zip->entry_crc32 = crc32(zip->entry_crc32, *buff,
(unsigned)bytes);
/* If we hit the end, swallow any end-of-data marker. */
if (zip->end_of_entry) {
/* Check computed CRC against file contents. */
if ((zip->entry->flg & CRC32_IS_SET) &&
zip->si.ss.digests[zip->entry->ssIndex] !=
zip->entry_crc32) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"7-Zip bad CRC: 0x%lx should be 0x%lx",
(unsigned long)zip->entry_crc32,
(unsigned long)zip->si.ss.digests[
zip->entry->ssIndex]);
ret = ARCHIVE_WARN;
}
}
*size = bytes;
*offset = zip->entry_offset;
zip->entry_offset += bytes;
return (ret);
}
static int
archive_read_format_7zip_read_data_skip(struct archive_read *a)
{
struct _7zip *zip;
int64_t bytes_skipped;
zip = (struct _7zip *)(a->format->data);
if (zip->pack_stream_bytes_unconsumed)
read_consume(a);
/* If we've already read to end of data, we're done. */
if (zip->end_of_entry)
return (ARCHIVE_OK);
/*
* If the length is at the beginning, we can skip the
* compressed data much more quickly.
*/
bytes_skipped = skip_stream(a, (size_t)zip->entry_bytes_remaining);
if (bytes_skipped < 0)
return (ARCHIVE_FATAL);
zip->entry_bytes_remaining = 0;
/* This entry is finished and done. */
zip->end_of_entry = 1;
return (ARCHIVE_OK);
}
static int
archive_read_format_7zip_cleanup(struct archive_read *a)
{
struct _7zip *zip;
zip = (struct _7zip *)(a->format->data);
free_StreamsInfo(&(zip->si));
free(zip->entries);
free(zip->entry_names);
free_decompression(a, zip);
free(zip->uncompressed_buffer);
free(zip->sub_stream_buff[0]);
free(zip->sub_stream_buff[1]);
free(zip->sub_stream_buff[2]);
free(zip->tmp_stream_buff);
free(zip);
(a->format->data) = NULL;
return (ARCHIVE_OK);
}
static void
read_consume(struct archive_read *a)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
if (zip->pack_stream_bytes_unconsumed) {
__archive_read_consume(a, zip->pack_stream_bytes_unconsumed);
zip->stream_offset += zip->pack_stream_bytes_unconsumed;
zip->pack_stream_bytes_unconsumed = 0;
}
}
#ifdef HAVE_LZMA_H
/*
* Set an error code and choose an error message for liblzma.
*/
static void
set_error(struct archive_read *a, int ret)
{
switch (ret) {
case LZMA_STREAM_END: /* Found end of stream. */
case LZMA_OK: /* Decompressor made some progress. */
break;
case LZMA_MEM_ERROR:
archive_set_error(&a->archive, ENOMEM,
"Lzma library error: Cannot allocate memory");
break;
case LZMA_MEMLIMIT_ERROR:
archive_set_error(&a->archive, ENOMEM,
"Lzma library error: Out of memory");
break;
case LZMA_FORMAT_ERROR:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Lzma library error: format not recognized");
break;
case LZMA_OPTIONS_ERROR:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Lzma library error: Invalid options");
break;
case LZMA_DATA_ERROR:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Lzma library error: Corrupted input data");
break;
case LZMA_BUF_ERROR:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Lzma library error: No progress is possible");
break;
default:
/* Return an error. */
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Lzma decompression failed: Unknown error");
break;
}
}
#endif
static unsigned long
decode_codec_id(const unsigned char *codecId, size_t id_size)
{
unsigned i;
unsigned long id = 0;
for (i = 0; i < id_size; i++) {
id <<= 8;
id += codecId[i];
}
return (id);
}
static Byte
ppmd_read(void *p)
{
struct archive_read *a = ((IByteIn*)p)->a;
struct _7zip *zip = (struct _7zip *)(a->format->data);
Byte b;
if (zip->ppstream.avail_in == 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated RAR file data");
zip->ppstream.overconsumed = 1;
return (0);
}
b = *zip->ppstream.next_in++;
zip->ppstream.avail_in--;
zip->ppstream.total_in++;
return (b);
}
static int
init_decompression(struct archive_read *a, struct _7zip *zip,
const struct _7z_coder *coder1, const struct _7z_coder *coder2)
{
int r;
zip->codec = coder1->codec;
zip->codec2 = -1;
switch (zip->codec) {
case _7Z_COPY:
case _7Z_BZ2:
case _7Z_DEFLATE:
case _7Z_PPMD:
if (coder2 != NULL) {
if (coder2->codec != _7Z_X86 &&
coder2->codec != _7Z_X86_BCJ2) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Unsupported filter %lx for %lx",
coder2->codec, coder1->codec);
return (ARCHIVE_FAILED);
}
zip->codec2 = coder2->codec;
zip->bcj_state = 0;
if (coder2->codec == _7Z_X86)
x86_Init(zip);
}
break;
default:
break;
}
switch (zip->codec) {
case _7Z_COPY:
break;
case _7Z_LZMA: case _7Z_LZMA2:
#ifdef HAVE_LZMA_H
#if LZMA_VERSION_MAJOR >= 5
/* Effectively disable the limiter. */
#define LZMA_MEMLIMIT UINT64_MAX
#else
/* NOTE: This needs to check memory size which running system has. */
#define LZMA_MEMLIMIT (1U << 30)
#endif
{
lzma_options_delta delta_opt;
lzma_filter filters[LZMA_FILTERS_MAX], *ff;
int fi = 0;
if (zip->lzstream_valid) {
lzma_end(&(zip->lzstream));
zip->lzstream_valid = 0;
}
/*
* NOTE: liblzma incompletely handle the BCJ+LZMA compressed
* data made by 7-Zip because 7-Zip does not add End-Of-
* Payload Marker(EOPM) at the end of LZMA compressed data,
* and so liblzma cannot know the end of the compressed data
* without EOPM. So consequently liblzma will not return last
* three or four bytes of uncompressed data because
* LZMA_FILTER_X86 filter does not handle input data if its
* data size is less than five bytes. If liblzma detect EOPM
* or know the uncompressed data size, liblzma will flush out
* the remaining that three or four bytes of uncompressed
* data. That is why we have to use our converting program
* for BCJ+LZMA. If we were able to tell the uncompressed
* size to liblzma when using lzma_raw_decoder() liblzma
* could correctly deal with BCJ+LZMA. But unfortunately
* there is no way to do that.
* Discussion about this can be found at XZ Utils forum.
*/
if (coder2 != NULL) {
zip->codec2 = coder2->codec;
filters[fi].options = NULL;
switch (zip->codec2) {
case _7Z_X86:
if (zip->codec == _7Z_LZMA2) {
filters[fi].id = LZMA_FILTER_X86;
fi++;
} else
/* Use our filter. */
x86_Init(zip);
break;
case _7Z_X86_BCJ2:
/* Use our filter. */
zip->bcj_state = 0;
break;
case _7Z_DELTA:
filters[fi].id = LZMA_FILTER_DELTA;
memset(&delta_opt, 0, sizeof(delta_opt));
delta_opt.type = LZMA_DELTA_TYPE_BYTE;
delta_opt.dist = 1;
filters[fi].options = &delta_opt;
fi++;
break;
/* Following filters have not been tested yet. */
case _7Z_POWERPC:
filters[fi].id = LZMA_FILTER_POWERPC;
fi++;
break;
case _7Z_IA64:
filters[fi].id = LZMA_FILTER_IA64;
fi++;
break;
case _7Z_ARM:
filters[fi].id = LZMA_FILTER_ARM;
fi++;
break;
case _7Z_ARMTHUMB:
filters[fi].id = LZMA_FILTER_ARMTHUMB;
fi++;
break;
case _7Z_SPARC:
filters[fi].id = LZMA_FILTER_SPARC;
fi++;
break;
default:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Unexpected codec ID: %lX", zip->codec2);
return (ARCHIVE_FAILED);
}
}
if (zip->codec == _7Z_LZMA2)
filters[fi].id = LZMA_FILTER_LZMA2;
else
filters[fi].id = LZMA_FILTER_LZMA1;
filters[fi].options = NULL;
ff = &filters[fi];
r = lzma_properties_decode(&filters[fi], NULL,
coder1->properties, (size_t)coder1->propertiesSize);
if (r != LZMA_OK) {
set_error(a, r);
return (ARCHIVE_FAILED);
}
fi++;
filters[fi].id = LZMA_VLI_UNKNOWN;
filters[fi].options = NULL;
r = lzma_raw_decoder(&(zip->lzstream), filters);
free(ff->options);
if (r != LZMA_OK) {
set_error(a, r);
return (ARCHIVE_FAILED);
}
zip->lzstream_valid = 1;
zip->lzstream.total_in = 0;
zip->lzstream.total_out = 0;
break;
}
#else
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"LZMA codec is unsupported");
return (ARCHIVE_FAILED);
#endif
case _7Z_BZ2:
#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
if (zip->bzstream_valid) {
BZ2_bzDecompressEnd(&(zip->bzstream));
zip->bzstream_valid = 0;
}
r = BZ2_bzDecompressInit(&(zip->bzstream), 0, 0);
if (r == BZ_MEM_ERROR)
r = BZ2_bzDecompressInit(&(zip->bzstream), 0, 1);
if (r != BZ_OK) {
int err = ARCHIVE_ERRNO_MISC;
const char *detail = NULL;
switch (r) {
case BZ_PARAM_ERROR:
detail = "invalid setup parameter";
break;
case BZ_MEM_ERROR:
err = ENOMEM;
detail = "out of memory";
break;
case BZ_CONFIG_ERROR:
detail = "mis-compiled library";
break;
}
archive_set_error(&a->archive, err,
"Internal error initializing decompressor: %s",
detail != NULL ? detail : "??");
zip->bzstream_valid = 0;
return (ARCHIVE_FAILED);
}
zip->bzstream_valid = 1;
zip->bzstream.total_in_lo32 = 0;
zip->bzstream.total_in_hi32 = 0;
zip->bzstream.total_out_lo32 = 0;
zip->bzstream.total_out_hi32 = 0;
break;
#else
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"BZ2 codec is unsupported");
return (ARCHIVE_FAILED);
#endif
case _7Z_DEFLATE:
#ifdef HAVE_ZLIB_H
if (zip->stream_valid)
r = inflateReset(&(zip->stream));
else
r = inflateInit2(&(zip->stream),
-15 /* Don't check for zlib header */);
if (r != Z_OK) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Couldn't initialize zlib stream.");
return (ARCHIVE_FAILED);
}
zip->stream_valid = 1;
zip->stream.total_in = 0;
zip->stream.total_out = 0;
break;
#else
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"DEFLATE codec is unsupported");
return (ARCHIVE_FAILED);
#endif
case _7Z_PPMD:
{
unsigned order;
uint32_t msize;
if (zip->ppmd7_valid) {
__archive_ppmd7_functions.Ppmd7_Free(
&zip->ppmd7_context);
zip->ppmd7_valid = 0;
}
if (coder1->propertiesSize < 5) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Malformed PPMd parameter");
return (ARCHIVE_FAILED);
}
order = coder1->properties[0];
msize = archive_le32dec(&(coder1->properties[1]));
if (order < PPMD7_MIN_ORDER || order > PPMD7_MAX_ORDER ||
msize < PPMD7_MIN_MEM_SIZE || msize > PPMD7_MAX_MEM_SIZE) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Malformed PPMd parameter");
return (ARCHIVE_FAILED);
}
__archive_ppmd7_functions.Ppmd7_Construct(&zip->ppmd7_context);
r = __archive_ppmd7_functions.Ppmd7_Alloc(
&zip->ppmd7_context, msize);
if (r == 0) {
archive_set_error(&a->archive, ENOMEM,
"Coludn't allocate memory for PPMd");
return (ARCHIVE_FATAL);
}
__archive_ppmd7_functions.Ppmd7_Init(
&zip->ppmd7_context, order);
__archive_ppmd7_functions.Ppmd7z_RangeDec_CreateVTable(
&zip->range_dec);
zip->ppmd7_valid = 1;
zip->ppmd7_stat = 0;
zip->ppstream.overconsumed = 0;
zip->ppstream.total_in = 0;
zip->ppstream.total_out = 0;
break;
}
case _7Z_X86:
case _7Z_X86_BCJ2:
case _7Z_POWERPC:
case _7Z_IA64:
case _7Z_ARM:
case _7Z_ARMTHUMB:
case _7Z_SPARC:
case _7Z_DELTA:
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Unexpected codec ID: %lX", zip->codec);
return (ARCHIVE_FAILED);
case _7Z_CRYPTO_MAIN_ZIP:
case _7Z_CRYPTO_RAR_29:
case _7Z_CRYPTO_AES_256_SHA_256:
if (a->entry) {
archive_entry_set_is_metadata_encrypted(a->entry, 1);
archive_entry_set_is_data_encrypted(a->entry, 1);
zip->has_encrypted_entries = 1;
}
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Crypto codec not supported yet (ID: 0x%lX)", zip->codec);
return (ARCHIVE_FAILED);
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Unknown codec ID: %lX", zip->codec);
return (ARCHIVE_FAILED);
}
return (ARCHIVE_OK);
}
static int
decompress(struct archive_read *a, struct _7zip *zip,
void *buff, size_t *outbytes, const void *b, size_t *used)
{
const uint8_t *t_next_in;
uint8_t *t_next_out;
size_t o_avail_in, o_avail_out;
size_t t_avail_in, t_avail_out;
uint8_t *bcj2_next_out;
size_t bcj2_avail_out;
int r, ret = ARCHIVE_OK;
t_avail_in = o_avail_in = *used;
t_avail_out = o_avail_out = *outbytes;
t_next_in = b;
t_next_out = buff;
if (zip->codec != _7Z_LZMA2 && zip->codec2 == _7Z_X86) {
int i;
/* Do not copy out the BCJ remaining bytes when the output
* buffer size is less than five bytes. */
if (o_avail_in != 0 && t_avail_out < 5 && zip->odd_bcj_size) {
*used = 0;
*outbytes = 0;
return (ret);
}
for (i = 0; zip->odd_bcj_size > 0 && t_avail_out; i++) {
*t_next_out++ = zip->odd_bcj[i];
t_avail_out--;
zip->odd_bcj_size--;
}
if (o_avail_in == 0 || t_avail_out == 0) {
*used = o_avail_in - t_avail_in;
*outbytes = o_avail_out - t_avail_out;
if (o_avail_in == 0)
ret = ARCHIVE_EOF;
return (ret);
}
}
bcj2_next_out = t_next_out;
bcj2_avail_out = t_avail_out;
if (zip->codec2 == _7Z_X86_BCJ2) {
/*
* Decord a remaining decompressed main stream for BCJ2.
*/
if (zip->tmp_stream_bytes_remaining) {
ssize_t bytes;
size_t remaining = zip->tmp_stream_bytes_remaining;
bytes = Bcj2_Decode(zip, t_next_out, t_avail_out);
if (bytes < 0) {
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC,
"BCJ2 conversion Failed");
return (ARCHIVE_FAILED);
}
zip->main_stream_bytes_remaining -=
remaining - zip->tmp_stream_bytes_remaining;
t_avail_out -= bytes;
if (o_avail_in == 0 || t_avail_out == 0) {
*used = 0;
*outbytes = o_avail_out - t_avail_out;
if (o_avail_in == 0 &&
zip->tmp_stream_bytes_remaining)
ret = ARCHIVE_EOF;
return (ret);
}
t_next_out += bytes;
bcj2_next_out = t_next_out;
bcj2_avail_out = t_avail_out;
}
t_next_out = zip->tmp_stream_buff;
t_avail_out = zip->tmp_stream_buff_size;
}
switch (zip->codec) {
case _7Z_COPY:
{
size_t bytes =
(t_avail_in > t_avail_out)?t_avail_out:t_avail_in;
memcpy(t_next_out, t_next_in, bytes);
t_avail_in -= bytes;
t_avail_out -= bytes;
if (o_avail_in == 0)
ret = ARCHIVE_EOF;
break;
}
#ifdef HAVE_LZMA_H
case _7Z_LZMA: case _7Z_LZMA2:
zip->lzstream.next_in = t_next_in;
zip->lzstream.avail_in = t_avail_in;
zip->lzstream.next_out = t_next_out;
zip->lzstream.avail_out = t_avail_out;
r = lzma_code(&(zip->lzstream), LZMA_RUN);
switch (r) {
case LZMA_STREAM_END: /* Found end of stream. */
lzma_end(&(zip->lzstream));
zip->lzstream_valid = 0;
ret = ARCHIVE_EOF;
break;
case LZMA_OK: /* Decompressor made some progress. */
break;
default:
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC,
"Decompression failed(%d)",
r);
return (ARCHIVE_FAILED);
}
t_avail_in = zip->lzstream.avail_in;
t_avail_out = zip->lzstream.avail_out;
break;
#endif
#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
case _7Z_BZ2:
zip->bzstream.next_in = (char *)(uintptr_t)t_next_in;
zip->bzstream.avail_in = t_avail_in;
zip->bzstream.next_out = (char *)(uintptr_t)t_next_out;
zip->bzstream.avail_out = t_avail_out;
r = BZ2_bzDecompress(&(zip->bzstream));
switch (r) {
case BZ_STREAM_END: /* Found end of stream. */
switch (BZ2_bzDecompressEnd(&(zip->bzstream))) {
case BZ_OK:
break;
default:
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC,
"Failed to clean up decompressor");
return (ARCHIVE_FAILED);
}
zip->bzstream_valid = 0;
ret = ARCHIVE_EOF;
break;
case BZ_OK: /* Decompressor made some progress. */
break;
default:
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC,
"bzip decompression failed");
return (ARCHIVE_FAILED);
}
t_avail_in = zip->bzstream.avail_in;
t_avail_out = zip->bzstream.avail_out;
break;
#endif
#ifdef HAVE_ZLIB_H
case _7Z_DEFLATE:
zip->stream.next_in = (Bytef *)(uintptr_t)t_next_in;
zip->stream.avail_in = (uInt)t_avail_in;
zip->stream.next_out = t_next_out;
zip->stream.avail_out = (uInt)t_avail_out;
r = inflate(&(zip->stream), 0);
switch (r) {
case Z_STREAM_END: /* Found end of stream. */
ret = ARCHIVE_EOF;
break;
case Z_OK: /* Decompressor made some progress.*/
break;
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"File decompression failed (%d)", r);
return (ARCHIVE_FAILED);
}
t_avail_in = zip->stream.avail_in;
t_avail_out = zip->stream.avail_out;
break;
#endif
case _7Z_PPMD:
{
uint64_t flush_bytes;
if (!zip->ppmd7_valid || zip->ppmd7_stat < 0 ||
t_avail_out <= 0) {
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC,
"Decompression internal error");
return (ARCHIVE_FAILED);
}
zip->ppstream.next_in = t_next_in;
zip->ppstream.avail_in = t_avail_in;
zip->ppstream.next_out = t_next_out;
zip->ppstream.avail_out = t_avail_out;
if (zip->ppmd7_stat == 0) {
zip->bytein.a = a;
zip->bytein.Read = &ppmd_read;
zip->range_dec.Stream = &zip->bytein;
r = __archive_ppmd7_functions.Ppmd7z_RangeDec_Init(
&(zip->range_dec));
if (r == 0) {
zip->ppmd7_stat = -1;
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Failed to initialize PPMd range decorder");
return (ARCHIVE_FAILED);
}
if (zip->ppstream.overconsumed) {
zip->ppmd7_stat = -1;
return (ARCHIVE_FAILED);
}
zip->ppmd7_stat = 1;
}
if (t_avail_in == 0)
/* XXX Flush out remaining decoded data XXX */
flush_bytes = zip->folder_outbytes_remaining;
else
flush_bytes = 0;
do {
int sym;
sym = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
&(zip->ppmd7_context), &(zip->range_dec.p));
if (sym < 0) {
zip->ppmd7_stat = -1;
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Failed to decode PPMd");
return (ARCHIVE_FAILED);
}
if (zip->ppstream.overconsumed) {
zip->ppmd7_stat = -1;
return (ARCHIVE_FAILED);
}
*zip->ppstream.next_out++ = (unsigned char)sym;
zip->ppstream.avail_out--;
zip->ppstream.total_out++;
if (flush_bytes)
flush_bytes--;
} while (zip->ppstream.avail_out &&
(zip->ppstream.avail_in || flush_bytes));
t_avail_in = (size_t)zip->ppstream.avail_in;
t_avail_out = (size_t)zip->ppstream.avail_out;
break;
}
default:
archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
"Decompression internal error");
return (ARCHIVE_FAILED);
}
if (ret != ARCHIVE_OK && ret != ARCHIVE_EOF)
return (ret);
*used = o_avail_in - t_avail_in;
*outbytes = o_avail_out - t_avail_out;
/*
* Decord BCJ.
*/
if (zip->codec != _7Z_LZMA2 && zip->codec2 == _7Z_X86) {
size_t l = x86_Convert(zip, buff, *outbytes);
zip->odd_bcj_size = *outbytes - l;
if (zip->odd_bcj_size > 0 && zip->odd_bcj_size <= 4 &&
o_avail_in && ret != ARCHIVE_EOF) {
memcpy(zip->odd_bcj, ((unsigned char *)buff) + l,
zip->odd_bcj_size);
*outbytes = l;
} else
zip->odd_bcj_size = 0;
}
/*
* Decord BCJ2 with a decompressed main stream.
*/
if (zip->codec2 == _7Z_X86_BCJ2) {
ssize_t bytes;
zip->tmp_stream_bytes_avail =
zip->tmp_stream_buff_size - t_avail_out;
if (zip->tmp_stream_bytes_avail >
zip->main_stream_bytes_remaining)
zip->tmp_stream_bytes_avail =
zip->main_stream_bytes_remaining;
zip->tmp_stream_bytes_remaining = zip->tmp_stream_bytes_avail;
bytes = Bcj2_Decode(zip, bcj2_next_out, bcj2_avail_out);
if (bytes < 0) {
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC, "BCJ2 conversion Failed");
return (ARCHIVE_FAILED);
}
zip->main_stream_bytes_remaining -=
zip->tmp_stream_bytes_avail
- zip->tmp_stream_bytes_remaining;
bcj2_avail_out -= bytes;
*outbytes = o_avail_out - bcj2_avail_out;
}
return (ret);
}
static int
free_decompression(struct archive_read *a, struct _7zip *zip)
{
int r = ARCHIVE_OK;
#if !defined(HAVE_ZLIB_H) &&\
!(defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR))
(void)a;/* UNUSED */
#endif
#ifdef HAVE_LZMA_H
if (zip->lzstream_valid)
lzma_end(&(zip->lzstream));
#endif
#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
if (zip->bzstream_valid) {
if (BZ2_bzDecompressEnd(&(zip->bzstream)) != BZ_OK) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Failed to clean up bzip2 decompressor");
r = ARCHIVE_FATAL;
}
zip->bzstream_valid = 0;
}
#endif
#ifdef HAVE_ZLIB_H
if (zip->stream_valid) {
if (inflateEnd(&(zip->stream)) != Z_OK) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Failed to clean up zlib decompressor");
r = ARCHIVE_FATAL;
}
zip->stream_valid = 0;
}
#endif
if (zip->ppmd7_valid) {
__archive_ppmd7_functions.Ppmd7_Free(
&zip->ppmd7_context);
zip->ppmd7_valid = 0;
}
return (r);
}
static int
parse_7zip_uint64(struct archive_read *a, uint64_t *val)
{
const unsigned char *p;
unsigned char avail, mask;
int i;
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
avail = *p;
mask = 0x80;
*val = 0;
for (i = 0; i < 8; i++) {
if (avail & mask) {
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
*val |= ((uint64_t)*p) << (8 * i);
mask >>= 1;
continue;
}
*val += ((uint64_t)(avail & (mask -1))) << (8 * i);
break;
}
return (0);
}
static int
read_Bools(struct archive_read *a, unsigned char *data, size_t num)
{
const unsigned char *p;
unsigned i, mask = 0, avail = 0;
for (i = 0; i < num; i++) {
if (mask == 0) {
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
avail = *p;
mask = 0x80;
}
data[i] = (avail & mask)?1:0;
mask >>= 1;
}
return (0);
}
static void
free_Digest(struct _7z_digests *d)
{
free(d->defineds);
free(d->digests);
}
static int
read_Digests(struct archive_read *a, struct _7z_digests *d, size_t num)
{
const unsigned char *p;
unsigned i;
if (num == 0)
return (-1);
memset(d, 0, sizeof(*d));
d->defineds = malloc(num);
if (d->defineds == NULL)
return (-1);
/*
* Read Bools.
*/
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p == 0) {
if (read_Bools(a, d->defineds, num) < 0)
return (-1);
} else
/* All are defined */
memset(d->defineds, 1, num);
d->digests = calloc(num, sizeof(*d->digests));
if (d->digests == NULL)
return (-1);
for (i = 0; i < num; i++) {
if (d->defineds[i]) {
if ((p = header_bytes(a, 4)) == NULL)
return (-1);
d->digests[i] = archive_le32dec(p);
}
}
return (0);
}
static void
free_PackInfo(struct _7z_pack_info *pi)
{
free(pi->sizes);
free(pi->positions);
free_Digest(&(pi->digest));
}
static int
read_PackInfo(struct archive_read *a, struct _7z_pack_info *pi)
{
const unsigned char *p;
unsigned i;
memset(pi, 0, sizeof(*pi));
/*
* Read PackPos.
*/
if (parse_7zip_uint64(a, &(pi->pos)) < 0)
return (-1);
/*
* Read NumPackStreams.
*/
if (parse_7zip_uint64(a, &(pi->numPackStreams)) < 0)
return (-1);
if (pi->numPackStreams == 0)
return (-1);
if (UMAX_ENTRY < pi->numPackStreams)
return (-1);
/*
* Read PackSizes[num]
*/
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p == kEnd)
/* PackSizes[num] are not present. */
return (0);
if (*p != kSize)
return (-1);
pi->sizes = calloc((size_t)pi->numPackStreams, sizeof(uint64_t));
pi->positions = calloc((size_t)pi->numPackStreams, sizeof(uint64_t));
if (pi->sizes == NULL || pi->positions == NULL)
return (-1);
for (i = 0; i < pi->numPackStreams; i++) {
if (parse_7zip_uint64(a, &(pi->sizes[i])) < 0)
return (-1);
}
/*
* Read PackStreamDigests[num]
*/
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p == kEnd) {
/* PackStreamDigests[num] are not present. */
pi->digest.defineds =
calloc((size_t)pi->numPackStreams, sizeof(*pi->digest.defineds));
pi->digest.digests =
calloc((size_t)pi->numPackStreams, sizeof(*pi->digest.digests));
if (pi->digest.defineds == NULL || pi->digest.digests == NULL)
return (-1);
return (0);
}
if (*p != kSize)
return (-1);
if (read_Digests(a, &(pi->digest), (size_t)pi->numPackStreams) < 0)
return (-1);
/*
* Must be marked by kEnd.
*/
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p != kEnd)
return (-1);
return (0);
}
static void
free_Folder(struct _7z_folder *f)
{
unsigned i;
if (f->coders) {
for (i = 0; i< f->numCoders; i++) {
free(f->coders[i].properties);
}
free(f->coders);
}
free(f->bindPairs);
free(f->packedStreams);
free(f->unPackSize);
}
static int
read_Folder(struct archive_read *a, struct _7z_folder *f)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
const unsigned char *p;
uint64_t numInStreamsTotal = 0;
uint64_t numOutStreamsTotal = 0;
unsigned i;
memset(f, 0, sizeof(*f));
/*
* Read NumCoders.
*/
if (parse_7zip_uint64(a, &(f->numCoders)) < 0)
return (-1);
if (f->numCoders > 4)
/* Too many coders. */
return (-1);
f->coders = calloc((size_t)f->numCoders, sizeof(*f->coders));
if (f->coders == NULL)
return (-1);
for (i = 0; i< f->numCoders; i++) {
size_t codec_size;
int simple, attr;
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
/*
* 0:3 CodecIdSize
* 4: 0 - IsSimple
* 1 - Is not Simple
* 5: 0 - No Attributes
* 1 - There are Attributes;
* 7: Must be zero.
*/
codec_size = *p & 0xf;
simple = (*p & 0x10)?0:1;
attr = *p & 0x20;
if (*p & 0x80)
return (-1);/* Not supported. */
/*
* Read Decompression Method IDs.
*/
if ((p = header_bytes(a, codec_size)) == NULL)
return (-1);
f->coders[i].codec = decode_codec_id(p, codec_size);
if (simple) {
f->coders[i].numInStreams = 1;
f->coders[i].numOutStreams = 1;
} else {
if (parse_7zip_uint64(
a, &(f->coders[i].numInStreams)) < 0)
return (-1);
if (UMAX_ENTRY < f->coders[i].numInStreams)
return (-1);
if (parse_7zip_uint64(
a, &(f->coders[i].numOutStreams)) < 0)
return (-1);
if (UMAX_ENTRY < f->coders[i].numOutStreams)
return (-1);
}
if (attr) {
if (parse_7zip_uint64(
a, &(f->coders[i].propertiesSize)) < 0)
return (-1);
if ((p = header_bytes(
a, (size_t)f->coders[i].propertiesSize)) == NULL)
return (-1);
f->coders[i].properties =
malloc((size_t)f->coders[i].propertiesSize);
if (f->coders[i].properties == NULL)
return (-1);
memcpy(f->coders[i].properties, p,
(size_t)f->coders[i].propertiesSize);
}
numInStreamsTotal += f->coders[i].numInStreams;
numOutStreamsTotal += f->coders[i].numOutStreams;
}
if (numOutStreamsTotal == 0 ||
numInStreamsTotal < numOutStreamsTotal-1)
return (-1);
f->numBindPairs = numOutStreamsTotal - 1;
if (zip->header_bytes_remaining < f->numBindPairs)
return (-1);
if (f->numBindPairs > 0) {
f->bindPairs =
calloc((size_t)f->numBindPairs, sizeof(*f->bindPairs));
if (f->bindPairs == NULL)
return (-1);
} else
f->bindPairs = NULL;
for (i = 0; i < f->numBindPairs; i++) {
if (parse_7zip_uint64(a, &(f->bindPairs[i].inIndex)) < 0)
return (-1);
if (UMAX_ENTRY < f->bindPairs[i].inIndex)
return (-1);
if (parse_7zip_uint64(a, &(f->bindPairs[i].outIndex)) < 0)
return (-1);
if (UMAX_ENTRY < f->bindPairs[i].outIndex)
return (-1);
}
f->numPackedStreams = numInStreamsTotal - f->numBindPairs;
f->packedStreams =
calloc((size_t)f->numPackedStreams, sizeof(*f->packedStreams));
if (f->packedStreams == NULL)
return (-1);
if (f->numPackedStreams == 1) {
for (i = 0; i < numInStreamsTotal; i++) {
unsigned j;
for (j = 0; j < f->numBindPairs; j++) {
if (f->bindPairs[j].inIndex == i)
break;
}
if (j == f->numBindPairs)
break;
}
if (i == numInStreamsTotal)
return (-1);
f->packedStreams[0] = i;
} else {
for (i = 0; i < f->numPackedStreams; i++) {
if (parse_7zip_uint64(a, &(f->packedStreams[i])) < 0)
return (-1);
if (UMAX_ENTRY < f->packedStreams[i])
return (-1);
}
}
f->numInStreams = numInStreamsTotal;
f->numOutStreams = numOutStreamsTotal;
return (0);
}
static void
free_CodersInfo(struct _7z_coders_info *ci)
{
unsigned i;
if (ci->folders) {
for (i = 0; i < ci->numFolders; i++)
free_Folder(&(ci->folders[i]));
free(ci->folders);
}
}
static int
read_CodersInfo(struct archive_read *a, struct _7z_coders_info *ci)
{
const unsigned char *p;
struct _7z_digests digest;
unsigned i;
memset(ci, 0, sizeof(*ci));
memset(&digest, 0, sizeof(digest));
if ((p = header_bytes(a, 1)) == NULL)
goto failed;
if (*p != kFolder)
goto failed;
/*
* Read NumFolders.
*/
if (parse_7zip_uint64(a, &(ci->numFolders)) < 0)
goto failed;
if (UMAX_ENTRY < ci->numFolders)
return (-1);
/*
* Read External.
*/
if ((p = header_bytes(a, 1)) == NULL)
goto failed;
switch (*p) {
case 0:
ci->folders =
calloc((size_t)ci->numFolders, sizeof(*ci->folders));
if (ci->folders == NULL)
return (-1);
for (i = 0; i < ci->numFolders; i++) {
if (read_Folder(a, &(ci->folders[i])) < 0)
goto failed;
}
break;
case 1:
if (parse_7zip_uint64(a, &(ci->dataStreamIndex)) < 0)
return (-1);
if (UMAX_ENTRY < ci->dataStreamIndex)
return (-1);
if (ci->numFolders > 0) {
archive_set_error(&a->archive, -1,
"Malformed 7-Zip archive");
goto failed;
}
break;
default:
archive_set_error(&a->archive, -1,
"Malformed 7-Zip archive");
goto failed;
}
if ((p = header_bytes(a, 1)) == NULL)
goto failed;
if (*p != kCodersUnPackSize)
goto failed;
for (i = 0; i < ci->numFolders; i++) {
struct _7z_folder *folder = &(ci->folders[i]);
unsigned j;
folder->unPackSize =
calloc((size_t)folder->numOutStreams, sizeof(*folder->unPackSize));
if (folder->unPackSize == NULL)
goto failed;
for (j = 0; j < folder->numOutStreams; j++) {
if (parse_7zip_uint64(a, &(folder->unPackSize[j])) < 0)
goto failed;
}
}
/*
* Read CRCs.
*/
if ((p = header_bytes(a, 1)) == NULL)
goto failed;
if (*p == kEnd)
return (0);
if (*p != kCRC)
goto failed;
if (read_Digests(a, &digest, (size_t)ci->numFolders) < 0)
goto failed;
for (i = 0; i < ci->numFolders; i++) {
ci->folders[i].digest_defined = digest.defineds[i];
ci->folders[i].digest = digest.digests[i];
}
/*
* Must be kEnd.
*/
if ((p = header_bytes(a, 1)) == NULL)
goto failed;
if (*p != kEnd)
goto failed;
free_Digest(&digest);
return (0);
failed:
free_Digest(&digest);
return (-1);
}
static uint64_t
folder_uncompressed_size(struct _7z_folder *f)
{
int n = (int)f->numOutStreams;
unsigned pairs = (unsigned)f->numBindPairs;
while (--n >= 0) {
unsigned i;
for (i = 0; i < pairs; i++) {
if (f->bindPairs[i].outIndex == (uint64_t)n)
break;
}
if (i >= pairs)
return (f->unPackSize[n]);
}
return (0);
}
static void
free_SubStreamsInfo(struct _7z_substream_info *ss)
{
free(ss->unpackSizes);
free(ss->digestsDefined);
free(ss->digests);
}
static int
read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss,
struct _7z_folder *f, size_t numFolders)
{
const unsigned char *p;
uint64_t *usizes;
size_t unpack_streams;
int type;
unsigned i;
uint32_t numDigests;
memset(ss, 0, sizeof(*ss));
for (i = 0; i < numFolders; i++)
f[i].numUnpackStreams = 1;
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
type = *p;
if (type == kNumUnPackStream) {
unpack_streams = 0;
for (i = 0; i < numFolders; i++) {
if (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0)
return (-1);
if (UMAX_ENTRY < f[i].numUnpackStreams)
return (-1);
if (unpack_streams > SIZE_MAX - UMAX_ENTRY) {
return (-1);
}
unpack_streams += (size_t)f[i].numUnpackStreams;
}
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
type = *p;
} else
unpack_streams = numFolders;
ss->unpack_streams = unpack_streams;
if (unpack_streams) {
ss->unpackSizes = calloc(unpack_streams,
sizeof(*ss->unpackSizes));
ss->digestsDefined = calloc(unpack_streams,
sizeof(*ss->digestsDefined));
ss->digests = calloc(unpack_streams,
sizeof(*ss->digests));
if (ss->unpackSizes == NULL || ss->digestsDefined == NULL ||
ss->digests == NULL)
return (-1);
}
usizes = ss->unpackSizes;
for (i = 0; i < numFolders; i++) {
unsigned pack;
uint64_t sum;
if (f[i].numUnpackStreams == 0)
continue;
sum = 0;
if (type == kSize) {
for (pack = 1; pack < f[i].numUnpackStreams; pack++) {
if (parse_7zip_uint64(a, usizes) < 0)
return (-1);
sum += *usizes++;
}
}
*usizes++ = folder_uncompressed_size(&f[i]) - sum;
}
if (type == kSize) {
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
type = *p;
}
for (i = 0; i < unpack_streams; i++) {
ss->digestsDefined[i] = 0;
ss->digests[i] = 0;
}
numDigests = 0;
for (i = 0; i < numFolders; i++) {
if (f[i].numUnpackStreams != 1 || !f[i].digest_defined)
numDigests += (uint32_t)f[i].numUnpackStreams;
}
if (type == kCRC) {
struct _7z_digests tmpDigests;
unsigned char *digestsDefined = ss->digestsDefined;
uint32_t * digests = ss->digests;
int di = 0;
memset(&tmpDigests, 0, sizeof(tmpDigests));
if (read_Digests(a, &(tmpDigests), numDigests) < 0) {
free_Digest(&tmpDigests);
return (-1);
}
for (i = 0; i < numFolders; i++) {
if (f[i].numUnpackStreams == 1 && f[i].digest_defined) {
*digestsDefined++ = 1;
*digests++ = f[i].digest;
} else {
unsigned j;
for (j = 0; j < f[i].numUnpackStreams;
j++, di++) {
*digestsDefined++ =
tmpDigests.defineds[di];
*digests++ =
tmpDigests.digests[di];
}
}
}
free_Digest(&tmpDigests);
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
type = *p;
}
/*
* Must be kEnd.
*/
if (type != kEnd)
return (-1);
return (0);
}
static void
free_StreamsInfo(struct _7z_stream_info *si)
{
free_PackInfo(&(si->pi));
free_CodersInfo(&(si->ci));
free_SubStreamsInfo(&(si->ss));
}
static int
read_StreamsInfo(struct archive_read *a, struct _7z_stream_info *si)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
const unsigned char *p;
unsigned i;
memset(si, 0, sizeof(*si));
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p == kPackInfo) {
uint64_t packPos;
if (read_PackInfo(a, &(si->pi)) < 0)
return (-1);
if (si->pi.positions == NULL || si->pi.sizes == NULL)
return (-1);
/*
* Calculate packed stream positions.
*/
packPos = si->pi.pos;
for (i = 0; i < si->pi.numPackStreams; i++) {
si->pi.positions[i] = packPos;
packPos += si->pi.sizes[i];
if (packPos > zip->header_offset)
return (-1);
}
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
}
if (*p == kUnPackInfo) {
uint32_t packIndex;
struct _7z_folder *f;
if (read_CodersInfo(a, &(si->ci)) < 0)
return (-1);
/*
* Calculate packed stream indexes.
*/
packIndex = 0;
f = si->ci.folders;
for (i = 0; i < si->ci.numFolders; i++) {
f[i].packIndex = packIndex;
packIndex += (uint32_t)f[i].numPackedStreams;
if (packIndex > si->pi.numPackStreams)
return (-1);
}
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
}
if (*p == kSubStreamsInfo) {
if (read_SubStreamsInfo(a, &(si->ss),
si->ci.folders, (size_t)si->ci.numFolders) < 0)
return (-1);
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
}
/*
* Must be kEnd.
*/
if (*p != kEnd)
return (-1);
return (0);
}
static void
free_Header(struct _7z_header_info *h)
{
free(h->emptyStreamBools);
free(h->emptyFileBools);
free(h->antiBools);
free(h->attrBools);
}
static int
read_Header(struct archive_read *a, struct _7z_header_info *h,
int check_header_id)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
const unsigned char *p;
struct _7z_folder *folders;
struct _7z_stream_info *si = &(zip->si);
struct _7zip_entry *entries;
uint32_t folderIndex, indexInFolder;
unsigned i;
int eindex, empty_streams, sindex;
if (check_header_id) {
/*
* Read Header.
*/
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p != kHeader)
return (-1);
}
/*
* Read ArchiveProperties.
*/
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p == kArchiveProperties) {
for (;;) {
uint64_t size;
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p == 0)
break;
if (parse_7zip_uint64(a, &size) < 0)
return (-1);
}
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
}
/*
* Read MainStreamsInfo.
*/
if (*p == kMainStreamsInfo) {
if (read_StreamsInfo(a, &(zip->si)) < 0)
return (-1);
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
}
if (*p == kEnd)
return (0);
/*
* Read FilesInfo.
*/
if (*p != kFilesInfo)
return (-1);
if (parse_7zip_uint64(a, &(zip->numFiles)) < 0)
return (-1);
if (UMAX_ENTRY < zip->numFiles)
return (-1);
zip->entries = calloc((size_t)zip->numFiles, sizeof(*zip->entries));
if (zip->entries == NULL)
return (-1);
entries = zip->entries;
empty_streams = 0;
for (;;) {
int type;
uint64_t size;
size_t ll;
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
type = *p;
if (type == kEnd)
break;
if (parse_7zip_uint64(a, &size) < 0)
return (-1);
if (zip->header_bytes_remaining < size)
return (-1);
ll = (size_t)size;
switch (type) {
case kEmptyStream:
if (h->emptyStreamBools != NULL)
return (-1);
h->emptyStreamBools = calloc((size_t)zip->numFiles,
sizeof(*h->emptyStreamBools));
if (h->emptyStreamBools == NULL)
return (-1);
if (read_Bools(
a, h->emptyStreamBools, (size_t)zip->numFiles) < 0)
return (-1);
empty_streams = 0;
for (i = 0; i < zip->numFiles; i++) {
if (h->emptyStreamBools[i])
empty_streams++;
}
break;
case kEmptyFile:
if (empty_streams <= 0) {
/* Unexcepted sequence. Skip this. */
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
if (h->emptyFileBools != NULL)
return (-1);
h->emptyFileBools = calloc(empty_streams,
sizeof(*h->emptyFileBools));
if (h->emptyFileBools == NULL)
return (-1);
if (read_Bools(a, h->emptyFileBools, empty_streams) < 0)
return (-1);
break;
case kAnti:
if (empty_streams <= 0) {
/* Unexcepted sequence. Skip this. */
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
if (h->antiBools != NULL)
return (-1);
h->antiBools = calloc(empty_streams,
sizeof(*h->antiBools));
if (h->antiBools == NULL)
return (-1);
if (read_Bools(a, h->antiBools, empty_streams) < 0)
return (-1);
break;
case kCTime:
case kATime:
case kMTime:
if (read_Times(a, h, type) < 0)
return (-1);
break;
case kName:
{
unsigned char *np;
size_t nl, nb;
/* Skip one byte. */
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
ll--;
if ((ll & 1) || ll < zip->numFiles * 4)
return (-1);
if (zip->entry_names != NULL)
return (-1);
zip->entry_names = malloc(ll);
if (zip->entry_names == NULL)
return (-1);
np = zip->entry_names;
nb = ll;
/*
* Copy whole file names.
* NOTE: This loop prevents from expanding
* the uncompressed buffer in order not to
* use extra memory resource.
*/
while (nb) {
size_t b;
if (nb > UBUFF_SIZE)
b = UBUFF_SIZE;
else
b = nb;
if ((p = header_bytes(a, b)) == NULL)
return (-1);
memcpy(np, p, b);
np += b;
nb -= b;
}
np = zip->entry_names;
nl = ll;
for (i = 0; i < zip->numFiles; i++) {
entries[i].utf16name = np;
#if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG)
entries[i].wname = (wchar_t *)np;
#endif
/* Find a terminator. */
while (nl >= 2 && (np[0] || np[1])) {
np += 2;
nl -= 2;
}
if (nl < 2)
return (-1);/* Terminator not found */
entries[i].name_len = np - entries[i].utf16name;
np += 2;
nl -= 2;
}
break;
}
case kAttributes:
{
int allAreDefined;
if ((p = header_bytes(a, 2)) == NULL)
return (-1);
allAreDefined = *p;
if (h->attrBools != NULL)
return (-1);
h->attrBools = calloc((size_t)zip->numFiles,
sizeof(*h->attrBools));
if (h->attrBools == NULL)
return (-1);
if (allAreDefined)
memset(h->attrBools, 1, (size_t)zip->numFiles);
else {
if (read_Bools(a, h->attrBools,
(size_t)zip->numFiles) < 0)
return (-1);
}
for (i = 0; i < zip->numFiles; i++) {
if (h->attrBools[i]) {
if ((p = header_bytes(a, 4)) == NULL)
return (-1);
entries[i].attr = archive_le32dec(p);
}
}
break;
}
case kDummy:
if (ll == 0)
break;
__LA_FALLTHROUGH;
default:
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
}
/*
* Set up entry's attributes.
*/
folders = si->ci.folders;
eindex = sindex = 0;
folderIndex = indexInFolder = 0;
for (i = 0; i < zip->numFiles; i++) {
if (h->emptyStreamBools == NULL || h->emptyStreamBools[i] == 0)
entries[i].flg |= HAS_STREAM;
/* The high 16 bits of attributes is a posix file mode. */
entries[i].mode = entries[i].attr >> 16;
if (entries[i].flg & HAS_STREAM) {
if ((size_t)sindex >= si->ss.unpack_streams)
return (-1);
if (entries[i].mode == 0)
entries[i].mode = AE_IFREG | 0666;
if (si->ss.digestsDefined[sindex])
entries[i].flg |= CRC32_IS_SET;
entries[i].ssIndex = sindex;
sindex++;
} else {
int dir;
if (h->emptyFileBools == NULL)
dir = 1;
else {
if (h->emptyFileBools[eindex])
dir = 0;
else
dir = 1;
eindex++;
}
if (entries[i].mode == 0) {
if (dir)
entries[i].mode = AE_IFDIR | 0777;
else
entries[i].mode = AE_IFREG | 0666;
} else if (dir &&
(entries[i].mode & AE_IFMT) != AE_IFDIR) {
entries[i].mode &= ~AE_IFMT;
entries[i].mode |= AE_IFDIR;
}
if ((entries[i].mode & AE_IFMT) == AE_IFDIR &&
entries[i].name_len >= 2 &&
(entries[i].utf16name[entries[i].name_len-2] != '/' ||
entries[i].utf16name[entries[i].name_len-1] != 0)) {
entries[i].utf16name[entries[i].name_len] = '/';
entries[i].utf16name[entries[i].name_len+1] = 0;
entries[i].name_len += 2;
}
entries[i].ssIndex = -1;
}
if (entries[i].attr & 0x01)
entries[i].mode &= ~0222;/* Read only. */
if ((entries[i].flg & HAS_STREAM) == 0 && indexInFolder == 0) {
/*
* The entry is an empty file or a directory file,
* those both have no contents.
*/
entries[i].folderIndex = -1;
continue;
}
if (indexInFolder == 0) {
for (;;) {
if (folderIndex >= si->ci.numFolders)
return (-1);
if (folders[folderIndex].numUnpackStreams)
break;
folderIndex++;
}
}
entries[i].folderIndex = folderIndex;
if ((entries[i].flg & HAS_STREAM) == 0)
continue;
indexInFolder++;
if (indexInFolder >= folders[folderIndex].numUnpackStreams) {
folderIndex++;
indexInFolder = 0;
}
}
return (0);
}
#define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000)
static void
fileTimeToUtc(uint64_t fileTime, time_t *timep, long *ns)
{
if (fileTime >= EPOC_TIME) {
fileTime -= EPOC_TIME;
/* milli seconds base */
*timep = (time_t)(fileTime / 10000000);
/* nano seconds base */
*ns = (long)(fileTime % 10000000) * 100;
} else {
*timep = 0;
*ns = 0;
}
}
static int
read_Times(struct archive_read *a, struct _7z_header_info *h, int type)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
const unsigned char *p;
struct _7zip_entry *entries = zip->entries;
unsigned char *timeBools;
int allAreDefined;
unsigned i;
timeBools = calloc((size_t)zip->numFiles, sizeof(*timeBools));
if (timeBools == NULL)
return (-1);
/* Read allAreDefined. */
if ((p = header_bytes(a, 1)) == NULL)
goto failed;
allAreDefined = *p;
if (allAreDefined)
memset(timeBools, 1, (size_t)zip->numFiles);
else {
if (read_Bools(a, timeBools, (size_t)zip->numFiles) < 0)
goto failed;
}
/* Read external. */
if ((p = header_bytes(a, 1)) == NULL)
goto failed;
if (*p) {
if (parse_7zip_uint64(a, &(h->dataIndex)) < 0)
goto failed;
if (UMAX_ENTRY < h->dataIndex)
goto failed;
}
for (i = 0; i < zip->numFiles; i++) {
if (!timeBools[i])
continue;
if ((p = header_bytes(a, 8)) == NULL)
goto failed;
switch (type) {
case kCTime:
fileTimeToUtc(archive_le64dec(p),
&(entries[i].ctime),
&(entries[i].ctime_ns));
entries[i].flg |= CTIME_IS_SET;
break;
case kATime:
fileTimeToUtc(archive_le64dec(p),
&(entries[i].atime),
&(entries[i].atime_ns));
entries[i].flg |= ATIME_IS_SET;
break;
case kMTime:
fileTimeToUtc(archive_le64dec(p),
&(entries[i].mtime),
&(entries[i].mtime_ns));
entries[i].flg |= MTIME_IS_SET;
break;
}
}
free(timeBools);
return (0);
failed:
free(timeBools);
return (-1);
}
static int
decode_encoded_header_info(struct archive_read *a, struct _7z_stream_info *si)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
errno = 0;
if (read_StreamsInfo(a, si) < 0) {
if (errno == ENOMEM)
archive_set_error(&a->archive, -1,
"Couldn't allocate memory");
else
archive_set_error(&a->archive, -1,
"Malformed 7-Zip archive");
return (ARCHIVE_FATAL);
}
if (si->pi.numPackStreams == 0 || si->ci.numFolders == 0) {
archive_set_error(&a->archive, -1, "Malformed 7-Zip archive");
return (ARCHIVE_FATAL);
}
if (zip->header_offset < si->pi.pos + si->pi.sizes[0] ||
(int64_t)(si->pi.pos + si->pi.sizes[0]) < 0 ||
si->pi.sizes[0] == 0 || (int64_t)si->pi.pos < 0) {
archive_set_error(&a->archive, -1, "Malformed Header offset");
return (ARCHIVE_FATAL);
}
return (ARCHIVE_OK);
}
static const unsigned char *
header_bytes(struct archive_read *a, size_t rbytes)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
const unsigned char *p;
if (zip->header_bytes_remaining < rbytes)
return (NULL);
if (zip->pack_stream_bytes_unconsumed)
read_consume(a);
if (zip->header_is_encoded == 0) {
p = __archive_read_ahead(a, rbytes, NULL);
if (p == NULL)
return (NULL);
zip->header_bytes_remaining -= rbytes;
zip->pack_stream_bytes_unconsumed = rbytes;
} else {
const void *buff;
ssize_t bytes;
bytes = read_stream(a, &buff, rbytes, rbytes);
if (bytes <= 0)
return (NULL);
zip->header_bytes_remaining -= bytes;
p = buff;
}
/* Update checksum */
zip->header_crc32 = crc32(zip->header_crc32, p, (unsigned)rbytes);
return (p);
}
static int
slurp_central_directory(struct archive_read *a, struct _7zip *zip,
struct _7z_header_info *header)
{
const unsigned char *p;
uint64_t next_header_offset;
uint64_t next_header_size;
uint32_t next_header_crc;
ssize_t bytes_avail;
int check_header_crc, r;
if ((p = __archive_read_ahead(a, 32, &bytes_avail)) == NULL)
return (ARCHIVE_FATAL);
if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) {
/* This is an executable ? Must be self-extracting... */
r = skip_sfx(a, bytes_avail);
if (r < ARCHIVE_WARN)
return (r);
if ((p = __archive_read_ahead(a, 32, &bytes_avail)) == NULL)
return (ARCHIVE_FATAL);
}
zip->seek_base += 32;
if (memcmp(p, _7ZIP_SIGNATURE, 6) != 0) {
archive_set_error(&a->archive, -1, "Not 7-Zip archive file");
return (ARCHIVE_FATAL);
}
/* CRC check. */
if (crc32(0, (const unsigned char *)p + 12, 20)
!= archive_le32dec(p + 8)) {
archive_set_error(&a->archive, -1, "Header CRC error");
return (ARCHIVE_FATAL);
}
next_header_offset = archive_le64dec(p + 12);
next_header_size = archive_le64dec(p + 20);
next_header_crc = archive_le32dec(p + 28);
if (next_header_size == 0)
/* There is no entry in an archive file. */
return (ARCHIVE_EOF);
if (((int64_t)next_header_offset) < 0) {
archive_set_error(&a->archive, -1, "Malformed 7-Zip archive");
return (ARCHIVE_FATAL);
}
__archive_read_consume(a, 32);
if (next_header_offset != 0) {
if (bytes_avail >= (ssize_t)next_header_offset)
__archive_read_consume(a, next_header_offset);
else if (__archive_read_seek(a,
next_header_offset + zip->seek_base, SEEK_SET) < 0)
return (ARCHIVE_FATAL);
}
zip->stream_offset = next_header_offset;
zip->header_offset = next_header_offset;
zip->header_bytes_remaining = next_header_size;
zip->header_crc32 = 0;
zip->header_is_encoded = 0;
zip->header_is_being_read = 1;
zip->has_encrypted_entries = 0;
check_header_crc = 1;
if ((p = header_bytes(a, 1)) == NULL) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file body");
return (ARCHIVE_FATAL);
}
/* Parse ArchiveProperties. */
switch (p[0]) {
case kEncodedHeader:
/*
* The archive has an encoded header and we have to decode it
* in order to parse the header correctly.
*/
r = decode_encoded_header_info(a, &(zip->si));
/* Check the EncodedHeader CRC.*/
if (r == 0 && zip->header_crc32 != next_header_crc) {
archive_set_error(&a->archive, -1,
"Damaged 7-Zip archive");
r = -1;
}
if (r == 0) {
if (zip->si.ci.folders[0].digest_defined)
next_header_crc = zip->si.ci.folders[0].digest;
else
check_header_crc = 0;
if (zip->pack_stream_bytes_unconsumed)
read_consume(a);
r = setup_decode_folder(a, zip->si.ci.folders, 1);
if (r == 0) {
zip->header_bytes_remaining =
zip->folder_outbytes_remaining;
r = seek_pack(a);
}
}
/* Clean up StreamsInfo. */
free_StreamsInfo(&(zip->si));
memset(&(zip->si), 0, sizeof(zip->si));
if (r < 0)
return (ARCHIVE_FATAL);
zip->header_is_encoded = 1;
zip->header_crc32 = 0;
/* FALL THROUGH */
case kHeader:
/*
* Parse the header.
*/
errno = 0;
r = read_Header(a, header, zip->header_is_encoded);
if (r < 0) {
if (errno == ENOMEM)
archive_set_error(&a->archive, -1,
"Couldn't allocate memory");
else
archive_set_error(&a->archive, -1,
"Damaged 7-Zip archive");
return (ARCHIVE_FATAL);
}
/*
* Must be kEnd.
*/
if ((p = header_bytes(a, 1)) == NULL ||*p != kEnd) {
archive_set_error(&a->archive, -1,
"Malformed 7-Zip archive");
return (ARCHIVE_FATAL);
}
/* Check the Header CRC.*/
if (check_header_crc && zip->header_crc32 != next_header_crc) {
archive_set_error(&a->archive, -1,
"Malformed 7-Zip archive");
return (ARCHIVE_FATAL);
}
break;
default:
archive_set_error(&a->archive, -1,
"Unexpected Property ID = %X", p[0]);
return (ARCHIVE_FATAL);
}
/* Clean up variables be used for decoding the archive header */
zip->pack_stream_remaining = 0;
zip->pack_stream_index = 0;
zip->folder_outbytes_remaining = 0;
zip->uncompressed_buffer_bytes_remaining = 0;
zip->pack_stream_bytes_unconsumed = 0;
zip->header_is_being_read = 0;
return (ARCHIVE_OK);
}
static ssize_t
get_uncompressed_data(struct archive_read *a, const void **buff, size_t size,
size_t minimum)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
ssize_t bytes_avail;
if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {
/* Copy mode. */
/*
* Note: '1' here is a performance optimization.
* Recall that the decompression layer returns a count of
* available bytes; asking for more than that forces the
* decompressor to combine reads by copying data.
*/
*buff = __archive_read_ahead(a, 1, &bytes_avail);
if (bytes_avail <= 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file data");
return (ARCHIVE_FATAL);
}
if ((size_t)bytes_avail >
zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
if ((size_t)bytes_avail > size)
bytes_avail = (ssize_t)size;
zip->pack_stream_bytes_unconsumed = bytes_avail;
} else if (zip->uncompressed_buffer_pointer == NULL) {
/* Decompression has failed. */
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive");
return (ARCHIVE_FATAL);
} else {
/* Packed mode. */
if (minimum > zip->uncompressed_buffer_bytes_remaining) {
/*
* If remaining uncompressed data size is less than
* the minimum size, fill the buffer up to the
* minimum size.
*/
if (extract_pack_stream(a, minimum) < 0)
return (ARCHIVE_FATAL);
}
if (size > zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
else
bytes_avail = (ssize_t)size;
*buff = zip->uncompressed_buffer_pointer;
zip->uncompressed_buffer_pointer += bytes_avail;
}
zip->uncompressed_buffer_bytes_remaining -= bytes_avail;
return (bytes_avail);
}
static ssize_t
extract_pack_stream(struct archive_read *a, size_t minimum)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
ssize_t bytes_avail;
int r;
if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {
if (minimum == 0)
minimum = 1;
if (__archive_read_ahead(a, minimum, &bytes_avail) == NULL
|| bytes_avail <= 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file body");
return (ARCHIVE_FATAL);
}
if (bytes_avail > (ssize_t)zip->pack_stream_inbytes_remaining)
bytes_avail = (ssize_t)zip->pack_stream_inbytes_remaining;
zip->pack_stream_inbytes_remaining -= bytes_avail;
if (bytes_avail > (ssize_t)zip->folder_outbytes_remaining)
bytes_avail = (ssize_t)zip->folder_outbytes_remaining;
zip->folder_outbytes_remaining -= bytes_avail;
zip->uncompressed_buffer_bytes_remaining = bytes_avail;
return (ARCHIVE_OK);
}
/* If the buffer hasn't been allocated, allocate it now. */
if (zip->uncompressed_buffer == NULL) {
zip->uncompressed_buffer_size = UBUFF_SIZE;
if (zip->uncompressed_buffer_size < minimum) {
zip->uncompressed_buffer_size = minimum + 1023;
zip->uncompressed_buffer_size &= ~0x3ff;
}
zip->uncompressed_buffer =
malloc(zip->uncompressed_buffer_size);
if (zip->uncompressed_buffer == NULL) {
archive_set_error(&a->archive, ENOMEM,
"No memory for 7-Zip decompression");
return (ARCHIVE_FATAL);
}
zip->uncompressed_buffer_bytes_remaining = 0;
} else if (zip->uncompressed_buffer_size < minimum ||
zip->uncompressed_buffer_bytes_remaining < minimum) {
/*
* Make sure the uncompressed buffer can have bytes
* at least `minimum' bytes.
* NOTE: This case happen when reading the header.
*/
size_t used;
if (zip->uncompressed_buffer_pointer != 0)
used = zip->uncompressed_buffer_pointer -
zip->uncompressed_buffer;
else
used = 0;
if (zip->uncompressed_buffer_size < minimum) {
/*
* Expand the uncompressed buffer up to
* the minimum size.
*/
void *p;
size_t new_size;
new_size = minimum + 1023;
new_size &= ~0x3ff;
p = realloc(zip->uncompressed_buffer, new_size);
if (p == NULL) {
archive_set_error(&a->archive, ENOMEM,
"No memory for 7-Zip decompression");
return (ARCHIVE_FATAL);
}
zip->uncompressed_buffer = (unsigned char *)p;
zip->uncompressed_buffer_size = new_size;
}
/*
* Move unconsumed bytes to the head.
*/
if (used) {
memmove(zip->uncompressed_buffer,
zip->uncompressed_buffer + used,
zip->uncompressed_buffer_bytes_remaining);
}
} else
zip->uncompressed_buffer_bytes_remaining = 0;
zip->uncompressed_buffer_pointer = NULL;
for (;;) {
size_t bytes_in, bytes_out;
const void *buff_in;
unsigned char *buff_out;
int end_of_data;
/*
* Note: '1' here is a performance optimization.
* Recall that the decompression layer returns a count of
* available bytes; asking for more than that forces the
* decompressor to combine reads by copying data.
*/
buff_in = __archive_read_ahead(a, 1, &bytes_avail);
if (bytes_avail <= 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file body");
return (ARCHIVE_FATAL);
}
buff_out = zip->uncompressed_buffer
+ zip->uncompressed_buffer_bytes_remaining;
bytes_out = zip->uncompressed_buffer_size
- zip->uncompressed_buffer_bytes_remaining;
bytes_in = bytes_avail;
if (bytes_in > zip->pack_stream_inbytes_remaining)
bytes_in = (size_t)zip->pack_stream_inbytes_remaining;
/* Drive decompression. */
r = decompress(a, zip, buff_out, &bytes_out,
buff_in, &bytes_in);
switch (r) {
case ARCHIVE_OK:
end_of_data = 0;
break;
case ARCHIVE_EOF:
end_of_data = 1;
break;
default:
return (ARCHIVE_FATAL);
}
zip->pack_stream_inbytes_remaining -= bytes_in;
if (bytes_out > zip->folder_outbytes_remaining)
bytes_out = (size_t)zip->folder_outbytes_remaining;
zip->folder_outbytes_remaining -= bytes_out;
zip->uncompressed_buffer_bytes_remaining += bytes_out;
zip->pack_stream_bytes_unconsumed = bytes_in;
/*
* Continue decompression until uncompressed_buffer is full.
*/
if (zip->uncompressed_buffer_bytes_remaining ==
zip->uncompressed_buffer_size)
break;
if (zip->codec2 == _7Z_X86 && zip->odd_bcj_size &&
zip->uncompressed_buffer_bytes_remaining + 5 >
zip->uncompressed_buffer_size)
break;
if (zip->pack_stream_inbytes_remaining == 0 &&
zip->folder_outbytes_remaining == 0)
break;
if (end_of_data || (bytes_in == 0 && bytes_out == 0)) {
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive");
return (ARCHIVE_FATAL);
}
read_consume(a);
}
if (zip->uncompressed_buffer_bytes_remaining < minimum) {
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive");
return (ARCHIVE_FATAL);
}
zip->uncompressed_buffer_pointer = zip->uncompressed_buffer;
return (ARCHIVE_OK);
}
static int
seek_pack(struct archive_read *a)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
int64_t pack_offset;
if (zip->pack_stream_remaining <= 0) {
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive");
return (ARCHIVE_FATAL);
}
zip->pack_stream_inbytes_remaining =
zip->si.pi.sizes[zip->pack_stream_index];
pack_offset = zip->si.pi.positions[zip->pack_stream_index];
if (zip->stream_offset != pack_offset) {
if (0 > __archive_read_seek(a, pack_offset + zip->seek_base,
SEEK_SET))
return (ARCHIVE_FATAL);
zip->stream_offset = pack_offset;
}
zip->pack_stream_index++;
zip->pack_stream_remaining--;
return (ARCHIVE_OK);
}
static ssize_t
read_stream(struct archive_read *a, const void **buff, size_t size,
size_t minimum)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
uint64_t skip_bytes = 0;
ssize_t r;
if (zip->uncompressed_buffer_bytes_remaining == 0) {
if (zip->pack_stream_inbytes_remaining > 0) {
r = extract_pack_stream(a, 0);
if (r < 0)
return (r);
return (get_uncompressed_data(a, buff, size, minimum));
} else if (zip->folder_outbytes_remaining > 0) {
/* Extract a remaining pack stream. */
r = extract_pack_stream(a, 0);
if (r < 0)
return (r);
return (get_uncompressed_data(a, buff, size, minimum));
}
} else
return (get_uncompressed_data(a, buff, size, minimum));
/*
* Current pack stream has been consumed.
*/
if (zip->pack_stream_remaining == 0) {
if (zip->header_is_being_read) {
/* Invalid sequence. This might happen when
* reading a malformed archive. */
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC, "Malformed 7-Zip archive");
return (ARCHIVE_FATAL);
}
/*
* All current folder's pack streams have been
* consumed. Switch to next folder.
*/
if (zip->folder_index == 0 &&
(zip->si.ci.folders[zip->entry->folderIndex].skipped_bytes
|| zip->folder_index != zip->entry->folderIndex)) {
zip->folder_index = zip->entry->folderIndex;
skip_bytes =
zip->si.ci.folders[zip->folder_index].skipped_bytes;
}
if (zip->folder_index >= zip->si.ci.numFolders) {
/*
* We have consumed all folders and its pack streams.
*/
*buff = NULL;
return (0);
}
r = setup_decode_folder(a,
&(zip->si.ci.folders[zip->folder_index]), 0);
if (r != ARCHIVE_OK)
return (ARCHIVE_FATAL);
zip->folder_index++;
}
/*
* Switch to next pack stream.
*/
r = seek_pack(a);
if (r < 0)
return (r);
/* Extract a new pack stream. */
r = extract_pack_stream(a, 0);
if (r < 0)
return (r);
/*
* Skip the bytes we already has skipped in skip_stream().
*/
while (skip_bytes) {
ssize_t skipped;
if (zip->uncompressed_buffer_bytes_remaining == 0) {
if (zip->pack_stream_inbytes_remaining > 0) {
r = extract_pack_stream(a, 0);
if (r < 0)
return (r);
} else if (zip->folder_outbytes_remaining > 0) {
/* Extract a remaining pack stream. */
r = extract_pack_stream(a, 0);
if (r < 0)
return (r);
} else {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file body");
return (ARCHIVE_FATAL);
}
}
skipped = get_uncompressed_data(
a, buff, (size_t)skip_bytes, 0);
if (skipped < 0)
return (skipped);
skip_bytes -= skipped;
if (zip->pack_stream_bytes_unconsumed)
read_consume(a);
}
return (get_uncompressed_data(a, buff, size, minimum));
}
static int
setup_decode_folder(struct archive_read *a, struct _7z_folder *folder,
int header)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
const struct _7z_coder *coder1, *coder2;
const char *cname = (header)?"archive header":"file content";
unsigned i;
int r, found_bcj2 = 0;
/*
* Release the memory which the previous folder used for BCJ2.
*/
for (i = 0; i < 3; i++) {
if (zip->sub_stream_buff[i] != NULL)
free(zip->sub_stream_buff[i]);
zip->sub_stream_buff[i] = NULL;
}
/*
* Initialize a stream reader.
*/
zip->pack_stream_remaining = (unsigned)folder->numPackedStreams;
zip->pack_stream_index = (unsigned)folder->packIndex;
zip->folder_outbytes_remaining = folder_uncompressed_size(folder);
zip->uncompressed_buffer_bytes_remaining = 0;
/*
* Check coder types.
*/
for (i = 0; i < folder->numCoders; i++) {
switch(folder->coders[i].codec) {
case _7Z_CRYPTO_MAIN_ZIP:
case _7Z_CRYPTO_RAR_29:
case _7Z_CRYPTO_AES_256_SHA_256: {
/* For entry that is associated with this folder, mark
it as encrypted (data+metadata). */
zip->has_encrypted_entries = 1;
if (a->entry) {
archive_entry_set_is_data_encrypted(a->entry, 1);
archive_entry_set_is_metadata_encrypted(a->entry, 1);
}
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC,
"The %s is encrypted, "
"but currently not supported", cname);
return (ARCHIVE_FATAL);
}
case _7Z_X86_BCJ2: {
found_bcj2++;
break;
}
}
}
/* Now that we've checked for encryption, if there were still no
* encrypted entries found we can say for sure that there are none.
*/
if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
zip->has_encrypted_entries = 0;
}
if ((folder->numCoders > 2 && !found_bcj2) || found_bcj2 > 1) {
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC,
"The %s is encoded with many filters, "
"but currently not supported", cname);
return (ARCHIVE_FATAL);
}
coder1 = &(folder->coders[0]);
if (folder->numCoders == 2)
coder2 = &(folder->coders[1]);
else
coder2 = NULL;
if (found_bcj2) {
/*
* Preparation to decode BCJ2.
* Decoding BCJ2 requires four sources. Those are at least,
* as far as I know, two types of the storage form.
*/
const struct _7z_coder *fc = folder->coders;
static const struct _7z_coder coder_copy = {0, 1, 1, 0, NULL};
const struct _7z_coder *scoder[3] =
{&coder_copy, &coder_copy, &coder_copy};
const void *buff;
ssize_t bytes;
unsigned char *b[3] = {NULL, NULL, NULL};
uint64_t sunpack[3] ={-1, -1, -1};
size_t s[3] = {0, 0, 0};
int idx[3] = {0, 1, 2};
if (folder->numCoders == 4 && fc[3].codec == _7Z_X86_BCJ2 &&
folder->numInStreams == 7 && folder->numOutStreams == 4 &&
zip->pack_stream_remaining == 4) {
/* Source type 1 made by 7zr or 7z with -m options. */
if (folder->bindPairs[0].inIndex == 5) {
/* The form made by 7zr */
idx[0] = 1; idx[1] = 2; idx[2] = 0;
scoder[1] = &(fc[1]);
scoder[2] = &(fc[0]);
sunpack[1] = folder->unPackSize[1];
sunpack[2] = folder->unPackSize[0];
coder1 = &(fc[2]);
} else {
/*
* NOTE: Some patterns do not work.
* work:
* 7z a -m0=BCJ2 -m1=COPY -m2=COPY
* -m3=(any)
* 7z a -m0=BCJ2 -m1=COPY -m2=(any)
* -m3=COPY
* 7z a -m0=BCJ2 -m1=(any) -m2=COPY
* -m3=COPY
* not work:
* other patterns.
*
* We have to handle this like `pipe' or
* our libarchive7s filter frame work,
* decoding the BCJ2 main stream sequentially,
* m3 -> m2 -> m1 -> BCJ2.
*
*/
if (fc[0].codec == _7Z_COPY &&
fc[1].codec == _7Z_COPY)
coder1 = &(folder->coders[2]);
else if (fc[0].codec == _7Z_COPY &&
fc[2].codec == _7Z_COPY)
coder1 = &(folder->coders[1]);
else if (fc[1].codec == _7Z_COPY &&
fc[2].codec == _7Z_COPY)
coder1 = &(folder->coders[0]);
else {
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC,
"Unsupported form of "
"BCJ2 streams");
return (ARCHIVE_FATAL);
}
}
coder2 = &(fc[3]);
zip->main_stream_bytes_remaining =
(size_t)folder->unPackSize[2];
} else if (coder2 != NULL && coder2->codec == _7Z_X86_BCJ2 &&
zip->pack_stream_remaining == 4 &&
folder->numInStreams == 5 && folder->numOutStreams == 2) {
/* Source type 0 made by 7z */
zip->main_stream_bytes_remaining =
(size_t)folder->unPackSize[0];
} else {
/* We got an unexpected form. */
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC,
"Unsupported form of BCJ2 streams");
return (ARCHIVE_FATAL);
}
/* Skip the main stream at this time. */
if ((r = seek_pack(a)) < 0)
return (r);
zip->pack_stream_bytes_unconsumed =
(size_t)zip->pack_stream_inbytes_remaining;
read_consume(a);
/* Read following three sub streams. */
for (i = 0; i < 3; i++) {
const struct _7z_coder *coder = scoder[i];
if ((r = seek_pack(a)) < 0) {
free(b[0]); free(b[1]); free(b[2]);
return (r);
}
if (sunpack[i] == (uint64_t)-1)
zip->folder_outbytes_remaining =
zip->pack_stream_inbytes_remaining;
else
zip->folder_outbytes_remaining = sunpack[i];
r = init_decompression(a, zip, coder, NULL);
if (r != ARCHIVE_OK) {
free(b[0]); free(b[1]); free(b[2]);
return (ARCHIVE_FATAL);
}
/* Allocate memory for the decoded data of a sub
* stream. */
b[i] = malloc((size_t)zip->folder_outbytes_remaining);
if (b[i] == NULL) {
free(b[0]); free(b[1]); free(b[2]);
archive_set_error(&a->archive, ENOMEM,
"No memory for 7-Zip decompression");
return (ARCHIVE_FATAL);
}
/* Extract a sub stream. */
while (zip->pack_stream_inbytes_remaining > 0) {
r = (int)extract_pack_stream(a, 0);
if (r < 0) {
free(b[0]); free(b[1]); free(b[2]);
return (r);
}
bytes = get_uncompressed_data(a, &buff,
zip->uncompressed_buffer_bytes_remaining,
0);
if (bytes < 0) {
free(b[0]); free(b[1]); free(b[2]);
return ((int)bytes);
}
memcpy(b[i]+s[i], buff, bytes);
s[i] += bytes;
if (zip->pack_stream_bytes_unconsumed)
read_consume(a);
}
}
/* Set the sub streams to the right place. */
for (i = 0; i < 3; i++) {
zip->sub_stream_buff[i] = b[idx[i]];
zip->sub_stream_size[i] = s[idx[i]];
zip->sub_stream_bytes_remaining[i] = s[idx[i]];
}
/* Allocate memory used for decoded main stream bytes. */
if (zip->tmp_stream_buff == NULL) {
zip->tmp_stream_buff_size = 32 * 1024;
zip->tmp_stream_buff =
malloc(zip->tmp_stream_buff_size);
if (zip->tmp_stream_buff == NULL) {
archive_set_error(&a->archive, ENOMEM,
"No memory for 7-Zip decompression");
return (ARCHIVE_FATAL);
}
}
zip->tmp_stream_bytes_avail = 0;
zip->tmp_stream_bytes_remaining = 0;
zip->odd_bcj_size = 0;
zip->bcj2_outPos = 0;
/*
* Reset a stream reader in order to read the main stream
* of BCJ2.
*/
zip->pack_stream_remaining = 1;
zip->pack_stream_index = (unsigned)folder->packIndex;
zip->folder_outbytes_remaining =
folder_uncompressed_size(folder);
zip->uncompressed_buffer_bytes_remaining = 0;
}
/*
* Initialize the decompressor for the new folder's pack streams.
*/
r = init_decompression(a, zip, coder1, coder2);
if (r != ARCHIVE_OK)
return (ARCHIVE_FATAL);
return (ARCHIVE_OK);
}
static int64_t
skip_stream(struct archive_read *a, size_t skip_bytes)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
const void *p;
int64_t skipped_bytes;
size_t bytes = skip_bytes;
if (zip->folder_index == 0) {
/*
* Optimization for a list mode.
* Avoid unnecessary decoding operations.
*/
zip->si.ci.folders[zip->entry->folderIndex].skipped_bytes
+= skip_bytes;
return (skip_bytes);
}
while (bytes) {
skipped_bytes = read_stream(a, &p, bytes, 0);
if (skipped_bytes < 0)
return (skipped_bytes);
if (skipped_bytes == 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file body");
return (ARCHIVE_FATAL);
}
bytes -= (size_t)skipped_bytes;
if (zip->pack_stream_bytes_unconsumed)
read_consume(a);
}
return (skip_bytes);
}
/*
* Brought from LZMA SDK.
*
* Bra86.c -- Converter for x86 code (BCJ)
* 2008-10-04 : Igor Pavlov : Public domain
*
*/
#define Test86MSByte(b) ((b) == 0 || (b) == 0xFF)
static void
x86_Init(struct _7zip *zip)
{
zip->bcj_state = 0;
zip->bcj_prevPosT = (size_t)0 - 1;
zip->bcj_prevMask = 0;
zip->bcj_ip = 5;
}
static size_t
x86_Convert(struct _7zip *zip, uint8_t *data, size_t size)
{
static const uint8_t kMaskToAllowedStatus[8] = {1, 1, 1, 0, 1, 0, 0, 0};
static const uint8_t kMaskToBitNumber[8] = {0, 1, 2, 2, 3, 3, 3, 3};
size_t bufferPos, prevPosT;
uint32_t ip, prevMask;
if (size < 5)
return 0;
bufferPos = 0;
prevPosT = zip->bcj_prevPosT;
prevMask = zip->bcj_prevMask;
ip = zip->bcj_ip;
for (;;) {
uint8_t *p = data + bufferPos;
uint8_t *limit = data + size - 4;
for (; p < limit; p++)
if ((*p & 0xFE) == 0xE8)
break;
bufferPos = (size_t)(p - data);
if (p >= limit)
break;
prevPosT = bufferPos - prevPosT;
if (prevPosT > 3)
prevMask = 0;
else {
prevMask = (prevMask << ((int)prevPosT - 1)) & 0x7;
if (prevMask != 0) {
unsigned char b =
p[4 - kMaskToBitNumber[prevMask]];
if (!kMaskToAllowedStatus[prevMask] ||
Test86MSByte(b)) {
prevPosT = bufferPos;
prevMask = ((prevMask << 1) & 0x7) | 1;
bufferPos++;
continue;
}
}
}
prevPosT = bufferPos;
if (Test86MSByte(p[4])) {
uint32_t src = ((uint32_t)p[4] << 24) |
((uint32_t)p[3] << 16) | ((uint32_t)p[2] << 8) |
((uint32_t)p[1]);
uint32_t dest;
for (;;) {
uint8_t b;
int b_index;
dest = src - (ip + (uint32_t)bufferPos);
if (prevMask == 0)
break;
b_index = kMaskToBitNumber[prevMask] * 8;
b = (uint8_t)(dest >> (24 - b_index));
if (!Test86MSByte(b))
break;
src = dest ^ ((1 << (32 - b_index)) - 1);
}
p[4] = (uint8_t)(~(((dest >> 24) & 1) - 1));
p[3] = (uint8_t)(dest >> 16);
p[2] = (uint8_t)(dest >> 8);
p[1] = (uint8_t)dest;
bufferPos += 5;
} else {
prevMask = ((prevMask << 1) & 0x7) | 1;
bufferPos++;
}
}
zip->bcj_prevPosT = prevPosT;
zip->bcj_prevMask = prevMask;
zip->bcj_ip += (uint32_t)bufferPos;
return (bufferPos);
}
/*
* Brought from LZMA SDK.
*
* Bcj2.c -- Converter for x86 code (BCJ2)
* 2008-10-04 : Igor Pavlov : Public domain
*
*/
#define SZ_ERROR_DATA ARCHIVE_FAILED
#define IsJcc(b0, b1) ((b0) == 0x0F && ((b1) & 0xF0) == 0x80)
#define IsJ(b0, b1) ((b1 & 0xFE) == 0xE8 || IsJcc(b0, b1))
#define kNumTopBits 24
#define kTopValue ((uint32_t)1 << kNumTopBits)
#define kNumBitModelTotalBits 11
#define kBitModelTotal (1 << kNumBitModelTotalBits)
#define kNumMoveBits 5
#define RC_READ_BYTE (*buffer++)
#define RC_TEST { if (buffer == bufferLim) return SZ_ERROR_DATA; }
#define RC_INIT2 zip->bcj2_code = 0; zip->bcj2_range = 0xFFFFFFFF; \
{ int ii; for (ii = 0; ii < 5; ii++) { RC_TEST; zip->bcj2_code = (zip->bcj2_code << 8) | RC_READ_BYTE; }}
#define NORMALIZE if (zip->bcj2_range < kTopValue) { RC_TEST; zip->bcj2_range <<= 8; zip->bcj2_code = (zip->bcj2_code << 8) | RC_READ_BYTE; }
#define IF_BIT_0(p) ttt = *(p); bound = (zip->bcj2_range >> kNumBitModelTotalBits) * ttt; if (zip->bcj2_code < bound)
#define UPDATE_0(p) zip->bcj2_range = bound; *(p) = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); NORMALIZE;
#define UPDATE_1(p) zip->bcj2_range -= bound; zip->bcj2_code -= bound; *(p) = (CProb)(ttt - (ttt >> kNumMoveBits)); NORMALIZE;
static ssize_t
Bcj2_Decode(struct _7zip *zip, uint8_t *outBuf, size_t outSize)
{
size_t inPos = 0, outPos = 0;
const uint8_t *buf0, *buf1, *buf2, *buf3;
size_t size0, size1, size2, size3;
const uint8_t *buffer, *bufferLim;
unsigned int i, j;
size0 = zip->tmp_stream_bytes_remaining;
buf0 = zip->tmp_stream_buff + zip->tmp_stream_bytes_avail - size0;
size1 = zip->sub_stream_bytes_remaining[0];
buf1 = zip->sub_stream_buff[0] + zip->sub_stream_size[0] - size1;
size2 = zip->sub_stream_bytes_remaining[1];
buf2 = zip->sub_stream_buff[1] + zip->sub_stream_size[1] - size2;
size3 = zip->sub_stream_bytes_remaining[2];
buf3 = zip->sub_stream_buff[2] + zip->sub_stream_size[2] - size3;
buffer = buf3;
bufferLim = buffer + size3;
if (zip->bcj_state == 0) {
/*
* Initialize.
*/
zip->bcj2_prevByte = 0;
for (i = 0;
i < sizeof(zip->bcj2_p) / sizeof(zip->bcj2_p[0]); i++)
zip->bcj2_p[i] = kBitModelTotal >> 1;
RC_INIT2;
zip->bcj_state = 1;
}
/*
* Gather the odd bytes of a previous call.
*/
for (i = 0; zip->odd_bcj_size > 0 && outPos < outSize; i++) {
outBuf[outPos++] = zip->odd_bcj[i];
zip->odd_bcj_size--;
}
if (outSize == 0) {
zip->bcj2_outPos += outPos;
return (outPos);
}
for (;;) {
uint8_t b;
CProb *prob;
uint32_t bound;
uint32_t ttt;
size_t limit = size0 - inPos;
if (outSize - outPos < limit)
limit = outSize - outPos;
if (zip->bcj_state == 1) {
while (limit != 0) {
uint8_t bb = buf0[inPos];
outBuf[outPos++] = bb;
if (IsJ(zip->bcj2_prevByte, bb)) {
zip->bcj_state = 2;
break;
}
inPos++;
zip->bcj2_prevByte = bb;
limit--;
}
}
if (limit == 0 || outPos == outSize)
break;
zip->bcj_state = 1;
b = buf0[inPos++];
if (b == 0xE8)
prob = zip->bcj2_p + zip->bcj2_prevByte;
else if (b == 0xE9)
prob = zip->bcj2_p + 256;
else
prob = zip->bcj2_p + 257;
IF_BIT_0(prob) {
UPDATE_0(prob)
zip->bcj2_prevByte = b;
} else {
uint32_t dest;
const uint8_t *v;
uint8_t out[4];
UPDATE_1(prob)
if (b == 0xE8) {
v = buf1;
if (size1 < 4)
return SZ_ERROR_DATA;
buf1 += 4;
size1 -= 4;
} else {
v = buf2;
if (size2 < 4)
return SZ_ERROR_DATA;
buf2 += 4;
size2 -= 4;
}
dest = (((uint32_t)v[0] << 24) |
((uint32_t)v[1] << 16) |
((uint32_t)v[2] << 8) |
((uint32_t)v[3])) -
((uint32_t)zip->bcj2_outPos + (uint32_t)outPos + 4);
out[0] = (uint8_t)dest;
out[1] = (uint8_t)(dest >> 8);
out[2] = (uint8_t)(dest >> 16);
out[3] = zip->bcj2_prevByte = (uint8_t)(dest >> 24);
for (i = 0; i < 4 && outPos < outSize; i++)
outBuf[outPos++] = out[i];
if (i < 4) {
/*
* Save odd bytes which we could not add into
* the output buffer because of out of space.
*/
zip->odd_bcj_size = 4 -i;
for (; i < 4; i++) {
j = i - 4 + (unsigned)zip->odd_bcj_size;
zip->odd_bcj[j] = out[i];
}
break;
}
}
}
zip->tmp_stream_bytes_remaining -= inPos;
zip->sub_stream_bytes_remaining[0] = size1;
zip->sub_stream_bytes_remaining[1] = size2;
zip->sub_stream_bytes_remaining[2] = bufferLim - buffer;
zip->bcj2_outPos += outPos;
return ((ssize_t)outPos);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_706_0 |
crossvul-cpp_data_good_3909_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Auto-Detect PDUs
*
* Copyright 2014 Dell Software <Mike.McDonald@software.dell.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/crypto.h>
#include "autodetect.h"
#define RDP_RTT_REQUEST_TYPE_CONTINUOUS 0x0001
#define RDP_RTT_REQUEST_TYPE_CONNECTTIME 0x1001
#define RDP_RTT_RESPONSE_TYPE 0x0000
#define RDP_BW_START_REQUEST_TYPE_CONTINUOUS 0x0014
#define RDP_BW_START_REQUEST_TYPE_TUNNEL 0x0114
#define RDP_BW_START_REQUEST_TYPE_CONNECTTIME 0x1014
#define RDP_BW_PAYLOAD_REQUEST_TYPE 0x0002
#define RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME 0x002B
#define RDP_BW_STOP_REQUEST_TYPE_CONTINUOUS 0x0429
#define RDP_BW_STOP_REQUEST_TYPE_TUNNEL 0x0629
#define RDP_BW_RESULTS_RESPONSE_TYPE_CONNECTTIME 0x0003
#define RDP_BW_RESULTS_RESPONSE_TYPE_CONTINUOUS 0x000B
#define RDP_NETCHAR_SYNC_RESPONSE_TYPE 0x0018
typedef struct
{
UINT8 headerLength;
UINT8 headerTypeId;
UINT16 sequenceNumber;
UINT16 requestType;
} AUTODETECT_REQ_PDU;
typedef struct
{
UINT8 headerLength;
UINT8 headerTypeId;
UINT16 sequenceNumber;
UINT16 responseType;
} AUTODETECT_RSP_PDU;
static BOOL autodetect_send_rtt_measure_request(rdpContext* context, UINT16 sequenceNumber,
UINT16 requestType)
{
wStream* s;
s = rdp_message_channel_pdu_init(context->rdp);
if (!s)
return FALSE;
WLog_VRB(AUTODETECT_TAG, "sending RTT Measure Request PDU");
Stream_Write_UINT8(s, 0x06); /* headerLength (1 byte) */
Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */
Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */
Stream_Write_UINT16(s, requestType); /* requestType (2 bytes) */
context->rdp->autodetect->rttMeasureStartTime = GetTickCount64();
return rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ);
}
static BOOL autodetect_send_continuous_rtt_measure_request(rdpContext* context,
UINT16 sequenceNumber)
{
return autodetect_send_rtt_measure_request(context, sequenceNumber,
RDP_RTT_REQUEST_TYPE_CONTINUOUS);
}
BOOL autodetect_send_connecttime_rtt_measure_request(rdpContext* context, UINT16 sequenceNumber)
{
return autodetect_send_rtt_measure_request(context, sequenceNumber,
RDP_RTT_REQUEST_TYPE_CONNECTTIME);
}
static BOOL autodetect_send_rtt_measure_response(rdpRdp* rdp, UINT16 sequenceNumber)
{
wStream* s;
/* Send the response PDU to the server */
s = rdp_message_channel_pdu_init(rdp);
if (!s)
return FALSE;
WLog_VRB(AUTODETECT_TAG, "sending RTT Measure Response PDU");
Stream_Write_UINT8(s, 0x06); /* headerLength (1 byte) */
Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_RESPONSE); /* headerTypeId (1 byte) */
Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */
Stream_Write_UINT16(s, RDP_RTT_RESPONSE_TYPE); /* responseType (1 byte) */
return rdp_send_message_channel_pdu(rdp, s, SEC_AUTODETECT_RSP);
}
static BOOL autodetect_send_bandwidth_measure_start(rdpContext* context, UINT16 sequenceNumber,
UINT16 requestType)
{
wStream* s;
s = rdp_message_channel_pdu_init(context->rdp);
if (!s)
return FALSE;
WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Measure Start PDU");
Stream_Write_UINT8(s, 0x06); /* headerLength (1 byte) */
Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */
Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */
Stream_Write_UINT16(s, requestType); /* requestType (2 bytes) */
return rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ);
}
static BOOL autodetect_send_continuous_bandwidth_measure_start(rdpContext* context,
UINT16 sequenceNumber)
{
return autodetect_send_bandwidth_measure_start(context, sequenceNumber,
RDP_BW_START_REQUEST_TYPE_CONTINUOUS);
}
BOOL autodetect_send_connecttime_bandwidth_measure_start(rdpContext* context, UINT16 sequenceNumber)
{
return autodetect_send_bandwidth_measure_start(context, sequenceNumber,
RDP_BW_START_REQUEST_TYPE_CONNECTTIME);
}
BOOL autodetect_send_bandwidth_measure_payload(rdpContext* context, UINT16 payloadLength,
UINT16 sequenceNumber)
{
wStream* s;
UCHAR* buffer = NULL;
BOOL bResult = FALSE;
s = rdp_message_channel_pdu_init(context->rdp);
if (!s)
return FALSE;
WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Measure Payload PDU -> payloadLength=%" PRIu16 "",
payloadLength);
/* 4-bytes aligned */
payloadLength &= ~3;
if (!Stream_EnsureRemainingCapacity(s, 8 + payloadLength))
{
Stream_Release(s);
return FALSE;
}
Stream_Write_UINT8(s, 0x08); /* headerLength (1 byte) */
Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */
Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */
Stream_Write_UINT16(s, RDP_BW_PAYLOAD_REQUEST_TYPE); /* requestType (2 bytes) */
Stream_Write_UINT16(s, payloadLength); /* payloadLength (2 bytes) */
/* Random data (better measurement in case the line is compressed) */
buffer = (UCHAR*)malloc(payloadLength);
if (NULL == buffer)
{
Stream_Release(s);
return FALSE;
}
winpr_RAND(buffer, payloadLength);
Stream_Write(s, buffer, payloadLength);
bResult = rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ);
free(buffer);
return bResult;
}
static BOOL autodetect_send_bandwidth_measure_stop(rdpContext* context, UINT16 payloadLength,
UINT16 sequenceNumber, UINT16 requestType)
{
wStream* s;
UCHAR* buffer = NULL;
BOOL bResult = FALSE;
s = rdp_message_channel_pdu_init(context->rdp);
if (!s)
return FALSE;
WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Measure Stop PDU -> payloadLength=%" PRIu16 "",
payloadLength);
/* 4-bytes aligned */
payloadLength &= ~3;
Stream_Write_UINT8(s, requestType == RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME
? 0x08
: 0x06); /* headerLength (1 byte) */
Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */
Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */
Stream_Write_UINT16(s, requestType); /* requestType (2 bytes) */
if (requestType == RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME)
{
Stream_Write_UINT16(s, payloadLength); /* payloadLength (2 bytes) */
if (payloadLength > 0)
{
if (!Stream_EnsureRemainingCapacity(s, payloadLength))
{
Stream_Release(s);
return FALSE;
}
/* Random data (better measurement in case the line is compressed) */
buffer = malloc(payloadLength);
if (NULL == buffer)
{
Stream_Release(s);
return FALSE;
}
winpr_RAND(buffer, payloadLength);
Stream_Write(s, buffer, payloadLength);
}
}
bResult = rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ);
free(buffer);
return bResult;
}
static BOOL autodetect_send_continuous_bandwidth_measure_stop(rdpContext* context,
UINT16 sequenceNumber)
{
return autodetect_send_bandwidth_measure_stop(context, 0, sequenceNumber,
RDP_BW_STOP_REQUEST_TYPE_CONTINUOUS);
}
BOOL autodetect_send_connecttime_bandwidth_measure_stop(rdpContext* context, UINT16 payloadLength,
UINT16 sequenceNumber)
{
return autodetect_send_bandwidth_measure_stop(context, payloadLength, sequenceNumber,
RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME);
}
static BOOL autodetect_send_bandwidth_measure_results(rdpRdp* rdp, UINT16 responseType,
UINT16 sequenceNumber)
{
BOOL success = TRUE;
wStream* s;
UINT64 timeDelta;
/* Compute the total time */
timeDelta = GetTickCount64() - rdp->autodetect->bandwidthMeasureStartTime;
/* Send the result PDU to the server */
s = rdp_message_channel_pdu_init(rdp);
if (!s)
return FALSE;
WLog_VRB(AUTODETECT_TAG,
"sending Bandwidth Measure Results PDU -> timeDelta=%" PRIu32 ", byteCount=%" PRIu32
"",
timeDelta, rdp->autodetect->bandwidthMeasureByteCount);
Stream_Write_UINT8(s, 0x0E); /* headerLength (1 byte) */
Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_RESPONSE); /* headerTypeId (1 byte) */
Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */
Stream_Write_UINT16(s, responseType); /* responseType (1 byte) */
Stream_Write_UINT32(s, timeDelta); /* timeDelta (4 bytes) */
Stream_Write_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */
IFCALLRET(rdp->autodetect->ClientBandwidthMeasureResult, success, rdp->context,
rdp->autodetect);
if (!success)
return FALSE;
return rdp_send_message_channel_pdu(rdp, s, SEC_AUTODETECT_RSP);
}
static BOOL autodetect_send_netchar_result(rdpContext* context, UINT16 sequenceNumber)
{
wStream* s;
s = rdp_message_channel_pdu_init(context->rdp);
if (!s)
return FALSE;
WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Network Characteristics Result PDU");
if (context->rdp->autodetect->netCharBandwidth > 0)
{
Stream_Write_UINT8(s, 0x12); /* headerLength (1 byte) */
Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */
Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */
Stream_Write_UINT16(s, 0x08C0); /* requestType (2 bytes) */
Stream_Write_UINT32(s, context->rdp->autodetect->netCharBaseRTT); /* baseRTT (4 bytes) */
Stream_Write_UINT32(s,
context->rdp->autodetect->netCharBandwidth); /* bandwidth (4 bytes) */
Stream_Write_UINT32(s,
context->rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */
}
else
{
Stream_Write_UINT8(s, 0x0E); /* headerLength (1 byte) */
Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */
Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */
Stream_Write_UINT16(s, 0x0840); /* requestType (2 bytes) */
Stream_Write_UINT32(s, context->rdp->autodetect->netCharBaseRTT); /* baseRTT (4 bytes) */
Stream_Write_UINT32(s,
context->rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */
}
return rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ);
}
static BOOL autodetect_send_netchar_sync(rdpRdp* rdp, UINT16 sequenceNumber)
{
wStream* s;
/* Send the response PDU to the server */
s = rdp_message_channel_pdu_init(rdp);
if (!s)
return FALSE;
WLog_VRB(AUTODETECT_TAG,
"sending Network Characteristics Sync PDU -> bandwidth=%" PRIu32 ", rtt=%" PRIu32 "",
rdp->autodetect->netCharBandwidth, rdp->autodetect->netCharAverageRTT);
Stream_Write_UINT8(s, 0x0E); /* headerLength (1 byte) */
Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_RESPONSE); /* headerTypeId (1 byte) */
Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */
Stream_Write_UINT16(s, RDP_NETCHAR_SYNC_RESPONSE_TYPE); /* responseType (1 byte) */
Stream_Write_UINT32(s, rdp->autodetect->netCharBandwidth); /* bandwidth (4 bytes) */
Stream_Write_UINT32(s, rdp->autodetect->netCharAverageRTT); /* rtt (4 bytes) */
return rdp_send_message_channel_pdu(rdp, s, SEC_AUTODETECT_RSP);
}
static BOOL autodetect_recv_rtt_measure_request(rdpRdp* rdp, wStream* s,
AUTODETECT_REQ_PDU* autodetectReqPdu)
{
if (autodetectReqPdu->headerLength != 0x06)
return FALSE;
WLog_VRB(AUTODETECT_TAG, "received RTT Measure Request PDU");
/* Send a response to the server */
return autodetect_send_rtt_measure_response(rdp, autodetectReqPdu->sequenceNumber);
}
static BOOL autodetect_recv_rtt_measure_response(rdpRdp* rdp, wStream* s,
AUTODETECT_RSP_PDU* autodetectRspPdu)
{
BOOL success = TRUE;
if (autodetectRspPdu->headerLength != 0x06)
return FALSE;
WLog_VRB(AUTODETECT_TAG, "received RTT Measure Response PDU");
rdp->autodetect->netCharAverageRTT = GetTickCount64() - rdp->autodetect->rttMeasureStartTime;
if (rdp->autodetect->netCharBaseRTT == 0 ||
rdp->autodetect->netCharBaseRTT > rdp->autodetect->netCharAverageRTT)
rdp->autodetect->netCharBaseRTT = rdp->autodetect->netCharAverageRTT;
IFCALLRET(rdp->autodetect->RTTMeasureResponse, success, rdp->context,
autodetectRspPdu->sequenceNumber);
return success;
}
static BOOL autodetect_recv_bandwidth_measure_start(rdpRdp* rdp, wStream* s,
AUTODETECT_REQ_PDU* autodetectReqPdu)
{
if (autodetectReqPdu->headerLength != 0x06)
return FALSE;
WLog_VRB(AUTODETECT_TAG, "received Bandwidth Measure Start PDU - time=%" PRIu64 "",
GetTickCount64());
/* Initialize bandwidth measurement parameters */
rdp->autodetect->bandwidthMeasureStartTime = GetTickCount64();
rdp->autodetect->bandwidthMeasureByteCount = 0;
/* Continuous Auto-Detection: mark the start of the measurement */
if (autodetectReqPdu->requestType == RDP_BW_START_REQUEST_TYPE_CONTINUOUS)
{
rdp->autodetect->bandwidthMeasureStarted = TRUE;
}
return TRUE;
}
static BOOL autodetect_recv_bandwidth_measure_payload(rdpRdp* rdp, wStream* s,
AUTODETECT_REQ_PDU* autodetectReqPdu)
{
UINT16 payloadLength;
if (autodetectReqPdu->headerLength != 0x08)
return FALSE;
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, payloadLength); /* payloadLength (2 bytes) */
if (!Stream_SafeSeek(s, payloadLength))
return FALSE;
WLog_DBG(AUTODETECT_TAG, "received Bandwidth Measure Payload PDU -> payloadLength=%" PRIu16 "",
payloadLength);
/* Add the payload length to the bandwidth measurement parameters */
rdp->autodetect->bandwidthMeasureByteCount += payloadLength;
return TRUE;
}
static BOOL autodetect_recv_bandwidth_measure_stop(rdpRdp* rdp, wStream* s,
AUTODETECT_REQ_PDU* autodetectReqPdu)
{
UINT16 payloadLength;
UINT16 responseType;
if (autodetectReqPdu->requestType == RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME)
{
if (autodetectReqPdu->headerLength != 0x08)
return FALSE;
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, payloadLength); /* payloadLength (2 bytes) */
}
else
{
if (autodetectReqPdu->headerLength != 0x06)
return FALSE;
payloadLength = 0;
}
if (!Stream_SafeSeek(s, payloadLength))
return FALSE;
WLog_VRB(AUTODETECT_TAG, "received Bandwidth Measure Stop PDU -> payloadLength=%" PRIu16 "",
payloadLength);
/* Add the payload length to the bandwidth measurement parameters */
rdp->autodetect->bandwidthMeasureByteCount += payloadLength;
/* Continuous Auto-Detection: mark the stop of the measurement */
if (autodetectReqPdu->requestType == RDP_BW_STOP_REQUEST_TYPE_CONTINUOUS)
{
rdp->autodetect->bandwidthMeasureStarted = FALSE;
}
/* Send a response the server */
responseType = autodetectReqPdu->requestType == RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME
? RDP_BW_RESULTS_RESPONSE_TYPE_CONNECTTIME
: RDP_BW_RESULTS_RESPONSE_TYPE_CONTINUOUS;
return autodetect_send_bandwidth_measure_results(rdp, responseType,
autodetectReqPdu->sequenceNumber);
}
static BOOL autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s,
AUTODETECT_RSP_PDU* autodetectRspPdu)
{
BOOL success = TRUE;
if (autodetectRspPdu->headerLength != 0x0E)
return FALSE;
WLog_VRB(AUTODETECT_TAG, "received Bandwidth Measure Results PDU");
if (Stream_GetRemainingLength(s) < 8)
return -1;
Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */
Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */
if (rdp->autodetect->bandwidthMeasureTimeDelta > 0)
rdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 /
rdp->autodetect->bandwidthMeasureTimeDelta;
else
rdp->autodetect->netCharBandwidth = 0;
IFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context,
autodetectRspPdu->sequenceNumber);
return success;
}
static BOOL autodetect_recv_netchar_result(rdpRdp* rdp, wStream* s,
AUTODETECT_REQ_PDU* autodetectReqPdu)
{
BOOL success = TRUE;
switch (autodetectReqPdu->requestType)
{
case 0x0840:
/* baseRTT and averageRTT fields are present (bandwidth field is not) */
if ((autodetectReqPdu->headerLength != 0x0E) || (Stream_GetRemainingLength(s) < 8))
return FALSE;
Stream_Read_UINT32(s, rdp->autodetect->netCharBaseRTT); /* baseRTT (4 bytes) */
Stream_Read_UINT32(s, rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */
break;
case 0x0880:
/* bandwidth and averageRTT fields are present (baseRTT field is not) */
if ((autodetectReqPdu->headerLength != 0x0E) || (Stream_GetRemainingLength(s) < 8))
return FALSE;
Stream_Read_UINT32(s, rdp->autodetect->netCharBandwidth); /* bandwidth (4 bytes) */
Stream_Read_UINT32(s, rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */
break;
case 0x08C0:
/* baseRTT, bandwidth, and averageRTT fields are present */
if ((autodetectReqPdu->headerLength != 0x12) || (Stream_GetRemainingLength(s) < 12))
return FALSE;
Stream_Read_UINT32(s, rdp->autodetect->netCharBaseRTT); /* baseRTT (4 bytes) */
Stream_Read_UINT32(s, rdp->autodetect->netCharBandwidth); /* bandwidth (4 bytes) */
Stream_Read_UINT32(s, rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */
break;
}
WLog_VRB(AUTODETECT_TAG,
"received Network Characteristics Result PDU -> baseRTT=%" PRIu32
", bandwidth=%" PRIu32 ", averageRTT=%" PRIu32 "",
rdp->autodetect->netCharBaseRTT, rdp->autodetect->netCharBandwidth,
rdp->autodetect->netCharAverageRTT);
IFCALLRET(rdp->autodetect->NetworkCharacteristicsResult, success, rdp->context,
autodetectReqPdu->sequenceNumber);
return success;
}
int rdp_recv_autodetect_request_packet(rdpRdp* rdp, wStream* s)
{
AUTODETECT_REQ_PDU autodetectReqPdu;
BOOL success = FALSE;
if (Stream_GetRemainingLength(s) < 6)
return -1;
Stream_Read_UINT8(s, autodetectReqPdu.headerLength); /* headerLength (1 byte) */
Stream_Read_UINT8(s, autodetectReqPdu.headerTypeId); /* headerTypeId (1 byte) */
Stream_Read_UINT16(s, autodetectReqPdu.sequenceNumber); /* sequenceNumber (2 bytes) */
Stream_Read_UINT16(s, autodetectReqPdu.requestType); /* requestType (2 bytes) */
WLog_VRB(AUTODETECT_TAG,
"rdp_recv_autodetect_request_packet: headerLength=%" PRIu8 ", headerTypeId=%" PRIu8
", sequenceNumber=%" PRIu16 ", requestType=%04" PRIx16 "",
autodetectReqPdu.headerLength, autodetectReqPdu.headerTypeId,
autodetectReqPdu.sequenceNumber, autodetectReqPdu.requestType);
if (autodetectReqPdu.headerTypeId != TYPE_ID_AUTODETECT_REQUEST)
return -1;
switch (autodetectReqPdu.requestType)
{
case RDP_RTT_REQUEST_TYPE_CONTINUOUS:
case RDP_RTT_REQUEST_TYPE_CONNECTTIME:
/* RTT Measure Request (RDP_RTT_REQUEST) - MS-RDPBCGR 2.2.14.1.1 */
success = autodetect_recv_rtt_measure_request(rdp, s, &autodetectReqPdu);
break;
case RDP_BW_START_REQUEST_TYPE_CONTINUOUS:
case RDP_BW_START_REQUEST_TYPE_TUNNEL:
case RDP_BW_START_REQUEST_TYPE_CONNECTTIME:
/* Bandwidth Measure Start (RDP_BW_START) - MS-RDPBCGR 2.2.14.1.2 */
success = autodetect_recv_bandwidth_measure_start(rdp, s, &autodetectReqPdu);
break;
case RDP_BW_PAYLOAD_REQUEST_TYPE:
/* Bandwidth Measure Payload (RDP_BW_PAYLOAD) - MS-RDPBCGR 2.2.14.1.3 */
success = autodetect_recv_bandwidth_measure_payload(rdp, s, &autodetectReqPdu);
break;
case RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME:
case RDP_BW_STOP_REQUEST_TYPE_CONTINUOUS:
case RDP_BW_STOP_REQUEST_TYPE_TUNNEL:
/* Bandwidth Measure Stop (RDP_BW_STOP) - MS-RDPBCGR 2.2.14.1.4 */
success = autodetect_recv_bandwidth_measure_stop(rdp, s, &autodetectReqPdu);
break;
case 0x0840:
case 0x0880:
case 0x08C0:
/* Network Characteristics Result (RDP_NETCHAR_RESULT) - MS-RDPBCGR 2.2.14.1.5 */
success = autodetect_recv_netchar_result(rdp, s, &autodetectReqPdu);
break;
default:
break;
}
return success ? 0 : -1;
}
int rdp_recv_autodetect_response_packet(rdpRdp* rdp, wStream* s)
{
AUTODETECT_RSP_PDU autodetectRspPdu;
BOOL success = FALSE;
if (Stream_GetRemainingLength(s) < 6)
return -1;
Stream_Read_UINT8(s, autodetectRspPdu.headerLength); /* headerLength (1 byte) */
Stream_Read_UINT8(s, autodetectRspPdu.headerTypeId); /* headerTypeId (1 byte) */
Stream_Read_UINT16(s, autodetectRspPdu.sequenceNumber); /* sequenceNumber (2 bytes) */
Stream_Read_UINT16(s, autodetectRspPdu.responseType); /* responseType (2 bytes) */
WLog_VRB(AUTODETECT_TAG,
"rdp_recv_autodetect_response_packet: headerLength=%" PRIu8 ", headerTypeId=%" PRIu8
", sequenceNumber=%" PRIu16 ", requestType=%04" PRIx16 "",
autodetectRspPdu.headerLength, autodetectRspPdu.headerTypeId,
autodetectRspPdu.sequenceNumber, autodetectRspPdu.responseType);
if (autodetectRspPdu.headerTypeId != TYPE_ID_AUTODETECT_RESPONSE)
return -1;
switch (autodetectRspPdu.responseType)
{
case RDP_RTT_RESPONSE_TYPE:
/* RTT Measure Response (RDP_RTT_RESPONSE) - MS-RDPBCGR 2.2.14.2.1 */
success = autodetect_recv_rtt_measure_response(rdp, s, &autodetectRspPdu);
break;
case RDP_BW_RESULTS_RESPONSE_TYPE_CONNECTTIME:
case RDP_BW_RESULTS_RESPONSE_TYPE_CONTINUOUS:
/* Bandwidth Measure Results (RDP_BW_RESULTS) - MS-RDPBCGR 2.2.14.2.2 */
success = autodetect_recv_bandwidth_measure_results(rdp, s, &autodetectRspPdu);
break;
default:
break;
}
return success ? 0 : -1;
}
rdpAutoDetect* autodetect_new(void)
{
rdpAutoDetect* autoDetect = (rdpAutoDetect*)calloc(1, sizeof(rdpAutoDetect));
if (autoDetect)
{
}
return autoDetect;
}
void autodetect_free(rdpAutoDetect* autoDetect)
{
free(autoDetect);
}
void autodetect_register_server_callbacks(rdpAutoDetect* autodetect)
{
autodetect->RTTMeasureRequest = autodetect_send_continuous_rtt_measure_request;
autodetect->BandwidthMeasureStart = autodetect_send_continuous_bandwidth_measure_start;
autodetect->BandwidthMeasureStop = autodetect_send_continuous_bandwidth_measure_stop;
autodetect->NetworkCharacteristicsResult = autodetect_send_netchar_result;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3909_0 |
crossvul-cpp_data_bad_3207_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);
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: %li\n", *((long*)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/bad_3207_0 |
crossvul-cpp_data_good_4856_2 | /* $Id$ */
/*
* Copyright (c) 1996-1997 Sam Leffler
* Copyright (c) 1996 Pixar
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Pixar, Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Pixar, Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL PIXAR, SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
#include "tiffiop.h"
#ifdef PIXARLOG_SUPPORT
/*
* TIFF Library.
* PixarLog Compression Support
*
* Contributed by Dan McCoy.
*
* PixarLog film support uses the TIFF library to store companded
* 11 bit values into a tiff file, which are compressed using the
* zip compressor.
*
* The codec can take as input and produce as output 32-bit IEEE float values
* as well as 16-bit or 8-bit unsigned integer values.
*
* On writing any of the above are converted into the internal
* 11-bit log format. In the case of 8 and 16 bit values, the
* input is assumed to be unsigned linear color values that represent
* the range 0-1. In the case of IEEE values, the 0-1 range is assumed to
* be the normal linear color range, in addition over 1 values are
* accepted up to a value of about 25.0 to encode "hot" highlights and such.
* The encoding is lossless for 8-bit values, slightly lossy for the
* other bit depths. The actual color precision should be better
* than the human eye can perceive with extra room to allow for
* error introduced by further image computation. As with any quantized
* color format, it is possible to perform image calculations which
* expose the quantization error. This format should certainly be less
* susceptible to such errors than standard 8-bit encodings, but more
* susceptible than straight 16-bit or 32-bit encodings.
*
* On reading the internal format is converted to the desired output format.
* The program can request which format it desires by setting the internal
* pseudo tag TIFFTAG_PIXARLOGDATAFMT to one of these possible values:
* PIXARLOGDATAFMT_FLOAT = provide IEEE float values.
* PIXARLOGDATAFMT_16BIT = provide unsigned 16-bit integer values
* PIXARLOGDATAFMT_8BIT = provide unsigned 8-bit integer values
*
* alternately PIXARLOGDATAFMT_8BITABGR provides unsigned 8-bit integer
* values with the difference that if there are exactly three or four channels
* (rgb or rgba) it swaps the channel order (bgr or abgr).
*
* PIXARLOGDATAFMT_11BITLOG provides the internal encoding directly
* packed in 16-bit values. However no tools are supplied for interpreting
* these values.
*
* "hot" (over 1.0) areas written in floating point get clamped to
* 1.0 in the integer data types.
*
* When the file is closed after writing, the bit depth and sample format
* are set always to appear as if 8-bit data has been written into it.
* That way a naive program unaware of the particulars of the encoding
* gets the format it is most likely able to handle.
*
* The codec does it's own horizontal differencing step on the coded
* values so the libraries predictor stuff should be turned off.
* The codec also handle byte swapping the encoded values as necessary
* since the library does not have the information necessary
* to know the bit depth of the raw unencoded buffer.
*
* NOTE: This decoder does not appear to update tif_rawcp, and tif_rawcc.
* This can cause problems with the implementation of CHUNKY_STRIP_READ_SUPPORT
* as noted in http://trac.osgeo.org/gdal/ticket/3894. FrankW - Jan'11
*/
#include "tif_predict.h"
#include "zlib.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Tables for converting to/from 11 bit coded values */
#define TSIZE 2048 /* decode table size (11-bit tokens) */
#define TSIZEP1 2049 /* Plus one for slop */
#define ONE 1250 /* token value of 1.0 exactly */
#define RATIO 1.004 /* nominal ratio for log part */
#define CODE_MASK 0x7ff /* 11 bits. */
static float Fltsize;
static float LogK1, LogK2;
#define REPEAT(n, op) { int i; i=n; do { i--; op; } while (i>0); }
static void
horizontalAccumulateF(uint16 *wp, int n, int stride, float *op,
float *ToLinearF)
{
register unsigned int cr, cg, cb, ca, mask;
register float t0, t1, t2, t3;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
t0 = ToLinearF[cr = (wp[0] & mask)];
t1 = ToLinearF[cg = (wp[1] & mask)];
t2 = ToLinearF[cb = (wp[2] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
t0 = ToLinearF[(cr += wp[0]) & mask];
t1 = ToLinearF[(cg += wp[1]) & mask];
t2 = ToLinearF[(cb += wp[2]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
}
} else if (stride == 4) {
t0 = ToLinearF[cr = (wp[0] & mask)];
t1 = ToLinearF[cg = (wp[1] & mask)];
t2 = ToLinearF[cb = (wp[2] & mask)];
t3 = ToLinearF[ca = (wp[3] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
t0 = ToLinearF[(cr += wp[0]) & mask];
t1 = ToLinearF[(cg += wp[1]) & mask];
t2 = ToLinearF[(cb += wp[2]) & mask];
t3 = ToLinearF[(ca += wp[3]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else {
REPEAT(stride, *op = ToLinearF[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinearF[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate12(uint16 *wp, int n, int stride, int16 *op,
float *ToLinearF)
{
register unsigned int cr, cg, cb, ca, mask;
register float t0, t1, t2, t3;
#define SCALE12 2048.0F
#define CLAMP12(t) (((t) < 3071) ? (uint16) (t) : 3071)
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12;
t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12;
t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12;
t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12;
t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
}
} else if (stride == 4) {
t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12;
t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12;
t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12;
t3 = ToLinearF[ca = (wp[3] & mask)] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
op[3] = CLAMP12(t3);
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12;
t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12;
t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12;
t3 = ToLinearF[(ca += wp[3]) & mask] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
op[3] = CLAMP12(t3);
}
} else {
REPEAT(stride, t0 = ToLinearF[*wp&mask] * SCALE12;
*op = CLAMP12(t0); wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; t0 = ToLinearF[wp[stride]&mask]*SCALE12;
*op = CLAMP12(t0); wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate16(uint16 *wp, int n, int stride, uint16 *op,
uint16 *ToLinear16)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = ToLinear16[cr = (wp[0] & mask)];
op[1] = ToLinear16[cg = (wp[1] & mask)];
op[2] = ToLinear16[cb = (wp[2] & mask)];
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
op[0] = ToLinear16[(cr += wp[0]) & mask];
op[1] = ToLinear16[(cg += wp[1]) & mask];
op[2] = ToLinear16[(cb += wp[2]) & mask];
}
} else if (stride == 4) {
op[0] = ToLinear16[cr = (wp[0] & mask)];
op[1] = ToLinear16[cg = (wp[1] & mask)];
op[2] = ToLinear16[cb = (wp[2] & mask)];
op[3] = ToLinear16[ca = (wp[3] & mask)];
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
op[0] = ToLinear16[(cr += wp[0]) & mask];
op[1] = ToLinear16[(cg += wp[1]) & mask];
op[2] = ToLinear16[(cb += wp[2]) & mask];
op[3] = ToLinear16[(ca += wp[3]) & mask];
}
} else {
REPEAT(stride, *op = ToLinear16[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear16[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
/*
* Returns the log encoded 11-bit values with the horizontal
* differencing undone.
*/
static void
horizontalAccumulate11(uint16 *wp, int n, int stride, uint16 *op)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = wp[0]; op[1] = wp[1]; op[2] = wp[2];
cr = wp[0]; cg = wp[1]; cb = wp[2];
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
op[0] = (uint16)((cr += wp[0]) & mask);
op[1] = (uint16)((cg += wp[1]) & mask);
op[2] = (uint16)((cb += wp[2]) & mask);
}
} else if (stride == 4) {
op[0] = wp[0]; op[1] = wp[1];
op[2] = wp[2]; op[3] = wp[3];
cr = wp[0]; cg = wp[1]; cb = wp[2]; ca = wp[3];
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
op[0] = (uint16)((cr += wp[0]) & mask);
op[1] = (uint16)((cg += wp[1]) & mask);
op[2] = (uint16)((cb += wp[2]) & mask);
op[3] = (uint16)((ca += wp[3]) & mask);
}
} else {
REPEAT(stride, *op = *wp&mask; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = *wp&mask; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate8(uint16 *wp, int n, int stride, unsigned char *op,
unsigned char *ToLinear8)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = ToLinear8[cr = (wp[0] & mask)];
op[1] = ToLinear8[cg = (wp[1] & mask)];
op[2] = ToLinear8[cb = (wp[2] & mask)];
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
op += 3;
op[0] = ToLinear8[(cr += wp[0]) & mask];
op[1] = ToLinear8[(cg += wp[1]) & mask];
op[2] = ToLinear8[(cb += wp[2]) & mask];
}
} else if (stride == 4) {
op[0] = ToLinear8[cr = (wp[0] & mask)];
op[1] = ToLinear8[cg = (wp[1] & mask)];
op[2] = ToLinear8[cb = (wp[2] & mask)];
op[3] = ToLinear8[ca = (wp[3] & mask)];
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
op += 4;
op[0] = ToLinear8[(cr += wp[0]) & mask];
op[1] = ToLinear8[(cg += wp[1]) & mask];
op[2] = ToLinear8[(cb += wp[2]) & mask];
op[3] = ToLinear8[(ca += wp[3]) & mask];
}
} else {
REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate8abgr(uint16 *wp, int n, int stride, unsigned char *op,
unsigned char *ToLinear8)
{
register unsigned int cr, cg, cb, ca, mask;
register unsigned char t0, t1, t2, t3;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = 0;
t1 = ToLinear8[cb = (wp[2] & mask)];
t2 = ToLinear8[cg = (wp[1] & mask)];
t3 = ToLinear8[cr = (wp[0] & mask)];
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
op += 4;
op[0] = 0;
t1 = ToLinear8[(cb += wp[2]) & mask];
t2 = ToLinear8[(cg += wp[1]) & mask];
t3 = ToLinear8[(cr += wp[0]) & mask];
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else if (stride == 4) {
t0 = ToLinear8[ca = (wp[3] & mask)];
t1 = ToLinear8[cb = (wp[2] & mask)];
t2 = ToLinear8[cg = (wp[1] & mask)];
t3 = ToLinear8[cr = (wp[0] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
op += 4;
t0 = ToLinear8[(ca += wp[3]) & mask];
t1 = ToLinear8[(cb += wp[2]) & mask];
t2 = ToLinear8[(cg += wp[1]) & mask];
t3 = ToLinear8[(cr += wp[0]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else {
REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
/*
* State block for each open TIFF
* file using PixarLog compression/decompression.
*/
typedef struct {
TIFFPredictorState predict;
z_stream stream;
tmsize_t tbuf_size; /* only set/used on reading for now */
uint16 *tbuf;
uint16 stride;
int state;
int user_datafmt;
int quality;
#define PLSTATE_INIT 1
TIFFVSetMethod vgetparent; /* super-class method */
TIFFVSetMethod vsetparent; /* super-class method */
float *ToLinearF;
uint16 *ToLinear16;
unsigned char *ToLinear8;
uint16 *FromLT2;
uint16 *From14; /* Really for 16-bit data, but we shift down 2 */
uint16 *From8;
} PixarLogState;
static int
PixarLogMakeTables(PixarLogState *sp)
{
/*
* We make several tables here to convert between various external
* representations (float, 16-bit, and 8-bit) and the internal
* 11-bit companded representation. The 11-bit representation has two
* distinct regions. A linear bottom end up through .018316 in steps
* of about .000073, and a region of constant ratio up to about 25.
* These floating point numbers are stored in the main table ToLinearF.
* All other tables are derived from this one. The tables (and the
* ratios) are continuous at the internal seam.
*/
int nlin, lt2size;
int i, j;
double b, c, linstep, v;
float *ToLinearF;
uint16 *ToLinear16;
unsigned char *ToLinear8;
uint16 *FromLT2;
uint16 *From14; /* Really for 16-bit data, but we shift down 2 */
uint16 *From8;
c = log(RATIO);
nlin = (int)(1./c); /* nlin must be an integer */
c = 1./nlin;
b = exp(-c*ONE); /* multiplicative scale factor [b*exp(c*ONE) = 1] */
linstep = b*c*exp(1.);
LogK1 = (float)(1./c); /* if (v >= 2) token = k1*log(v*k2) */
LogK2 = (float)(1./b);
lt2size = (int)(2./linstep) + 1;
FromLT2 = (uint16 *)_TIFFmalloc(lt2size*sizeof(uint16));
From14 = (uint16 *)_TIFFmalloc(16384*sizeof(uint16));
From8 = (uint16 *)_TIFFmalloc(256*sizeof(uint16));
ToLinearF = (float *)_TIFFmalloc(TSIZEP1 * sizeof(float));
ToLinear16 = (uint16 *)_TIFFmalloc(TSIZEP1 * sizeof(uint16));
ToLinear8 = (unsigned char *)_TIFFmalloc(TSIZEP1 * sizeof(unsigned char));
if (FromLT2 == NULL || From14 == NULL || From8 == NULL ||
ToLinearF == NULL || ToLinear16 == NULL || ToLinear8 == NULL) {
if (FromLT2) _TIFFfree(FromLT2);
if (From14) _TIFFfree(From14);
if (From8) _TIFFfree(From8);
if (ToLinearF) _TIFFfree(ToLinearF);
if (ToLinear16) _TIFFfree(ToLinear16);
if (ToLinear8) _TIFFfree(ToLinear8);
sp->FromLT2 = NULL;
sp->From14 = NULL;
sp->From8 = NULL;
sp->ToLinearF = NULL;
sp->ToLinear16 = NULL;
sp->ToLinear8 = NULL;
return 0;
}
j = 0;
for (i = 0; i < nlin; i++) {
v = i * linstep;
ToLinearF[j++] = (float)v;
}
for (i = nlin; i < TSIZE; i++)
ToLinearF[j++] = (float)(b*exp(c*i));
ToLinearF[2048] = ToLinearF[2047];
for (i = 0; i < TSIZEP1; i++) {
v = ToLinearF[i]*65535.0 + 0.5;
ToLinear16[i] = (v > 65535.0) ? 65535 : (uint16)v;
v = ToLinearF[i]*255.0 + 0.5;
ToLinear8[i] = (v > 255.0) ? 255 : (unsigned char)v;
}
j = 0;
for (i = 0; i < lt2size; i++) {
if ((i*linstep)*(i*linstep) > ToLinearF[j]*ToLinearF[j+1])
j++;
FromLT2[i] = (uint16)j;
}
/*
* Since we lose info anyway on 16-bit data, we set up a 14-bit
* table and shift 16-bit values down two bits on input.
* saves a little table space.
*/
j = 0;
for (i = 0; i < 16384; i++) {
while ((i/16383.)*(i/16383.) > ToLinearF[j]*ToLinearF[j+1])
j++;
From14[i] = (uint16)j;
}
j = 0;
for (i = 0; i < 256; i++) {
while ((i/255.)*(i/255.) > ToLinearF[j]*ToLinearF[j+1])
j++;
From8[i] = (uint16)j;
}
Fltsize = (float)(lt2size/2);
sp->ToLinearF = ToLinearF;
sp->ToLinear16 = ToLinear16;
sp->ToLinear8 = ToLinear8;
sp->FromLT2 = FromLT2;
sp->From14 = From14;
sp->From8 = From8;
return 1;
}
#define DecoderState(tif) ((PixarLogState*) (tif)->tif_data)
#define EncoderState(tif) ((PixarLogState*) (tif)->tif_data)
static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s);
static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s);
#define PIXARLOGDATAFMT_UNKNOWN -1
static int
PixarLogGuessDataFmt(TIFFDirectory *td)
{
int guess = PIXARLOGDATAFMT_UNKNOWN;
int format = td->td_sampleformat;
/* If the user didn't tell us his datafmt,
* take our best guess from the bitspersample.
*/
switch (td->td_bitspersample) {
case 32:
if (format == SAMPLEFORMAT_IEEEFP)
guess = PIXARLOGDATAFMT_FLOAT;
break;
case 16:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_16BIT;
break;
case 12:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_INT)
guess = PIXARLOGDATAFMT_12BITPICIO;
break;
case 11:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_11BITLOG;
break;
case 8:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_8BIT;
break;
}
return guess;
}
static tmsize_t
multiply_ms(tmsize_t m1, tmsize_t m2)
{
tmsize_t bytes = m1 * m2;
if (m1 && bytes / m1 != m2)
bytes = 0;
return bytes;
}
static tmsize_t
add_ms(tmsize_t m1, tmsize_t m2)
{
tmsize_t bytes = m1 + m2;
/* if either input is zero, assume overflow already occurred */
if (m1 == 0 || m2 == 0)
bytes = 0;
else if (bytes <= m1 || bytes <= m2)
bytes = 0;
return bytes;
}
static int
PixarLogFixupTags(TIFF* tif)
{
(void) tif;
return (1);
}
static int
PixarLogSetupDecode(TIFF* tif)
{
static const char module[] = "PixarLogSetupDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t tbuf_size;
assert(sp != NULL);
/* Make sure no byte swapping happens on the data
* after decompression. */
tif->tif_postdecode = _TIFFNoPostDecode;
/* for some reason, we can't do this in TIFFInitPixarLog */
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
td->td_rowsperstrip), sizeof(uint16));
/* add one more stride in case input ends mid-stride */
tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride);
if (tbuf_size == 0)
return (0); /* TODO: this is an error return without error report through TIFFErrorExt */
sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
if (sp->tbuf == NULL)
return (0);
sp->tbuf_size = tbuf_size;
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
sp->user_datafmt = PixarLogGuessDataFmt(td);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
TIFFErrorExt(tif->tif_clientdata, module,
"PixarLog compression can't handle bits depth/data format combination (depth: %d)",
td->td_bitspersample);
return (0);
}
if (inflateInit(&sp->stream) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
} else {
sp->state |= PLSTATE_INIT;
return (1);
}
}
/*
* Setup state for decoding a strip.
*/
static int
PixarLogPreDecode(TIFF* tif, uint16 s)
{
static const char module[] = "PixarLogPreDecode";
PixarLogState* sp = DecoderState(tif);
(void) s;
assert(sp != NULL);
sp->stream.next_in = tif->tif_rawdata;
assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_in = (uInt) tif->tif_rawcc;
if ((tmsize_t)sp->stream.avail_in != tif->tif_rawcc)
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
return (inflateReset(&sp->stream) == Z_OK);
}
static int
PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
{
static const char module[] = "PixarLogDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t i;
tmsize_t nsamples;
int llen;
uint16 *up;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
nsamples = occ / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
nsamples = occ;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
(void) s;
assert(sp != NULL);
sp->stream.next_out = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16));
if (sp->stream.avail_out != nsamples * sizeof(uint16))
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
/* Check that we will not fill more than what was allocated */
if ((tmsize_t)sp->stream.avail_out > sp->tbuf_size)
{
TIFFErrorExt(tif->tif_clientdata, module, "sp->stream.avail_out > sp->tbuf_size");
return (0);
}
do {
int state = inflate(&sp->stream, Z_PARTIAL_FLUSH);
if (state == Z_STREAM_END) {
break; /* XXX */
}
if (state == Z_DATA_ERROR) {
TIFFErrorExt(tif->tif_clientdata, module,
"Decoding error at scanline %lu, %s",
(unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)");
if (inflateSync(&sp->stream) != Z_OK)
return (0);
continue;
}
if (state != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (sp->stream.avail_out > 0);
/* hopefully, we got all the bytes we needed */
if (sp->stream.avail_out != 0) {
TIFFErrorExt(tif->tif_clientdata, module,
"Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)",
(unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out);
return (0);
}
up = sp->tbuf;
/* Swap bytes in the data if from a different endian machine. */
if (tif->tif_flags & TIFF_SWAB)
TIFFSwabArrayOfShort(up, nsamples);
/*
* if llen is not an exact multiple of nsamples, the decode operation
* may overflow the output buffer, so truncate it enough to prevent
* that but still salvage as much data as possible.
*/
if (nsamples % llen) {
TIFFWarningExt(tif->tif_clientdata, module,
"stride %lu is not a multiple of sample count, "
"%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples);
nsamples -= nsamples % llen;
}
for (i = 0; i < nsamples; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalAccumulateF(up, llen, sp->stride,
(float *)op, sp->ToLinearF);
op += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalAccumulate16(up, llen, sp->stride,
(uint16 *)op, sp->ToLinear16);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_12BITPICIO:
horizontalAccumulate12(up, llen, sp->stride,
(int16 *)op, sp->ToLinearF);
op += llen * sizeof(int16);
break;
case PIXARLOGDATAFMT_11BITLOG:
horizontalAccumulate11(up, llen, sp->stride,
(uint16 *)op);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalAccumulate8(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
case PIXARLOGDATAFMT_8BITABGR:
horizontalAccumulate8abgr(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"Unsupported bits/sample: %d",
td->td_bitspersample);
return (0);
}
}
return (1);
}
static int
PixarLogSetupEncode(TIFF* tif)
{
static const char module[] = "PixarLogSetupEncode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = EncoderState(tif);
tmsize_t tbuf_size;
assert(sp != NULL);
/* for some reason, we can't do this in TIFFInitPixarLog */
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
td->td_rowsperstrip), sizeof(uint16));
if (tbuf_size == 0)
return (0); /* TODO: this is an error return without error report through TIFFErrorExt */
sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
if (sp->tbuf == NULL)
return (0);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
sp->user_datafmt = PixarLogGuessDataFmt(td);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle %d bit linear encodings", td->td_bitspersample);
return (0);
}
if (deflateInit(&sp->stream, sp->quality) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
} else {
sp->state |= PLSTATE_INIT;
return (1);
}
}
/*
* Reset encoding state at the start of a strip.
*/
static int
PixarLogPreEncode(TIFF* tif, uint16 s)
{
static const char module[] = "PixarLogPreEncode";
PixarLogState *sp = EncoderState(tif);
(void) s;
assert(sp != NULL);
sp->stream.next_out = tif->tif_rawdata;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt)tif->tif_rawdatasize;
if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize)
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
return (deflateReset(&sp->stream) == Z_OK);
}
static void
horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2)
{
int32 r1, g1, b1, a1, r2, g2, b2, a2, mask;
float fltsize = Fltsize;
#define CLAMP(v) ( (v<(float)0.) ? 0 \
: (v<(float)2.) ? FromLT2[(int)(v*fltsize)] \
: (v>(float)24.2) ? 2047 \
: LogK1*log(v*LogK2) + 0.5 )
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
a2 = wp[3] = (uint16) CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp++; ip++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[0] = (uint16)(((int32)CLAMP(ip[0])-(int32)CLAMP(ip[-stride])) & mask);
wp++; ip++)
n -= stride;
}
}
}
}
static void
horizontalDifference16(unsigned short *ip, int n, int stride,
unsigned short *wp, uint16 *From14)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
/* assumption is unsigned pixel values */
#undef CLAMP
#define CLAMP(v) From14[(v) >> 2]
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask);
wp++; ip++)
n -= stride;
}
}
}
}
static void
horizontalDifference8(unsigned char *ip, int n, int stride,
unsigned short *wp, uint16 *From8)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
#undef CLAMP
#define CLAMP(v) (From8[(v)])
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1;
wp += 3;
ip += 3;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1;
wp += 4;
ip += 4;
}
} else {
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask);
wp++; ip++)
n -= stride;
}
}
}
}
/*
* Encode a chunk of pixels.
*/
static int
PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
{
static const char module[] = "PixarLogEncode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState *sp = EncoderState(tif);
tmsize_t i;
tmsize_t n;
int llen;
unsigned short * up;
(void) s;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
n = cc / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
n = cc / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
n = cc;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
/* Check against the number of elements (of size uint16) of sp->tbuf */
if( n > (tmsize_t)(td->td_rowsperstrip * llen) )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Too many input bytes provided");
return 0;
}
for (i = 0, up = sp->tbuf; i < n; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalDifferenceF((float *)bp, llen,
sp->stride, up, sp->FromLT2);
bp += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalDifference16((uint16 *)bp, llen,
sp->stride, up, sp->From14);
bp += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalDifference8((unsigned char *)bp, llen,
sp->stride, up, sp->From8);
bp += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
}
sp->stream.next_in = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_in = (uInt) (n * sizeof(uint16));
if ((sp->stream.avail_in / sizeof(uint16)) != (uInt) n)
{
TIFFErrorExt(tif->tif_clientdata, module,
"ZLib cannot deal with buffers this size");
return (0);
}
do {
if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "Encoder error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
if (sp->stream.avail_out == 0) {
tif->tif_rawcc = tif->tif_rawdatasize;
TIFFFlushData1(tif);
sp->stream.next_out = tif->tif_rawdata;
sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */
}
} while (sp->stream.avail_in > 0);
return (1);
}
/*
* Finish off an encoded strip by flushing the last
* string and tacking on an End Of Information code.
*/
static int
PixarLogPostEncode(TIFF* tif)
{
static const char module[] = "PixarLogPostEncode";
PixarLogState *sp = EncoderState(tif);
int state;
sp->stream.avail_in = 0;
do {
state = deflate(&sp->stream, Z_FINISH);
switch (state) {
case Z_STREAM_END:
case Z_OK:
if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) {
tif->tif_rawcc =
tif->tif_rawdatasize - sp->stream.avail_out;
TIFFFlushData1(tif);
sp->stream.next_out = tif->tif_rawdata;
sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */
}
break;
default:
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (state != Z_STREAM_END);
return (1);
}
static void
PixarLogClose(TIFF* tif)
{
PixarLogState* sp = (PixarLogState*) tif->tif_data;
TIFFDirectory *td = &tif->tif_dir;
assert(sp != 0);
/* In a really sneaky (and really incorrect, and untruthful, and
* troublesome, and error-prone) maneuver that completely goes against
* the spirit of TIFF, and breaks TIFF, on close, we covertly
* modify both bitspersample and sampleformat in the directory to
* indicate 8-bit linear. This way, the decode "just works" even for
* readers that don't know about PixarLog, or how to set
* the PIXARLOGDATFMT pseudo-tag.
*/
if (sp->state&PLSTATE_INIT) {
/* We test the state to avoid an issue such as in
* http://bugzilla.maptools.org/show_bug.cgi?id=2604
* What appends in that case is that the bitspersample is 1 and
* a TransferFunction is set. The size of the TransferFunction
* depends on 1<<bitspersample. So if we increase it, an access
* out of the buffer will happen at directory flushing.
* Another option would be to clear those targs.
*/
td->td_bitspersample = 8;
td->td_sampleformat = SAMPLEFORMAT_UINT;
}
}
static void
PixarLogCleanup(TIFF* tif)
{
PixarLogState* sp = (PixarLogState*) tif->tif_data;
assert(sp != 0);
(void)TIFFPredictorCleanup(tif);
tif->tif_tagmethods.vgetfield = sp->vgetparent;
tif->tif_tagmethods.vsetfield = sp->vsetparent;
if (sp->FromLT2) _TIFFfree(sp->FromLT2);
if (sp->From14) _TIFFfree(sp->From14);
if (sp->From8) _TIFFfree(sp->From8);
if (sp->ToLinearF) _TIFFfree(sp->ToLinearF);
if (sp->ToLinear16) _TIFFfree(sp->ToLinear16);
if (sp->ToLinear8) _TIFFfree(sp->ToLinear8);
if (sp->state&PLSTATE_INIT) {
if (tif->tif_mode == O_RDONLY)
inflateEnd(&sp->stream);
else
deflateEnd(&sp->stream);
}
if (sp->tbuf)
_TIFFfree(sp->tbuf);
_TIFFfree(sp);
tif->tif_data = NULL;
_TIFFSetDefaultCompressionState(tif);
}
static int
PixarLogVSetField(TIFF* tif, uint32 tag, va_list ap)
{
static const char module[] = "PixarLogVSetField";
PixarLogState *sp = (PixarLogState *)tif->tif_data;
int result;
switch (tag) {
case TIFFTAG_PIXARLOGQUALITY:
sp->quality = (int) va_arg(ap, int);
if (tif->tif_mode != O_RDONLY && (sp->state&PLSTATE_INIT)) {
if (deflateParams(&sp->stream,
sp->quality, Z_DEFAULT_STRATEGY) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
}
return (1);
case TIFFTAG_PIXARLOGDATAFMT:
sp->user_datafmt = (int) va_arg(ap, int);
/* Tweak the TIFF header so that the rest of libtiff knows what
* size of data will be passed between app and library, and
* assume that the app knows what it is doing and is not
* confused by these header manipulations...
*/
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_11BITLOG:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_12BITPICIO:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
break;
case PIXARLOGDATAFMT_16BIT:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_FLOAT:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 32);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
break;
}
/*
* Must recalculate sizes should bits/sample change.
*/
tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);
tif->tif_scanlinesize = TIFFScanlineSize(tif);
result = 1; /* NB: pseudo tag */
break;
default:
result = (*sp->vsetparent)(tif, tag, ap);
}
return (result);
}
static int
PixarLogVGetField(TIFF* tif, uint32 tag, va_list ap)
{
PixarLogState *sp = (PixarLogState *)tif->tif_data;
switch (tag) {
case TIFFTAG_PIXARLOGQUALITY:
*va_arg(ap, int*) = sp->quality;
break;
case TIFFTAG_PIXARLOGDATAFMT:
*va_arg(ap, int*) = sp->user_datafmt;
break;
default:
return (*sp->vgetparent)(tif, tag, ap);
}
return (1);
}
static const TIFFField pixarlogFields[] = {
{TIFFTAG_PIXARLOGDATAFMT, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL},
{TIFFTAG_PIXARLOGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL}
};
int
TIFFInitPixarLog(TIFF* tif, int scheme)
{
static const char module[] = "TIFFInitPixarLog";
PixarLogState* sp;
assert(scheme == COMPRESSION_PIXARLOG);
/*
* Merge codec-specific tag information.
*/
if (!_TIFFMergeFields(tif, pixarlogFields,
TIFFArrayCount(pixarlogFields))) {
TIFFErrorExt(tif->tif_clientdata, module,
"Merging PixarLog codec-specific tags failed");
return 0;
}
/*
* Allocate state block so tag methods have storage to record values.
*/
tif->tif_data = (uint8*) _TIFFmalloc(sizeof (PixarLogState));
if (tif->tif_data == NULL)
goto bad;
sp = (PixarLogState*) tif->tif_data;
_TIFFmemset(sp, 0, sizeof (*sp));
sp->stream.data_type = Z_BINARY;
sp->user_datafmt = PIXARLOGDATAFMT_UNKNOWN;
/*
* Install codec methods.
*/
tif->tif_fixuptags = PixarLogFixupTags;
tif->tif_setupdecode = PixarLogSetupDecode;
tif->tif_predecode = PixarLogPreDecode;
tif->tif_decoderow = PixarLogDecode;
tif->tif_decodestrip = PixarLogDecode;
tif->tif_decodetile = PixarLogDecode;
tif->tif_setupencode = PixarLogSetupEncode;
tif->tif_preencode = PixarLogPreEncode;
tif->tif_postencode = PixarLogPostEncode;
tif->tif_encoderow = PixarLogEncode;
tif->tif_encodestrip = PixarLogEncode;
tif->tif_encodetile = PixarLogEncode;
tif->tif_close = PixarLogClose;
tif->tif_cleanup = PixarLogCleanup;
/* Override SetField so we can handle our private pseudo-tag */
sp->vgetparent = tif->tif_tagmethods.vgetfield;
tif->tif_tagmethods.vgetfield = PixarLogVGetField; /* hook for codec tags */
sp->vsetparent = tif->tif_tagmethods.vsetfield;
tif->tif_tagmethods.vsetfield = PixarLogVSetField; /* hook for codec tags */
/* Default values for codec-specific fields */
sp->quality = Z_DEFAULT_COMPRESSION; /* default comp. level */
sp->state = 0;
/* we don't wish to use the predictor,
* the default is none, which predictor value 1
*/
(void) TIFFPredictorInit(tif);
/*
* build the companding tables
*/
PixarLogMakeTables(sp);
return (1);
bad:
TIFFErrorExt(tif->tif_clientdata, module,
"No space for PixarLog state block");
return (0);
}
#endif /* PIXARLOG_SUPPORT */
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4856_2 |
crossvul-cpp_data_bad_5241_1 | /*
TIFF - Tagged Image File Format Encapsulation for GD Library
gd_tiff.c
Copyright (C) Pierre-A. Joye, M. Retallack
---------------------------------------------------------------------------
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation. This software is provided "as is" without express or
** implied warranty.
**
---------------------------------------------------------------------------
Ctx code written by M. Retallack
Todo:
If we fail - cleanup
Writer: Use gd error function, overflow check may not be necessary as
we write our own data (check already done)
Implement 2 color black/white saving using group4 fax compression
Implement function to specify encoding to use when writing tiff data
----------------------------------------------------------------------------
*/
/* $Id$ */
/**
* File: TIFF IO
*
* Read and write TIFF images.
*
* There is only most basic support for the TIFF format available for now;
* for instance, multiple pages are not yet supported.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "gd.h"
#include "gd_errors.h"
#include "gdfonts.h"
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "gdhelpers.h"
#ifdef HAVE_LIBTIFF
#include "tiff.h"
#include "tiffio.h"
#define GD_SUCCESS 1
#define GD_FAILURE 0
#define TRUE 1
#define FALSE 0
/* I define those here until the new formats
* are commited. We can then rely on the global
* def
*/
#define GD_PALETTE 1
#define GD_TRUECOLOR 2
#define GD_GRAY 3
#define GD_INDEXED 4
#define GD_RGB 5
#define MIN(a,b) (a < b) ? a : b;
#define MAX(a,b) (a > b) ? a : b;
typedef struct tiff_handle {
int size;
int pos;
gdIOCtx *ctx;
int written;
}
tiff_handle;
/*
Functions for reading, writing and seeking in gdIOCtx
This allows for non-file i/o operations with no
explicit use of libtiff fileio wrapper functions
Note: because libtiff requires random access, but gdIOCtx
only supports streams, all writes are buffered
into memory and written out on close, also all
reads are done from a memory mapped version of the
tiff (assuming one already exists)
*/
tiff_handle * new_tiff_handle(gdIOCtx *g)
{
tiff_handle * t;
if (!g) {
gd_error("Cannot create a new tiff handle, missing Ctx argument");
return NULL;
}
t = (tiff_handle *) gdMalloc(sizeof(tiff_handle));
if (!t) {
gd_error("Failed to allocate a new tiff handle");
return NULL;
}
t->size = 0;
t->pos = 0;
t->ctx = g;
t->written = 0;
return t;
}
/* TIFFReadWriteProc tiff_readproc - Will use gdIOCtx procs to read required
(previously written) TIFF file content */
static tsize_t tiff_readproc(thandle_t clientdata, tdata_t data, tsize_t size)
{
tiff_handle *th = (tiff_handle *)clientdata;
gdIOCtx *ctx = th->ctx;
size = (ctx->getBuf)(ctx, data, size);
return size;
}
/* TIFFReadWriteProc tiff_writeproc - Will use gdIOCtx procs to write out
TIFF data */
static tsize_t tiff_writeproc(thandle_t clientdata, tdata_t data, tsize_t size)
{
tiff_handle *th = (tiff_handle *)clientdata;
gdIOCtx *ctx = th->ctx;
size = (ctx->putBuf)(ctx, data, size);
if(size + th->pos>th->size) {
th->size = size + th->pos;
th->pos += size;
}
return size;
}
/* TIFFSeekProc tiff_seekproc
* used to move around the partially written TIFF */
static toff_t tiff_seekproc(thandle_t clientdata, toff_t offset, int from)
{
tiff_handle *th = (tiff_handle *)clientdata;
gdIOCtx *ctx = th->ctx;
int result;
switch(from) {
default:
case SEEK_SET:
/* just use offset */
break;
case SEEK_END:
/* invert offset, so that it is from start, not end as supplied */
offset = th->size + offset;
break;
case SEEK_CUR:
/* add current position to translate it to 'from start',
* not from durrent as supplied
*/
offset += th->pos;
break;
}
/* now, move pos in both io context and buf */
if((result = (ctx->seek)(ctx, offset))) {
th->pos = offset;
}
return result ? offset : (toff_t)-1;
}
/* TIFFCloseProc tiff_closeproc - used to finally close the TIFF file */
static int tiff_closeproc(thandle_t clientdata)
{
(void)clientdata;
/*tiff_handle *th = (tiff_handle *)clientdata;
gdIOCtx *ctx = th->ctx;
(ctx->gd_free)(ctx);*/
return 0;
}
/* TIFFSizeProc tiff_sizeproc */
static toff_t tiff_sizeproc(thandle_t clientdata)
{
tiff_handle *th = (tiff_handle *)clientdata;
return th->size;
}
/* TIFFMapFileProc tiff_mapproc() */
static int tiff_mapproc(thandle_t h, tdata_t *d, toff_t *o)
{
(void)h;
(void)d;
(void)o;
return 0;
}
/* TIFFUnmapFileProc tiff_unmapproc */
static void tiff_unmapproc(thandle_t h, tdata_t d, toff_t o)
{
(void)h;
(void)d;
(void)o;
}
/* tiffWriter
* ----------
* Write the gd image as a tiff file (called by gdImageTiffCtx)
* Parameters are:
* image: gd image structure;
* out: the stream where to write
* bitDepth: depth in bits of each pixel
*/
void tiffWriter(gdImagePtr image, gdIOCtx *out, int bitDepth)
{
int x, y;
int i;
int r, g, b, a;
TIFF *tiff;
int width, height;
int color;
char *scan;
int samplesPerPixel = 3;
int bitsPerSample;
int transparentColorR = -1;
int transparentColorG = -1;
int transparentColorB = -1;
uint16 extraSamples[1];
uint16 *colorMapRed = NULL;
uint16 *colorMapGreen = NULL;
uint16 *colorMapBlue = NULL;
tiff_handle *th;
th = new_tiff_handle(out);
if (!th) {
return;
}
extraSamples[0] = EXTRASAMPLE_ASSOCALPHA;
/* read in the width/height of gd image */
width = gdImageSX(image);
height = gdImageSY(image);
/* reset clip region to whole image */
gdImageSetClip(image, 0, 0, width, height);
/* handle old-style single-colour mapping to 100% transparency */
if(image->transparent != -1) {
/* set our 100% transparent colour value */
transparentColorR = gdImageRed(image, image->transparent);
transparentColorG = gdImageGreen(image, image->transparent);
transparentColorB = gdImageBlue(image, image->transparent);
}
/* Open tiff file writing routines, but use special read/write/seek
* functions so that tiff lib writes correct bits of tiff content to
* correct areas of file opened and modifieable by the gdIOCtx functions
*/
tiff = TIFFClientOpen("", "w", th, tiff_readproc,
tiff_writeproc,
tiff_seekproc,
tiff_closeproc,
tiff_sizeproc,
tiff_mapproc,
tiff_unmapproc);
TIFFSetField(tiff, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(tiff, TIFFTAG_IMAGELENGTH, height);
TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE);
TIFFSetField(tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC,
(bitDepth == 24) ? PHOTOMETRIC_RGB : PHOTOMETRIC_PALETTE);
bitsPerSample = (bitDepth == 24 || bitDepth == 8) ? 8 : 1;
TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, bitsPerSample);
TIFFSetField(tiff, TIFFTAG_XRESOLUTION, (float)image->res_x);
TIFFSetField(tiff, TIFFTAG_YRESOLUTION, (float)image->res_y);
/* build the color map for 8 bit images */
if(bitDepth != 24) {
colorMapRed = (uint16 *) gdMalloc(3 * (1 << bitsPerSample));
if (!colorMapRed) {
gdFree(th);
return;
}
colorMapGreen = (uint16 *) gdMalloc(3 * (1 << bitsPerSample));
if (!colorMapGreen) {
gdFree(colorMapRed);
gdFree(th);
return;
}
colorMapBlue = (uint16 *) gdMalloc(3 * (1 << bitsPerSample));
if (!colorMapBlue) {
gdFree(colorMapRed);
gdFree(colorMapGreen);
gdFree(th);
return;
}
for(i = 0; i < image->colorsTotal; i++) {
colorMapRed[i] = gdImageRed(image,i) + (gdImageRed(image,i) * 256);
colorMapGreen[i] = gdImageGreen(image,i)+(gdImageGreen(image,i)*256);
colorMapBlue[i] = gdImageBlue(image,i) + (gdImageBlue(image,i)*256);
}
TIFFSetField(tiff, TIFFTAG_COLORMAP, colorMapRed, colorMapGreen,
colorMapBlue);
samplesPerPixel = 1;
}
/* here, we check if the 'save alpha' flag is set on the source gd image */
if ((bitDepth == 24) &&
(image->saveAlphaFlag || image->transparent != -1)) {
/* so, we need to store the alpha values too!
* Also, tell TIFF what the extra sample means (associated alpha) */
samplesPerPixel = 4;
TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, samplesPerPixel);
TIFFSetField(tiff, TIFFTAG_EXTRASAMPLES, 1, extraSamples);
} else {
TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, samplesPerPixel);
}
TIFFSetField(tiff, TIFFTAG_ROWSPERSTRIP, 1);
if(overflow2(width, samplesPerPixel)) {
if (colorMapRed) gdFree(colorMapRed);
if (colorMapGreen) gdFree(colorMapGreen);
if (colorMapBlue) gdFree(colorMapBlue);
gdFree(th);
return;
}
if(!(scan = (char *)gdMalloc(width * samplesPerPixel))) {
if (colorMapRed) gdFree(colorMapRed);
if (colorMapGreen) gdFree(colorMapGreen);
if (colorMapBlue) gdFree(colorMapBlue);
gdFree(th);
return;
}
/* loop through y-coords, and x-coords */
for(y = 0; y < height; y++) {
for(x = 0; x < width; x++) {
/* generate scan line for writing to tiff */
color = gdImageGetPixel(image, x, y);
a = (127 - gdImageAlpha(image, color)) * 2;
a = (a == 0xfe) ? 0xff : a & 0xff;
b = gdImageBlue(image, color);
g = gdImageGreen(image, color);
r = gdImageRed(image, color);
/* if this pixel has the same RGB as the transparent colour,
* then set alpha fully transparent */
if (transparentColorR == r &&
transparentColorG == g &&
transparentColorB == b) {
a = 0x00;
}
if(bitDepth != 24) {
/* write out 1 or 8 bit value in 1 byte
* (currently treats 1bit as 8bit) */
scan[(x * samplesPerPixel) + 0] = color;
} else {
/* write out 24 bit value in 3 (or 4 if transparent) bytes */
if(image->saveAlphaFlag || image->transparent != -1) {
scan[(x * samplesPerPixel) + 3] = a;
}
scan[(x * samplesPerPixel) + 2] = b;
scan[(x * samplesPerPixel) + 1] = g;
scan[(x * samplesPerPixel) + 0] = r;
}
}
/* Write the scan line to the tiff */
if(TIFFWriteEncodedStrip(tiff, y, scan, width * samplesPerPixel) == -1) {
if (colorMapRed) gdFree(colorMapRed);
if (colorMapGreen) gdFree(colorMapGreen);
if (colorMapBlue) gdFree(colorMapBlue);
gdFree(th);
/* error handler here */
gd_error("Could not create TIFF\n");
return;
}
}
/* now cloase and free up resources */
TIFFClose(tiff);
gdFree(scan);
gdFree(th);
if(bitDepth != 24) {
gdFree(colorMapRed);
gdFree(colorMapGreen);
gdFree(colorMapBlue);
}
}
/*
Function: gdImageTiffCtx
Write the gd image as a tiff file.
Parameters:
image - gd image structure;
out - the stream where to write
*/
BGD_DECLARE(void) gdImageTiffCtx(gdImagePtr image, gdIOCtx *out)
{
int clipx1P, clipy1P, clipx2P, clipy2P;
int bitDepth = 24;
/* First, switch off clipping, or we'll not get all the image! */
gdImageGetClip(image, &clipx1P, &clipy1P, &clipx2P, &clipy2P);
/* use the appropriate routine depending on the bit depth of the image */
if(image->trueColor) {
bitDepth = 24;
} else if(image->colorsTotal == 2) {
bitDepth = 1;
} else {
bitDepth = 8;
}
tiffWriter(image, out, bitDepth);
/* reset clipping area to the gd image's original values */
gdImageSetClip(image, clipx1P, clipy1P, clipx2P, clipy2P);
}
/* Check if we are really in 8bit mode */
static int checkColorMap(n, r, g, b)
int n;
uint16 *r, *g, *b;
{
while (n-- > 0)
if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
return (16);
return (8);
}
/* Read and convert a TIFF colormap */
static int readTiffColorMap(gdImagePtr im, TIFF *tif, char is_bw, int photometric)
{
uint16 *redcmap, *greencmap, *bluecmap;
uint16 bps;
int i;
if (is_bw) {
if (photometric == PHOTOMETRIC_MINISWHITE) {
gdImageColorAllocate(im, 255,255,255);
gdImageColorAllocate(im, 0, 0, 0);
} else {
gdImageColorAllocate(im, 0, 0, 0);
gdImageColorAllocate(im, 255,255,255);
}
} else {
uint16 min_sample_val, max_sample_val;
if (!TIFFGetField(tif, TIFFTAG_MINSAMPLEVALUE, &min_sample_val)) {
min_sample_val = 0;
}
if (!TIFFGetField(tif, TIFFTAG_MAXSAMPLEVALUE, &max_sample_val)) {
max_sample_val = 255;
}
if (photometric == PHOTOMETRIC_MINISBLACK || photometric == PHOTOMETRIC_MINISWHITE) {
/* TODO: use TIFFTAG_MINSAMPLEVALUE and TIFFTAG_MAXSAMPLEVALUE */
/* Gray level palette */
for (i=min_sample_val; i <= max_sample_val; i++) {
gdImageColorAllocate(im, i,i,i);
}
return GD_SUCCESS;
} else if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &redcmap, &greencmap, &bluecmap)) {
gd_error("Cannot read the color map");
return GD_FAILURE;
}
TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bps);
#define CVT(x) (((x) * 255) / ((1L<<16)-1))
if (checkColorMap(1<<bps, redcmap, greencmap, bluecmap) == 16) {
for (i = (1<<bps)-1; i > 0; i--) {
redcmap[i] = CVT(redcmap[i]);
greencmap[i] = CVT(greencmap[i]);
bluecmap[i] = CVT(bluecmap[i]);
}
}
for (i = 0; i < 256; i++) {
gdImageColorAllocate(im, redcmap[i], greencmap[i], bluecmap[i]);
}
#undef CVT
}
return GD_SUCCESS;
}
static void readTiffBw (const unsigned char *src,
gdImagePtr im,
uint16 photometric,
int startx,
int starty,
int width,
int height,
char has_alpha,
int extra,
int align)
{
int x = startx, y = starty;
(void)has_alpha;
(void)extra;
(void)align;
for (y = starty; y < starty + height; y++) {
for (x = startx; x < startx + width; x++) {
register unsigned char curr = *src++;
register unsigned char mask;
if (photometric == PHOTOMETRIC_MINISWHITE) {
curr = ~curr;
}
for (mask = 0x80; mask != 0 && x < startx + width; mask >>= 1) {
gdImageSetPixel(im, x, y, ((curr & mask) != 0)?0:1);
}
}
}
}
static void readTiff8bit (const unsigned char *src,
gdImagePtr im,
uint16 photometric,
int startx,
int starty,
int width,
int height,
char has_alpha,
int extra,
int align)
{
int red, green, blue, alpha;
int x, y;
(void)extra;
(void)align;
switch (photometric) {
case PHOTOMETRIC_PALETTE:
/* Palette has no alpha (see TIFF specs for more details */
for (y = starty; y < starty + height; y++) {
for (x = startx; x < startx + width; x++) {
gdImageSetPixel(im, x, y,*(src++));
}
}
break;
case PHOTOMETRIC_RGB:
if (has_alpha) {
gdImageAlphaBlending(im, 0);
gdImageSaveAlpha(im, 1);
for (y = starty; y < starty + height; y++) {
for (x = startx; x < startx + width; x++) {
red = *src++;
green = *src++;
blue = *src++;
alpha = *src++;
red = MIN (red, alpha);
blue = MIN (blue, alpha);
green = MIN (green, alpha);
if (alpha) {
gdImageSetPixel(im, x, y, gdTrueColorAlpha(red * 255 / alpha, green * 255 / alpha, blue * 255 /alpha, gdAlphaMax - (alpha >> 1)));
} else {
gdImageSetPixel(im, x, y, gdTrueColorAlpha(red, green, blue, gdAlphaMax - (alpha >> 1)));
}
}
}
} else {
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
register unsigned char r = *src++;
register unsigned char g = *src++;
register unsigned char b = *src++;
gdImageSetPixel(im, x, y, gdTrueColor(r, g, b));
}
}
}
break;
case PHOTOMETRIC_MINISWHITE:
if (has_alpha) {
/* We don't process the extra yet */
} else {
for (y = starty; y < starty + height; y++) {
for (x = startx; x < startx + width; x++) {
gdImageSetPixel(im, x, y, ~(*src++));
}
}
}
break;
case PHOTOMETRIC_MINISBLACK:
if (has_alpha) {
/* We don't process the extra yet */
} else {
for (y = starty; y < height; y++) {
for (x = 0; x < width; x++) {
gdImageSetPixel(im, x, y, *src++);
}
}
}
break;
}
}
static int createFromTiffTiles(TIFF *tif, gdImagePtr im, uint16 bps, uint16 photometric,
char has_alpha, char is_bw, int extra)
{
uint16 planar;
int im_width, im_height;
int tile_width, tile_height;
int x, y, height, width;
unsigned char *buffer;
if (!TIFFGetField (tif, TIFFTAG_PLANARCONFIG, &planar)) {
planar = PLANARCONFIG_CONTIG;
}
if (TIFFGetField (tif, TIFFTAG_IMAGEWIDTH, &im_width) == 0 ||
TIFFGetField (tif, TIFFTAG_IMAGELENGTH, &im_height) == 0 ||
TIFFGetField (tif, TIFFTAG_TILEWIDTH, &tile_width) == 0 ||
TIFFGetField (tif, TIFFTAG_TILELENGTH, &tile_height) == 0) {
return FALSE;
}
buffer = (unsigned char *) gdMalloc (TIFFTileSize (tif));
if (!buffer) {
return FALSE;
}
for (y = 0; y < im_height; y += tile_height) {
for (x = 0; x < im_width; x += tile_width) {
TIFFReadTile(tif, buffer, x, y, 0, 0);
width = MIN(im_width - x, tile_width);
height = MIN(im_height - y, tile_height);
if (bps == 16) {
} else if (bps == 8) {
readTiff8bit(buffer, im, photometric, x, y, width, height, has_alpha, extra, 0);
} else if (is_bw) {
readTiffBw(buffer, im, photometric, x, y, width, height, has_alpha, extra, 0);
} else {
/* TODO: implement some default reader or detect this case earlier use force_rgb */
}
}
}
gdFree(buffer);
return TRUE;
}
static int createFromTiffLines(TIFF *tif, gdImagePtr im, uint16 bps, uint16 photometric,
char has_alpha, char is_bw, int extra)
{
uint16 planar;
uint32 im_height, im_width, y;
unsigned char *buffer;
if (!TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planar)) {
planar = PLANARCONFIG_CONTIG;
}
if (!TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &im_height)) {
gd_error("Can't fetch TIFF height\n");
return FALSE;
}
if (!TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &im_width)) {
gd_error("Can't fetch TIFF width \n");
return FALSE;
}
buffer = (unsigned char *)gdMalloc(im_width * 4);
if (!buffer) {
return GD_FAILURE;
}
if (planar == PLANARCONFIG_CONTIG) {
switch (bps) {
case 16:
/* TODO
* or simply use force_rgba
*/
break;
case 8:
for (y = 0; y < im_height; y++ ) {
if (!TIFFReadScanline (tif, buffer, y, 0)) {
gd_error("Error while reading scanline %i", y);
break;
}
/* reading one line at a time */
readTiff8bit(buffer, im, photometric, 0, y, im_width, 1, has_alpha, extra, 0);
}
break;
default:
if (is_bw) {
for (y = 0; y < im_height; y++ ) {
if (!TIFFReadScanline (tif, buffer, y, 0)) {
gd_error("Error while reading scanline %i", y);
break;
}
/* reading one line at a time */
readTiffBw(buffer, im, photometric, 0, y, im_width, 1, has_alpha, extra, 0);
}
} else {
/* TODO: implement some default reader or detect this case earlier > force_rgb */
}
break;
}
} else {
/* TODO: implement a reader for separate panes. We detect this case earlier for now and use force_rgb */
}
gdFree(buffer);
return GD_SUCCESS;
}
static int createFromTiffRgba(TIFF * tif, gdImagePtr im)
{
int a;
int x, y;
int alphaBlendingFlag = 0;
int color;
int width = im->sx;
int height = im->sy;
uint32 *buffer;
uint32 rgba;
/* switch off colour merging on target gd image just while we write out
* content - we want to preserve the alpha data until the user chooses
* what to do with the image */
alphaBlendingFlag = im->alphaBlendingFlag;
gdImageAlphaBlending(im, 0);
buffer = (uint32 *) gdCalloc(sizeof(uint32), width * height);
if (!buffer) {
return GD_FAILURE;
}
TIFFReadRGBAImage(tif, width, height, buffer, 0);
for(y = 0; y < height; y++) {
for(x = 0; x < width; x++) {
/* if it doesn't already exist, allocate a new colour,
* else use existing one */
rgba = buffer[(y * width + x)];
a = (0xff - TIFFGetA(rgba)) / 2;
color = gdTrueColorAlpha(TIFFGetR(rgba), TIFFGetG(rgba), TIFFGetB(rgba), a);
/* set pixel colour to this colour */
gdImageSetPixel(im, x, height - y - 1, color);
}
}
gdFree(buffer);
/* now reset colour merge for alpha blending routines */
gdImageAlphaBlending(im, alphaBlendingFlag);
return GD_SUCCESS;
}
/*
Function: gdImageCreateFromTiffCtx
Create a gdImage from a TIFF file input from an gdIOCtx.
*/
BGD_DECLARE(gdImagePtr) gdImageCreateFromTiffCtx(gdIOCtx *infile)
{
TIFF *tif;
tiff_handle *th;
uint16 bps, spp, photometric;
uint16 orientation;
int width, height;
uint16 extra, *extra_types;
uint16 planar;
char has_alpha, is_bw, is_gray;
char force_rgba = FALSE;
char save_transparent;
int image_type;
int ret;
float res_float;
gdImagePtr im = NULL;
th = new_tiff_handle(infile);
if (!th) {
return NULL;
}
tif = TIFFClientOpen("", "rb", th, tiff_readproc,
tiff_writeproc,
tiff_seekproc,
tiff_closeproc,
tiff_sizeproc,
tiff_mapproc,
tiff_unmapproc);
if (!tif) {
gd_error("Cannot open TIFF image");
gdFree(th);
return NULL;
}
if (!TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width)) {
gd_error("TIFF error, Cannot read image width");
goto error;
}
if (!TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height)) {
gd_error("TIFF error, Cannot read image width");
goto error;
}
TIFFGetFieldDefaulted (tif, TIFFTAG_BITSPERSAMPLE, &bps);
/* Unsupported bps, force to RGBA */
if (1/*bps > 8 && bps != 16*/) {
force_rgba = TRUE;
}
TIFFGetFieldDefaulted (tif, TIFFTAG_SAMPLESPERPIXEL, &spp);
if (!TIFFGetField (tif, TIFFTAG_EXTRASAMPLES, &extra, &extra_types)) {
extra = 0;
}
if (!TIFFGetField (tif, TIFFTAG_PHOTOMETRIC, &photometric)) {
uint16 compression;
if (TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression) &&
(compression == COMPRESSION_CCITTFAX3 ||
compression == COMPRESSION_CCITTFAX4 ||
compression == COMPRESSION_CCITTRLE ||
compression == COMPRESSION_CCITTRLEW)) {
gd_error("Could not get photometric. "
"Image is CCITT compressed, assuming min-is-white");
photometric = PHOTOMETRIC_MINISWHITE;
} else {
gd_error("Could not get photometric. "
"Assuming min-is-black");
photometric = PHOTOMETRIC_MINISBLACK;
}
}
save_transparent = FALSE;
/* test if the extrasample represents an associated alpha channel... */
if (extra > 0 && (extra_types[0] == EXTRASAMPLE_ASSOCALPHA)) {
has_alpha = TRUE;
save_transparent = FALSE;
--extra;
} else if (extra > 0 && (extra_types[0] == EXTRASAMPLE_UNASSALPHA)) {
has_alpha = TRUE;
save_transparent = TRUE;
--extra;
} else if (extra > 0 && (extra_types[0] == EXTRASAMPLE_UNSPECIFIED)) {
/* assuming unassociated alpha if unspecified */
gd_error("alpha channel type not defined, assuming alpha is not premultiplied");
has_alpha = TRUE;
save_transparent = TRUE;
--extra;
} else {
has_alpha = FALSE;
}
if (photometric == PHOTOMETRIC_RGB && spp > 3 + extra) {
has_alpha = TRUE;
extra = spp - 4;
} else if (photometric != PHOTOMETRIC_RGB && spp > 1 + extra) {
has_alpha = TRUE;
extra = spp - 2;
}
is_bw = FALSE;
is_gray = FALSE;
switch (photometric) {
case PHOTOMETRIC_MINISBLACK:
case PHOTOMETRIC_MINISWHITE:
if (!has_alpha && bps == 1 && spp == 1) {
image_type = GD_INDEXED;
is_bw = TRUE;
} else {
image_type = GD_GRAY;
}
break;
case PHOTOMETRIC_RGB:
image_type = GD_RGB;
break;
case PHOTOMETRIC_PALETTE:
image_type = GD_INDEXED;
break;
default:
force_rgba = TRUE;
break;
}
if (!TIFFGetField (tif, TIFFTAG_PLANARCONFIG, &planar)) {
planar = PLANARCONFIG_CONTIG;
}
/* Force rgba if image plans are not contiguous */
if (force_rgba || planar != PLANARCONFIG_CONTIG) {
image_type = GD_RGB;
}
if (!force_rgba &&
(image_type == GD_PALETTE || image_type == GD_INDEXED || image_type == GD_GRAY)) {
im = gdImageCreate(width, height);
if (!im) goto error;
readTiffColorMap(im, tif, is_bw, photometric);
} else {
im = gdImageCreateTrueColor(width, height);
if (!im) goto error;
}
#ifdef DEBUG
printf("force rgba: %i\n", force_rgba);
printf("has_alpha: %i\n", has_alpha);
printf("save trans: %i\n", save_transparent);
printf("is_bw: %i\n", is_bw);
printf("is_gray: %i\n", is_gray);
printf("type: %i\n", image_type);
#else
(void)is_gray;
(void)save_transparent;
#endif
if (force_rgba) {
ret = createFromTiffRgba(tif, im);
} else if (TIFFIsTiled(tif)) {
ret = createFromTiffTiles(tif, im, bps, photometric, has_alpha, is_bw, extra);
} else {
ret = createFromTiffLines(tif, im, bps, photometric, has_alpha, is_bw, extra);
}
if (!ret) {
gdImageDestroy(im);
im = NULL;
goto error;
}
if (TIFFGetField(tif, TIFFTAG_XRESOLUTION, &res_float)) {
im->res_x = (unsigned int)res_float; //truncate
}
if (TIFFGetField(tif, TIFFTAG_YRESOLUTION, &res_float)) {
im->res_y = (unsigned int)res_float; //truncate
}
if (TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation)) {
switch (orientation) {
case ORIENTATION_TOPLEFT:
case ORIENTATION_TOPRIGHT:
case ORIENTATION_BOTRIGHT:
case ORIENTATION_BOTLEFT:
break;
default:
gd_error("Orientation %d not handled yet!", orientation);
break;
}
}
error:
TIFFClose(tif);
gdFree(th);
return im;
}
/*
Function: gdImageCreateFromTIFF
*/
BGD_DECLARE(gdImagePtr) gdImageCreateFromTiff(FILE *inFile)
{
gdImagePtr im;
gdIOCtx *in = gdNewFileCtx(inFile);
if (in == NULL) return NULL;
im = gdImageCreateFromTiffCtx(in);
in->gd_free(in);
return im;
}
/*
Function: gdImageCreateFromTiffPtr
*/
BGD_DECLARE(gdImagePtr) gdImageCreateFromTiffPtr(int size, void *data)
{
gdImagePtr im;
gdIOCtx *in = gdNewDynamicCtxEx (size, data, 0);
if (in == NULL) return NULL;
im = gdImageCreateFromTiffCtx(in);
in->gd_free(in);
return im;
}
/*
Function: gdImageTiff
*/
BGD_DECLARE(void) gdImageTiff(gdImagePtr im, FILE *outFile)
{
gdIOCtx *out = gdNewFileCtx(outFile);
if (out == NULL) return;
gdImageTiffCtx(im, out); /* what's an fg again? */
out->gd_free(out);
}
/*
Function: gdImageTiffPtr
*/
BGD_DECLARE(void *) gdImageTiffPtr(gdImagePtr im, int *size)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
if (out == NULL) return NULL;
gdImageTiffCtx(im, out); /* what's an fg again? */
rv = gdDPExtractData(out, size);
out->gd_free(out);
return rv;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5241_1 |
crossvul-cpp_data_bad_5483_0 | /* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001-2002 Intel Corp.
* Copyright (c) 2002 Nokia Corp.
*
* This is part of the SCTP Linux Kernel Implementation.
*
* These are the state functions for the state machine.
*
* This SCTP implementation is free software;
* you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This SCTP implementation is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied
* ************************
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU CC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <linux-sctp@vger.kernel.org>
*
* Written or modified by:
* La Monte H.P. Yarroll <piggy@acm.org>
* Karl Knutson <karl@athena.chicago.il.us>
* Mathew Kotowsky <kotowsky@sctp.org>
* Sridhar Samudrala <samudrala@us.ibm.com>
* Jon Grimm <jgrimm@us.ibm.com>
* Hui Huang <hui.huang@nokia.com>
* Dajiang Zhang <dajiang.zhang@nokia.com>
* Daisy Chang <daisyc@us.ibm.com>
* Ardelle Fan <ardelle.fan@intel.com>
* Ryan Layer <rmlayer@us.ibm.com>
* Kevin Gao <kevin.gao@intel.com>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/net.h>
#include <linux/inet.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/inet_ecn.h>
#include <linux/skbuff.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/structs.h>
static struct sctp_packet *sctp_abort_pkt_new(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
const void *payload,
size_t paylen);
static int sctp_eat_data(const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands);
static struct sctp_packet *sctp_ootb_pkt_new(struct net *net,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk);
static void sctp_send_stale_cookie_err(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_chunk *err_chunk);
static sctp_disposition_t sctp_sf_do_5_2_6_stale(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_shut_8_4_5(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_tabort_8_4_8(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk);
static sctp_disposition_t sctp_stop_t1_and_abort(struct net *net,
sctp_cmd_seq_t *commands,
__be16 error, int sk_err,
const struct sctp_association *asoc,
struct sctp_transport *transport);
static sctp_disposition_t sctp_sf_abort_violation(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
void *arg,
sctp_cmd_seq_t *commands,
const __u8 *payload,
const size_t paylen);
static sctp_disposition_t sctp_sf_violation_chunklen(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_violation_paramlen(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, void *ext,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_violation_ctsn(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_violation_chunk(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_ierror_t sctp_sf_authenticate(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
struct sctp_chunk *chunk);
static sctp_disposition_t __sctp_sf_do_9_1_abort(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
/* Small helper function that checks if the chunk length
* is of the appropriate length. The 'required_length' argument
* is set to be the size of a specific chunk we are testing.
* Return Values: 1 = Valid length
* 0 = Invalid length
*
*/
static inline int
sctp_chunk_length_valid(struct sctp_chunk *chunk,
__u16 required_length)
{
__u16 chunk_length = ntohs(chunk->chunk_hdr->length);
/* Previously already marked? */
if (unlikely(chunk->pdiscard))
return 0;
if (unlikely(chunk_length < required_length))
return 0;
return 1;
}
/**********************************************************
* These are the state functions for handling chunk events.
**********************************************************/
/*
* Process the final SHUTDOWN COMPLETE.
*
* Section: 4 (C) (diagram), 9.2
* Upon reception of the SHUTDOWN COMPLETE chunk the endpoint will verify
* that it is in SHUTDOWN-ACK-SENT state, if it is not the chunk should be
* discarded. If the endpoint is in the SHUTDOWN-ACK-SENT state the endpoint
* should stop the T2-shutdown timer and remove all knowledge of the
* association (and thus the association enters the CLOSED state).
*
* Verification Tag: 8.5.1(C), sctpimpguide 2.41.
* C) Rules for packet carrying SHUTDOWN COMPLETE:
* ...
* - The receiver of a SHUTDOWN COMPLETE shall accept the packet
* if the Verification Tag field of the packet matches its own tag and
* the T bit is not set
* OR
* it is set to its peer's tag and the T bit is set in the Chunk
* Flags.
* Otherwise, the receiver MUST silently discard the packet
* and take no further action. An endpoint MUST ignore the
* SHUTDOWN COMPLETE if it is not in the SHUTDOWN-ACK-SENT state.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_4_C(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_ulpevent *ev;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* RFC 2960 6.10 Bundling
*
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*/
if (!chunk->singleton)
return sctp_sf_violation_chunk(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN_COMPLETE chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* RFC 2960 10.2 SCTP-to-ULP
*
* H) SHUTDOWN COMPLETE notification
*
* When SCTP completes the shutdown procedures (section 9.2) this
* notification is passed to the upper layer.
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_SHUTDOWN_COMP,
0, 0, 0, NULL, GFP_ATOMIC);
if (ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
/* Upon reception of the SHUTDOWN COMPLETE chunk the endpoint
* will verify that it is in SHUTDOWN-ACK-SENT state, if it is
* not the chunk should be discarded. If the endpoint is in
* the SHUTDOWN-ACK-SENT state the endpoint should stop the
* T2-shutdown timer and remove all knowledge of the
* association (and thus the association enters the CLOSED
* state).
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
}
/*
* Respond to a normal INIT chunk.
* We are the side that is being asked for an association.
*
* Section: 5.1 Normal Establishment of an Association, B
* B) "Z" shall respond immediately with an INIT ACK chunk. The
* destination IP address of the INIT ACK MUST be set to the source
* IP address of the INIT to which this INIT ACK is responding. In
* the response, besides filling in other parameters, "Z" must set the
* Verification Tag field to Tag_A, and also provide its own
* Verification Tag (Tag_Z) in the Initiate Tag field.
*
* Verification Tag: Must be 0.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1B_init(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *repl;
struct sctp_association *new_asoc;
struct sctp_chunk *err_chunk;
struct sctp_packet *packet;
sctp_unrecognized_param_t *unk_param;
int len;
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*
* IG Section 2.11.2
* Furthermore, we require that the receiver of an INIT chunk MUST
* enforce these rules by silently discarding an arriving packet
* with an INIT chunk that is bundled with other chunks.
*/
if (!chunk->singleton)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* If the packet is an OOTB packet which is temporarily on the
* control endpoint, respond with an ABORT.
*/
if (ep == sctp_sk(net->sctp.ctl_sock)->ep) {
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
}
/* 3.1 A packet containing an INIT chunk MUST have a zero Verification
* Tag.
*/
if (chunk->sctp_hdr->vtag != 0)
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
/* Make sure that the INIT chunk has a valid length.
* Normally, this would cause an ABORT with a Protocol Violation
* error, but since we don't have an association, we'll
* just discard the packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_init_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* If the INIT is coming toward a closing socket, we'll send back
* and ABORT. Essentially, this catches the race of INIT being
* backloged to the socket at the same time as the user isses close().
* Since the socket and all its associations are going away, we
* can treat this OOTB
*/
if (sctp_sstate(ep->base.sk, CLOSING))
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type,
(sctp_init_chunk_t *)chunk->chunk_hdr, chunk,
&err_chunk)) {
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes if there is any.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(net, ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t));
sctp_chunk_free(err_chunk);
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
return SCTP_DISPOSITION_CONSUME;
} else {
return SCTP_DISPOSITION_NOMEM;
}
} else {
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg,
commands);
}
}
/* Grab the INIT header. */
chunk->subh.init_hdr = (sctp_inithdr_t *)chunk->skb->data;
/* Tag the variable length parameters. */
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t));
new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC);
if (!new_asoc)
goto nomem;
if (sctp_assoc_set_bind_addr_from_ep(new_asoc,
sctp_scope(sctp_source(chunk)),
GFP_ATOMIC) < 0)
goto nomem_init;
/* The call, sctp_process_init(), can fail on memory allocation. */
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk),
(sctp_init_chunk_t *)chunk->chunk_hdr,
GFP_ATOMIC))
goto nomem_init;
/* B) "Z" shall respond immediately with an INIT ACK chunk. */
/* If there are errors need to be reported for unknown parameters,
* make sure to reserve enough room in the INIT ACK for them.
*/
len = 0;
if (err_chunk)
len = ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t);
repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len);
if (!repl)
goto nomem_init;
/* If there are errors need to be reported for unknown parameters,
* include them in the outgoing INIT ACK as "Unrecognized parameter"
* parameter.
*/
if (err_chunk) {
/* Get the "Unrecognized parameter" parameter(s) out of the
* ERROR chunk generated by sctp_verify_init(). Since the
* error cause code for "unknown parameter" and the
* "Unrecognized parameter" type is the same, we can
* construct the parameters in INIT ACK by copying the
* ERROR causes over.
*/
unk_param = (sctp_unrecognized_param_t *)
((__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t));
/* Replace the cause code with the "Unrecognized parameter"
* parameter type.
*/
sctp_addto_chunk(repl, len, unk_param);
sctp_chunk_free(err_chunk);
}
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/*
* Note: After sending out INIT ACK with the State Cookie parameter,
* "Z" MUST NOT allocate any resources, nor keep any states for the
* new association. Otherwise, "Z" will be vulnerable to resource
* attacks.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
nomem_init:
sctp_association_free(new_asoc);
nomem:
if (err_chunk)
sctp_chunk_free(err_chunk);
return SCTP_DISPOSITION_NOMEM;
}
/*
* Respond to a normal INIT ACK chunk.
* We are the side that is initiating the association.
*
* Section: 5.1 Normal Establishment of an Association, C
* C) Upon reception of the INIT ACK from "Z", "A" shall stop the T1-init
* timer and leave COOKIE-WAIT state. "A" shall then send the State
* Cookie received in the INIT ACK chunk in a COOKIE ECHO chunk, start
* the T1-cookie timer, and enter the COOKIE-ECHOED state.
*
* Note: The COOKIE ECHO chunk can be bundled with any pending outbound
* DATA chunks, but it MUST be the first chunk in the packet and
* until the COOKIE ACK is returned the sender MUST NOT send any
* other packets to the peer.
*
* Verification Tag: 3.3.3
* If the value of the Initiate Tag in a received INIT ACK chunk is
* found to be 0, the receiver MUST treat it as an error and close the
* association by transmitting an ABORT.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1C_ack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_init_chunk_t *initchunk;
struct sctp_chunk *err_chunk;
struct sctp_packet *packet;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*/
if (!chunk->singleton)
return sctp_sf_violation_chunk(net, ep, asoc, type, arg, commands);
/* Make sure that the INIT-ACK chunk has a valid length */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_initack_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Grab the INIT header. */
chunk->subh.init_hdr = (sctp_inithdr_t *) chunk->skb->data;
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type,
(sctp_init_chunk_t *)chunk->chunk_hdr, chunk,
&err_chunk)) {
sctp_error_t error = SCTP_ERROR_NO_RESOURCE;
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes. If there are no causes,
* then there wasn't enough memory. Just terminate
* the association.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(net, ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t));
sctp_chunk_free(err_chunk);
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
error = SCTP_ERROR_INV_PARAM;
}
}
/* SCTP-AUTH, Section 6.3:
* It should be noted that if the receiver wants to tear
* down an association in an authenticated way only, the
* handling of malformed packets should not result in
* tearing down the association.
*
* This means that if we only want to abort associations
* in an authenticated way (i.e AUTH+ABORT), then we
* can't destroy this association just because the packet
* was malformed.
*/
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
return sctp_stop_t1_and_abort(net, commands, error, ECONNREFUSED,
asoc, chunk->transport);
}
/* Tag the variable length parameters. Note that we never
* convert the parameters in an INIT chunk.
*/
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t));
initchunk = (sctp_init_chunk_t *) chunk->chunk_hdr;
sctp_add_cmd_sf(commands, SCTP_CMD_PEER_INIT,
SCTP_PEER_INIT(initchunk));
/* Reset init error count upon receipt of INIT-ACK. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_RESET, SCTP_NULL());
/* 5.1 C) "A" shall stop the T1-init timer and leave
* COOKIE-WAIT state. "A" shall then ... start the T1-cookie
* timer, and enter the COOKIE-ECHOED state.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_COOKIE_ECHOED));
/* SCTP-AUTH: genereate the assocition shared keys so that
* we can potentially signe the COOKIE-ECHO.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_SHKEY, SCTP_NULL());
/* 5.1 C) "A" shall then send the State Cookie received in the
* INIT ACK chunk in a COOKIE ECHO chunk, ...
*/
/* If there is any errors to report, send the ERROR chunk generated
* for unknown parameters as well.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_COOKIE_ECHO,
SCTP_CHUNK(err_chunk));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Respond to a normal COOKIE ECHO chunk.
* We are the side that is being asked for an association.
*
* Section: 5.1 Normal Establishment of an Association, D
* D) Upon reception of the COOKIE ECHO chunk, Endpoint "Z" will reply
* with a COOKIE ACK chunk after building a TCB and moving to
* the ESTABLISHED state. A COOKIE ACK chunk may be bundled with
* any pending DATA chunks (and/or SACK chunks), but the COOKIE ACK
* chunk MUST be the first chunk in the packet.
*
* IMPLEMENTATION NOTE: An implementation may choose to send the
* Communication Up notification to the SCTP user upon reception
* of a valid COOKIE ECHO chunk.
*
* Verification Tag: 8.5.1 Exceptions in Verification Tag Rules
* D) Rules for packet carrying a COOKIE ECHO
*
* - When sending a COOKIE ECHO, the endpoint MUST use the value of the
* Initial Tag received in the INIT ACK.
*
* - The receiver of a COOKIE ECHO follows the procedures in Section 5.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1D_ce(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_association *new_asoc;
sctp_init_chunk_t *peer_init;
struct sctp_chunk *repl;
struct sctp_ulpevent *ev, *ai_ev = NULL;
int error = 0;
struct sctp_chunk *err_chk_p;
struct sock *sk;
/* If the packet is an OOTB packet which is temporarily on the
* control endpoint, respond with an ABORT.
*/
if (ep == sctp_sk(net->sctp.ctl_sock)->ep) {
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
}
/* Make sure that the COOKIE_ECHO chunk has a valid length.
* In this case, we check that we have enough for at least a
* chunk header. More detailed verification is done
* in sctp_unpack_cookie().
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* If the endpoint is not listening or if the number of associations
* on the TCP-style socket exceed the max backlog, respond with an
* ABORT.
*/
sk = ep->base.sk;
if (!sctp_sstate(sk, LISTENING) ||
(sctp_style(sk, TCP) && sk_acceptq_is_full(sk)))
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
/* "Decode" the chunk. We have no optional parameters so we
* are in good shape.
*/
chunk->subh.cookie_hdr =
(struct sctp_signed_cookie *)chunk->skb->data;
if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t)))
goto nomem;
/* 5.1 D) Upon reception of the COOKIE ECHO chunk, Endpoint
* "Z" will reply with a COOKIE ACK chunk after building a TCB
* and moving to the ESTABLISHED state.
*/
new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error,
&err_chk_p);
/* FIXME:
* If the re-build failed, what is the proper error path
* from here?
*
* [We should abort the association. --piggy]
*/
if (!new_asoc) {
/* FIXME: Several errors are possible. A bad cookie should
* be silently discarded, but think about logging it too.
*/
switch (error) {
case -SCTP_IERROR_NOMEM:
goto nomem;
case -SCTP_IERROR_STALE_COOKIE:
sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands,
err_chk_p);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case -SCTP_IERROR_BAD_SIG:
default:
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
}
/* Delay state machine commands until later.
*
* Re-build the bind address for the association is done in
* the sctp_unpack_cookie() already.
*/
/* This is a brand-new association, so these are not yet side
* effects--it is safe to run them here.
*/
peer_init = &chunk->subh.cookie_hdr->c.peer_init[0];
if (!sctp_process_init(new_asoc, chunk,
&chunk->subh.cookie_hdr->c.peer_addr,
peer_init, GFP_ATOMIC))
goto nomem_init;
/* SCTP-AUTH: Now that we've populate required fields in
* sctp_process_init, set up the assocaition shared keys as
* necessary so that we can potentially authenticate the ACK
*/
error = sctp_auth_asoc_init_active_key(new_asoc, GFP_ATOMIC);
if (error)
goto nomem_init;
/* SCTP-AUTH: auth_chunk pointer is only set when the cookie-echo
* is supposed to be authenticated and we have to do delayed
* authentication. We've just recreated the association using
* the information in the cookie and now it's much easier to
* do the authentication.
*/
if (chunk->auth_chunk) {
struct sctp_chunk auth;
sctp_ierror_t ret;
/* Make sure that we and the peer are AUTH capable */
if (!net->sctp.auth_enable || !new_asoc->peer.auth_capable) {
sctp_association_free(new_asoc);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* set-up our fake chunk so that we can process it */
auth.skb = chunk->auth_chunk;
auth.asoc = chunk->asoc;
auth.sctp_hdr = chunk->sctp_hdr;
auth.chunk_hdr = (sctp_chunkhdr_t *)skb_push(chunk->auth_chunk,
sizeof(sctp_chunkhdr_t));
skb_pull(chunk->auth_chunk, sizeof(sctp_chunkhdr_t));
auth.transport = chunk->transport;
ret = sctp_sf_authenticate(net, ep, new_asoc, type, &auth);
if (ret != SCTP_IERROR_NO_ERROR) {
sctp_association_free(new_asoc);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
}
repl = sctp_make_cookie_ack(new_asoc, chunk);
if (!repl)
goto nomem_init;
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose to
* send the Communication Up notification to the SCTP user
* upon reception of a valid COOKIE ECHO chunk.
*/
ev = sctp_ulpevent_make_assoc_change(new_asoc, 0, SCTP_COMM_UP, 0,
new_asoc->c.sinit_num_ostreams,
new_asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem_ev;
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*/
if (new_asoc->peer.adaptation_ind) {
ai_ev = sctp_ulpevent_make_adaptation_indication(new_asoc,
GFP_ATOMIC);
if (!ai_ev)
goto nomem_aiev;
}
/* Add all the state machine commands now since we've created
* everything. This way we don't introduce memory corruptions
* during side-effect processing and correclty count established
* associations.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(net, SCTP_MIB_PASSIVEESTABS);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL());
if (new_asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* This will send the COOKIE ACK */
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/* Queue the ASSOC_CHANGE event */
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Send up the Adaptation Layer Indication event */
if (ai_ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ai_ev));
return SCTP_DISPOSITION_CONSUME;
nomem_aiev:
sctp_ulpevent_free(ev);
nomem_ev:
sctp_chunk_free(repl);
nomem_init:
sctp_association_free(new_asoc);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Respond to a normal COOKIE ACK chunk.
* We are the side that is asking for an association.
*
* RFC 2960 5.1 Normal Establishment of an Association
*
* E) Upon reception of the COOKIE ACK, endpoint "A" will move from the
* COOKIE-ECHOED state to the ESTABLISHED state, stopping the T1-cookie
* timer. It may also notify its ULP about the successful
* establishment of the association with a Communication Up
* notification (see Section 10).
*
* Verification Tag:
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1E_ca(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_ulpevent *ev;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Verify that the chunk length for the COOKIE-ACK is OK.
* If we don't do this, any bundled chunks may be junked.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Reset init error count upon receipt of COOKIE-ACK,
* to avoid problems with the managemement of this
* counter in stale cookie situations when a transition back
* from the COOKIE-ECHOED state to the COOKIE-WAIT
* state is performed.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_RESET, SCTP_NULL());
/* RFC 2960 5.1 Normal Establishment of an Association
*
* E) Upon reception of the COOKIE ACK, endpoint "A" will move
* from the COOKIE-ECHOED state to the ESTABLISHED state,
* stopping the T1-cookie timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(net, SCTP_MIB_ACTIVEESTABS);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL());
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* It may also notify its ULP about the successful
* establishment of the association with a Communication Up
* notification (see Section 10).
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_COMM_UP,
0, asoc->c.sinit_num_ostreams,
asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*/
if (asoc->peer.adaptation_ind) {
ev = sctp_ulpevent_make_adaptation_indication(asoc, GFP_ATOMIC);
if (!ev)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
}
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Generate and sendout a heartbeat packet. */
static sctp_disposition_t sctp_sf_heartbeat(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_transport *transport = (struct sctp_transport *) arg;
struct sctp_chunk *reply;
/* Send a heartbeat to our peer. */
reply = sctp_make_heartbeat(asoc, transport);
if (!reply)
return SCTP_DISPOSITION_NOMEM;
/* Set rto_pending indicating that an RTT measurement
* is started with this heartbeat chunk.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_RTO_PENDING,
SCTP_TRANSPORT(transport));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
}
/* Generate a HEARTBEAT packet on the given transport. */
sctp_disposition_t sctp_sf_sendbeat_8_3(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_transport *transport = (struct sctp_transport *) arg;
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
}
/* Section 3.3.5.
* The Sender-specific Heartbeat Info field should normally include
* information about the sender's current time when this HEARTBEAT
* chunk is sent and the destination transport address to which this
* HEARTBEAT is sent (see Section 8.3).
*/
if (transport->param_flags & SPP_HB_ENABLE) {
if (SCTP_DISPOSITION_NOMEM ==
sctp_sf_heartbeat(ep, asoc, type, arg,
commands))
return SCTP_DISPOSITION_NOMEM;
/* Set transport error counter and association error counter
* when sending heartbeat.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_HB_SENT,
SCTP_TRANSPORT(transport));
}
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_IDLE,
SCTP_TRANSPORT(transport));
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMER_UPDATE,
SCTP_TRANSPORT(transport));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process an heartbeat request.
*
* Section: 8.3 Path Heartbeat
* The receiver of the HEARTBEAT should immediately respond with a
* HEARTBEAT ACK that contains the Heartbeat Information field copied
* from the received HEARTBEAT chunk.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* When receiving an SCTP packet, the endpoint MUST ensure that the
* value in the Verification Tag field of the received SCTP packet
* matches its own Tag. If the received Verification Tag value does not
* match the receiver's own tag value, the receiver shall silently
* discard the packet and shall not process it any further except for
* those cases listed in Section 8.5.1 below.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_beat_8_3(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_paramhdr_t *param_hdr;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *reply;
size_t paylen = 0;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the HEARTBEAT chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_heartbeat_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* 8.3 The receiver of the HEARTBEAT should immediately
* respond with a HEARTBEAT ACK that contains the Heartbeat
* Information field copied from the received HEARTBEAT chunk.
*/
chunk->subh.hb_hdr = (sctp_heartbeathdr_t *) chunk->skb->data;
param_hdr = (sctp_paramhdr_t *) chunk->subh.hb_hdr;
paylen = ntohs(chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t);
if (ntohs(param_hdr->length) > paylen)
return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
param_hdr, commands);
if (!pskb_pull(chunk->skb, paylen))
goto nomem;
reply = sctp_make_heartbeat_ack(asoc, chunk, param_hdr, paylen);
if (!reply)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process the returning HEARTBEAT ACK.
*
* Section: 8.3 Path Heartbeat
* Upon the receipt of the HEARTBEAT ACK, the sender of the HEARTBEAT
* should clear the error counter of the destination transport
* address to which the HEARTBEAT was sent, and mark the destination
* transport address as active if it is not so marked. The endpoint may
* optionally report to the upper layer when an inactive destination
* address is marked as active due to the reception of the latest
* HEARTBEAT ACK. The receiver of the HEARTBEAT ACK must also
* clear the association overall error count as well (as defined
* in section 8.1).
*
* The receiver of the HEARTBEAT ACK should also perform an RTT
* measurement for that destination transport address using the time
* value carried in the HEARTBEAT ACK chunk.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_backbeat_8_3(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
union sctp_addr from_addr;
struct sctp_transport *link;
sctp_sender_hb_info_t *hbinfo;
unsigned long max_interval;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the HEARTBEAT-ACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t) +
sizeof(sctp_sender_hb_info_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
hbinfo = (sctp_sender_hb_info_t *) chunk->skb->data;
/* Make sure that the length of the parameter is what we expect */
if (ntohs(hbinfo->param_hdr.length) !=
sizeof(sctp_sender_hb_info_t)) {
return SCTP_DISPOSITION_DISCARD;
}
from_addr = hbinfo->daddr;
link = sctp_assoc_lookup_paddr(asoc, &from_addr);
/* This should never happen, but lets log it if so. */
if (unlikely(!link)) {
if (from_addr.sa.sa_family == AF_INET6) {
net_warn_ratelimited("%s association %p could not find address %pI6\n",
__func__,
asoc,
&from_addr.v6.sin6_addr);
} else {
net_warn_ratelimited("%s association %p could not find address %pI4\n",
__func__,
asoc,
&from_addr.v4.sin_addr.s_addr);
}
return SCTP_DISPOSITION_DISCARD;
}
/* Validate the 64-bit random nonce. */
if (hbinfo->hb_nonce != link->hb_nonce)
return SCTP_DISPOSITION_DISCARD;
max_interval = link->hbinterval + link->rto;
/* Check if the timestamp looks valid. */
if (time_after(hbinfo->sent_at, jiffies) ||
time_after(jiffies, hbinfo->sent_at + max_interval)) {
pr_debug("%s: HEARTBEAT ACK with invalid timestamp received "
"for transport:%p\n", __func__, link);
return SCTP_DISPOSITION_DISCARD;
}
/* 8.3 Upon the receipt of the HEARTBEAT ACK, the sender of
* the HEARTBEAT should clear the error counter of the
* destination transport address to which the HEARTBEAT was
* sent and mark the destination transport address as active if
* it is not so marked.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_ON, SCTP_TRANSPORT(link));
return SCTP_DISPOSITION_CONSUME;
}
/* Helper function to send out an abort for the restart
* condition.
*/
static int sctp_sf_send_restart_abort(struct net *net, union sctp_addr *ssa,
struct sctp_chunk *init,
sctp_cmd_seq_t *commands)
{
int len;
struct sctp_packet *pkt;
union sctp_addr_param *addrparm;
struct sctp_errhdr *errhdr;
struct sctp_endpoint *ep;
char buffer[sizeof(struct sctp_errhdr)+sizeof(union sctp_addr_param)];
struct sctp_af *af = sctp_get_af_specific(ssa->v4.sin_family);
/* Build the error on the stack. We are way to malloc crazy
* throughout the code today.
*/
errhdr = (struct sctp_errhdr *)buffer;
addrparm = (union sctp_addr_param *)errhdr->variable;
/* Copy into a parm format. */
len = af->to_addr_param(ssa, addrparm);
len += sizeof(sctp_errhdr_t);
errhdr->cause = SCTP_ERROR_RESTART;
errhdr->length = htons(len);
/* Assign to the control socket. */
ep = sctp_sk(net->sctp.ctl_sock)->ep;
/* Association is NULL since this may be a restart attack and we
* want to send back the attacker's vtag.
*/
pkt = sctp_abort_pkt_new(net, ep, NULL, init, errhdr, len);
if (!pkt)
goto out;
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(pkt));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
/* Discard the rest of the inbound packet. */
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
out:
/* Even if there is no memory, treat as a failure so
* the packet will get dropped.
*/
return 0;
}
static bool list_has_sctp_addr(const struct list_head *list,
union sctp_addr *ipaddr)
{
struct sctp_transport *addr;
list_for_each_entry(addr, list, transports) {
if (sctp_cmp_addr_exact(ipaddr, &addr->ipaddr))
return true;
}
return false;
}
/* A restart is occurring, check to make sure no new addresses
* are being added as we may be under a takeover attack.
*/
static int sctp_sf_check_restart_addrs(const struct sctp_association *new_asoc,
const struct sctp_association *asoc,
struct sctp_chunk *init,
sctp_cmd_seq_t *commands)
{
struct net *net = sock_net(new_asoc->base.sk);
struct sctp_transport *new_addr;
int ret = 1;
/* Implementor's Guide - Section 5.2.2
* ...
* Before responding the endpoint MUST check to see if the
* unexpected INIT adds new addresses to the association. If new
* addresses are added to the association, the endpoint MUST respond
* with an ABORT..
*/
/* Search through all current addresses and make sure
* we aren't adding any new ones.
*/
list_for_each_entry(new_addr, &new_asoc->peer.transport_addr_list,
transports) {
if (!list_has_sctp_addr(&asoc->peer.transport_addr_list,
&new_addr->ipaddr)) {
sctp_sf_send_restart_abort(net, &new_addr->ipaddr, init,
commands);
ret = 0;
break;
}
}
/* Return success if all addresses were found. */
return ret;
}
/* Populate the verification/tie tags based on overlapping INIT
* scenario.
*
* Note: Do not use in CLOSED or SHUTDOWN-ACK-SENT state.
*/
static void sctp_tietags_populate(struct sctp_association *new_asoc,
const struct sctp_association *asoc)
{
switch (asoc->state) {
/* 5.2.1 INIT received in COOKIE-WAIT or COOKIE-ECHOED State */
case SCTP_STATE_COOKIE_WAIT:
new_asoc->c.my_vtag = asoc->c.my_vtag;
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = 0;
break;
case SCTP_STATE_COOKIE_ECHOED:
new_asoc->c.my_vtag = asoc->c.my_vtag;
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = asoc->c.peer_vtag;
break;
/* 5.2.2 Unexpected INIT in States Other than CLOSED, COOKIE-ECHOED,
* COOKIE-WAIT and SHUTDOWN-ACK-SENT
*/
default:
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = asoc->c.peer_vtag;
break;
}
/* Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of
* outbound streams) into the INIT ACK and cookie.
*/
new_asoc->rwnd = asoc->rwnd;
new_asoc->c.sinit_num_ostreams = asoc->c.sinit_num_ostreams;
new_asoc->c.sinit_max_instreams = asoc->c.sinit_max_instreams;
new_asoc->c.initial_tsn = asoc->c.initial_tsn;
}
/*
* Compare vtag/tietag values to determine unexpected COOKIE-ECHO
* handling action.
*
* RFC 2960 5.2.4 Handle a COOKIE ECHO when a TCB exists.
*
* Returns value representing action to be taken. These action values
* correspond to Action/Description values in RFC 2960, Table 2.
*/
static char sctp_tietags_compare(struct sctp_association *new_asoc,
const struct sctp_association *asoc)
{
/* In this case, the peer may have restarted. */
if ((asoc->c.my_vtag != new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag != new_asoc->c.peer_vtag) &&
(asoc->c.my_vtag == new_asoc->c.my_ttag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_ttag))
return 'A';
/* Collision case B. */
if ((asoc->c.my_vtag == new_asoc->c.my_vtag) &&
((asoc->c.peer_vtag != new_asoc->c.peer_vtag) ||
(0 == asoc->c.peer_vtag))) {
return 'B';
}
/* Collision case D. */
if ((asoc->c.my_vtag == new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_vtag))
return 'D';
/* Collision case C. */
if ((asoc->c.my_vtag != new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_vtag) &&
(0 == new_asoc->c.my_ttag) &&
(0 == new_asoc->c.peer_ttag))
return 'C';
/* No match to any of the special cases; discard this packet. */
return 'E';
}
/* Common helper routine for both duplicate and simulataneous INIT
* chunk handling.
*/
static sctp_disposition_t sctp_sf_do_unexpected_init(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, sctp_cmd_seq_t *commands)
{
sctp_disposition_t retval;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *repl;
struct sctp_association *new_asoc;
struct sctp_chunk *err_chunk;
struct sctp_packet *packet;
sctp_unrecognized_param_t *unk_param;
int len;
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*
* IG Section 2.11.2
* Furthermore, we require that the receiver of an INIT chunk MUST
* enforce these rules by silently discarding an arriving packet
* with an INIT chunk that is bundled with other chunks.
*/
if (!chunk->singleton)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* 3.1 A packet containing an INIT chunk MUST have a zero Verification
* Tag.
*/
if (chunk->sctp_hdr->vtag != 0)
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
/* Make sure that the INIT chunk has a valid length.
* In this case, we generate a protocol violation since we have
* an association established.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_init_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Grab the INIT header. */
chunk->subh.init_hdr = (sctp_inithdr_t *) chunk->skb->data;
/* Tag the variable length parameters. */
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t));
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type,
(sctp_init_chunk_t *)chunk->chunk_hdr, chunk,
&err_chunk)) {
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes if there is any.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(net, ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t));
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
retval = SCTP_DISPOSITION_CONSUME;
} else {
retval = SCTP_DISPOSITION_NOMEM;
}
goto cleanup;
} else {
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg,
commands);
}
}
/*
* Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of
* outbound streams) into the INIT ACK and cookie.
* FIXME: We are copying parameters from the endpoint not the
* association.
*/
new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC);
if (!new_asoc)
goto nomem;
if (sctp_assoc_set_bind_addr_from_ep(new_asoc,
sctp_scope(sctp_source(chunk)), GFP_ATOMIC) < 0)
goto nomem;
/* In the outbound INIT ACK the endpoint MUST copy its current
* Verification Tag and Peers Verification tag into a reserved
* place (local tie-tag and per tie-tag) within the state cookie.
*/
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk),
(sctp_init_chunk_t *)chunk->chunk_hdr,
GFP_ATOMIC))
goto nomem;
/* Make sure no new addresses are being added during the
* restart. Do not do this check for COOKIE-WAIT state,
* since there are no peer addresses to check against.
* Upon return an ABORT will have been sent if needed.
*/
if (!sctp_state(asoc, COOKIE_WAIT)) {
if (!sctp_sf_check_restart_addrs(new_asoc, asoc, chunk,
commands)) {
retval = SCTP_DISPOSITION_CONSUME;
goto nomem_retval;
}
}
sctp_tietags_populate(new_asoc, asoc);
/* B) "Z" shall respond immediately with an INIT ACK chunk. */
/* If there are errors need to be reported for unknown parameters,
* make sure to reserve enough room in the INIT ACK for them.
*/
len = 0;
if (err_chunk) {
len = ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t);
}
repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len);
if (!repl)
goto nomem;
/* If there are errors need to be reported for unknown parameters,
* include them in the outgoing INIT ACK as "Unrecognized parameter"
* parameter.
*/
if (err_chunk) {
/* Get the "Unrecognized parameter" parameter(s) out of the
* ERROR chunk generated by sctp_verify_init(). Since the
* error cause code for "unknown parameter" and the
* "Unrecognized parameter" type is the same, we can
* construct the parameters in INIT ACK by copying the
* ERROR causes over.
*/
unk_param = (sctp_unrecognized_param_t *)
((__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t));
/* Replace the cause code with the "Unrecognized parameter"
* parameter type.
*/
sctp_addto_chunk(repl, len, unk_param);
}
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/*
* Note: After sending out INIT ACK with the State Cookie parameter,
* "Z" MUST NOT allocate any resources for this new association.
* Otherwise, "Z" will be vulnerable to resource attacks.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
retval = SCTP_DISPOSITION_CONSUME;
return retval;
nomem:
retval = SCTP_DISPOSITION_NOMEM;
nomem_retval:
if (new_asoc)
sctp_association_free(new_asoc);
cleanup:
if (err_chunk)
sctp_chunk_free(err_chunk);
return retval;
}
/*
* Handle simultaneous INIT.
* This means we started an INIT and then we got an INIT request from
* our peer.
*
* Section: 5.2.1 INIT received in COOKIE-WAIT or COOKIE-ECHOED State (Item B)
* This usually indicates an initialization collision, i.e., each
* endpoint is attempting, at about the same time, to establish an
* association with the other endpoint.
*
* Upon receipt of an INIT in the COOKIE-WAIT or COOKIE-ECHOED state, an
* endpoint MUST respond with an INIT ACK using the same parameters it
* sent in its original INIT chunk (including its Verification Tag,
* unchanged). These original parameters are combined with those from the
* newly received INIT chunk. The endpoint shall also generate a State
* Cookie with the INIT ACK. The endpoint uses the parameters sent in its
* INIT to calculate the State Cookie.
*
* After that, the endpoint MUST NOT change its state, the T1-init
* timer shall be left running and the corresponding TCB MUST NOT be
* destroyed. The normal procedures for handling State Cookies when
* a TCB exists will resolve the duplicate INITs to a single association.
*
* For an endpoint that is in the COOKIE-ECHOED state it MUST populate
* its Tie-Tags with the Tag information of itself and its peer (see
* section 5.2.2 for a description of the Tie-Tags).
*
* Verification Tag: Not explicit, but an INIT can not have a valid
* verification tag, so we skip the check.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_2_1_siminit(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Call helper to do the real work for both simulataneous and
* duplicate INIT chunk handling.
*/
return sctp_sf_do_unexpected_init(net, ep, asoc, type, arg, commands);
}
/*
* Handle duplicated INIT messages. These are usually delayed
* restransmissions.
*
* Section: 5.2.2 Unexpected INIT in States Other than CLOSED,
* COOKIE-ECHOED and COOKIE-WAIT
*
* Unless otherwise stated, upon reception of an unexpected INIT for
* this association, the endpoint shall generate an INIT ACK with a
* State Cookie. In the outbound INIT ACK the endpoint MUST copy its
* current Verification Tag and peer's Verification Tag into a reserved
* place within the state cookie. We shall refer to these locations as
* the Peer's-Tie-Tag and the Local-Tie-Tag. The outbound SCTP packet
* containing this INIT ACK MUST carry a Verification Tag value equal to
* the Initiation Tag found in the unexpected INIT. And the INIT ACK
* MUST contain a new Initiation Tag (randomly generated see Section
* 5.3.1). Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of outbound
* streams) into the INIT ACK and cookie.
*
* After sending out the INIT ACK, the endpoint shall take no further
* actions, i.e., the existing association, including its current state,
* and the corresponding TCB MUST NOT be changed.
*
* Note: Only when a TCB exists and the association is not in a COOKIE-
* WAIT state are the Tie-Tags populated. For a normal association INIT
* (i.e. the endpoint is in a COOKIE-WAIT state), the Tie-Tags MUST be
* set to 0 (indicating that no previous TCB existed). The INIT ACK and
* State Cookie are populated as specified in section 5.2.1.
*
* Verification Tag: Not specified, but an INIT has no way of knowing
* what the verification tag could be, so we ignore it.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_2_2_dupinit(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Call helper to do the real work for both simulataneous and
* duplicate INIT chunk handling.
*/
return sctp_sf_do_unexpected_init(net, ep, asoc, type, arg, commands);
}
/*
* Unexpected INIT-ACK handler.
*
* Section 5.2.3
* If an INIT ACK received by an endpoint in any state other than the
* COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk.
* An unexpected INIT ACK usually indicates the processing of an old or
* duplicated INIT chunk.
*/
sctp_disposition_t sctp_sf_do_5_2_3_initack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, sctp_cmd_seq_t *commands)
{
/* Per the above section, we'll discard the chunk if we have an
* endpoint. If this is an OOTB INIT-ACK, treat it as such.
*/
if (ep == sctp_sk(net->sctp.ctl_sock)->ep)
return sctp_sf_ootb(net, ep, asoc, type, arg, commands);
else
return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);
}
/* Unexpected COOKIE-ECHO handler for peer restart (Table 2, action 'A')
*
* Section 5.2.4
* A) In this case, the peer may have restarted.
*/
static sctp_disposition_t sctp_sf_do_dupcook_a(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
sctp_init_chunk_t *peer_init;
struct sctp_ulpevent *ev;
struct sctp_chunk *repl;
struct sctp_chunk *err;
sctp_disposition_t disposition;
/* new_asoc is a brand-new association, so these are not yet
* side effects--it is safe to run them here.
*/
peer_init = &chunk->subh.cookie_hdr->c.peer_init[0];
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init,
GFP_ATOMIC))
goto nomem;
/* Make sure no new addresses are being added during the
* restart. Though this is a pretty complicated attack
* since you'd have to get inside the cookie.
*/
if (!sctp_sf_check_restart_addrs(new_asoc, asoc, chunk, commands)) {
return SCTP_DISPOSITION_CONSUME;
}
/* If the endpoint is in the SHUTDOWN-ACK-SENT state and recognizes
* the peer has restarted (Action A), it MUST NOT setup a new
* association but instead resend the SHUTDOWN ACK and send an ERROR
* chunk with a "Cookie Received while Shutting Down" error cause to
* its peer.
*/
if (sctp_state(asoc, SHUTDOWN_ACK_SENT)) {
disposition = sctp_sf_do_9_2_reshutack(net, ep, asoc,
SCTP_ST_CHUNK(chunk->chunk_hdr->type),
chunk, commands);
if (SCTP_DISPOSITION_NOMEM == disposition)
goto nomem;
err = sctp_make_op_error(asoc, chunk,
SCTP_ERROR_COOKIE_IN_SHUTDOWN,
NULL, 0, 0);
if (err)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
return SCTP_DISPOSITION_CONSUME;
}
/* For now, stop pending T3-rtx and SACK timers, fail any unsent/unacked
* data. Consider the optional choice of resending of this data.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_T3_RTX_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_SACK));
sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_OUTQUEUE, SCTP_NULL());
/* Stop pending T4-rto timer, teardown ASCONF queue, ASCONF-ACK queue
* and ASCONF-ACK cache.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_ASCONF_QUEUE, SCTP_NULL());
repl = sctp_make_cookie_ack(new_asoc, chunk);
if (!repl)
goto nomem;
/* Report association restart to upper layer. */
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_RESTART, 0,
new_asoc->c.sinit_num_ostreams,
new_asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem_ev;
/* Update the content of current association. */
sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_ASSOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
if (sctp_state(asoc, SHUTDOWN_PENDING) &&
(sctp_sstate(asoc->base.sk, CLOSING) ||
sock_flag(asoc->base.sk, SOCK_DEAD))) {
/* if were currently in SHUTDOWN_PENDING, but the socket
* has been closed by user, don't transition to ESTABLISHED.
* Instead trigger SHUTDOWN bundled with COOKIE_ACK.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
return sctp_sf_do_9_2_start_shutdown(net, ep, asoc,
SCTP_ST_CHUNK(0), NULL,
commands);
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
}
return SCTP_DISPOSITION_CONSUME;
nomem_ev:
sctp_chunk_free(repl);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Unexpected COOKIE-ECHO handler for setup collision (Table 2, action 'B')
*
* Section 5.2.4
* B) In this case, both sides may be attempting to start an association
* at about the same time but the peer endpoint started its INIT
* after responding to the local endpoint's INIT
*/
/* This case represents an initialization collision. */
static sctp_disposition_t sctp_sf_do_dupcook_b(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
sctp_init_chunk_t *peer_init;
struct sctp_chunk *repl;
/* new_asoc is a brand-new association, so these are not yet
* side effects--it is safe to run them here.
*/
peer_init = &chunk->subh.cookie_hdr->c.peer_init[0];
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init,
GFP_ATOMIC))
goto nomem;
/* Update the content of current association. */
sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_ASSOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL());
repl = sctp_make_cookie_ack(new_asoc, chunk);
if (!repl)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose to
* send the Communication Up notification to the SCTP user
* upon reception of a valid COOKIE ECHO chunk.
*
* Sadly, this needs to be implemented as a side-effect, because
* we are not guaranteed to have set the association id of the real
* association and so these notifications need to be delayed until
* the association id is allocated.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_CHANGE, SCTP_U8(SCTP_COMM_UP));
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*
* This also needs to be done as a side effect for the same reason as
* above.
*/
if (asoc->peer.adaptation_ind)
sctp_add_cmd_sf(commands, SCTP_CMD_ADAPTATION_IND, SCTP_NULL());
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Unexpected COOKIE-ECHO handler for setup collision (Table 2, action 'C')
*
* Section 5.2.4
* C) In this case, the local endpoint's cookie has arrived late.
* Before it arrived, the local endpoint sent an INIT and received an
* INIT-ACK and finally sent a COOKIE ECHO with the peer's same tag
* but a new tag of its own.
*/
/* This case represents an initialization collision. */
static sctp_disposition_t sctp_sf_do_dupcook_c(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
/* The cookie should be silently discarded.
* The endpoint SHOULD NOT change states and should leave
* any timers running.
*/
return SCTP_DISPOSITION_DISCARD;
}
/* Unexpected COOKIE-ECHO handler lost chunk (Table 2, action 'D')
*
* Section 5.2.4
*
* D) When both local and remote tags match the endpoint should always
* enter the ESTABLISHED state, if it has not already done so.
*/
/* This case represents an initialization collision. */
static sctp_disposition_t sctp_sf_do_dupcook_d(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
struct sctp_ulpevent *ev = NULL, *ai_ev = NULL;
struct sctp_chunk *repl;
/* Clarification from Implementor's Guide:
* D) When both local and remote tags match the endpoint should
* enter the ESTABLISHED state, if it is in the COOKIE-ECHOED state.
* It should stop any cookie timer that may be running and send
* a COOKIE ACK.
*/
/* Don't accidentally move back into established state. */
if (asoc->state < SCTP_STATE_ESTABLISHED) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START,
SCTP_NULL());
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose
* to send the Communication Up notification to the
* SCTP user upon reception of a valid COOKIE
* ECHO chunk.
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0,
SCTP_COMM_UP, 0,
asoc->c.sinit_num_ostreams,
asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter,
* SCTP delivers this notification to inform the application
* that of the peers requested adaptation layer.
*/
if (asoc->peer.adaptation_ind) {
ai_ev = sctp_ulpevent_make_adaptation_indication(asoc,
GFP_ATOMIC);
if (!ai_ev)
goto nomem;
}
}
repl = sctp_make_cookie_ack(new_asoc, chunk);
if (!repl)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
if (ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
if (ai_ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ai_ev));
return SCTP_DISPOSITION_CONSUME;
nomem:
if (ai_ev)
sctp_ulpevent_free(ai_ev);
if (ev)
sctp_ulpevent_free(ev);
return SCTP_DISPOSITION_NOMEM;
}
/*
* Handle a duplicate COOKIE-ECHO. This usually means a cookie-carrying
* chunk was retransmitted and then delayed in the network.
*
* Section: 5.2.4 Handle a COOKIE ECHO when a TCB exists
*
* Verification Tag: None. Do cookie validation.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_2_4_dupcook(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_disposition_t retval;
struct sctp_chunk *chunk = arg;
struct sctp_association *new_asoc;
int error = 0;
char action;
struct sctp_chunk *err_chk_p;
/* Make sure that the chunk has a valid length from the protocol
* perspective. In this case check to make sure we have at least
* enough for the chunk header. Cookie length verification is
* done later.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* "Decode" the chunk. We have no optional parameters so we
* are in good shape.
*/
chunk->subh.cookie_hdr = (struct sctp_signed_cookie *)chunk->skb->data;
if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t)))
goto nomem;
/* In RFC 2960 5.2.4 3, if both Verification Tags in the State Cookie
* of a duplicate COOKIE ECHO match the Verification Tags of the
* current association, consider the State Cookie valid even if
* the lifespan is exceeded.
*/
new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error,
&err_chk_p);
/* FIXME:
* If the re-build failed, what is the proper error path
* from here?
*
* [We should abort the association. --piggy]
*/
if (!new_asoc) {
/* FIXME: Several errors are possible. A bad cookie should
* be silently discarded, but think about logging it too.
*/
switch (error) {
case -SCTP_IERROR_NOMEM:
goto nomem;
case -SCTP_IERROR_STALE_COOKIE:
sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands,
err_chk_p);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case -SCTP_IERROR_BAD_SIG:
default:
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
}
/* Compare the tie_tag in cookie with the verification tag of
* current association.
*/
action = sctp_tietags_compare(new_asoc, asoc);
switch (action) {
case 'A': /* Association restart. */
retval = sctp_sf_do_dupcook_a(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'B': /* Collision case B. */
retval = sctp_sf_do_dupcook_b(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'C': /* Collision case C. */
retval = sctp_sf_do_dupcook_c(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'D': /* Collision case D. */
retval = sctp_sf_do_dupcook_d(net, ep, asoc, chunk, commands,
new_asoc);
break;
default: /* Discard packet for all others. */
retval = sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
break;
}
/* Delete the tempory new association. */
sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
/* Restore association pointer to provide SCTP command interpeter
* with a valid context in case it needs to manipulate
* the queues */
sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC,
SCTP_ASOC((struct sctp_association *)asoc));
return retval;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process an ABORT. (SHUTDOWN-PENDING state)
*
* See sctp_sf_do_9_1_abort().
*/
sctp_disposition_t sctp_sf_shutdown_pending_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest))
return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);
return __sctp_sf_do_9_1_abort(net, ep, asoc, type, arg, commands);
}
/*
* Process an ABORT. (SHUTDOWN-SENT state)
*
* See sctp_sf_do_9_1_abort().
*/
sctp_disposition_t sctp_sf_shutdown_sent_abort(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest))
return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);
/* Stop the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
return __sctp_sf_do_9_1_abort(net, ep, asoc, type, arg, commands);
}
/*
* Process an ABORT. (SHUTDOWN-ACK-SENT state)
*
* See sctp_sf_do_9_1_abort().
*/
sctp_disposition_t sctp_sf_shutdown_ack_sent_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* The same T2 timer, so we should be able to use
* common function with the SHUTDOWN-SENT state.
*/
return sctp_sf_shutdown_sent_abort(net, ep, asoc, type, arg, commands);
}
/*
* Handle an Error received in COOKIE_ECHOED state.
*
* Only handle the error type of stale COOKIE Error, the other errors will
* be ignored.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_cookie_echoed_err(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_errhdr_t *err;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ERROR chunk has a valid length.
* The parameter walking depends on this as well.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_operr_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Process the error here */
/* FUTURE FIXME: When PR-SCTP related and other optional
* parms are emitted, this will have to change to handle multiple
* errors.
*/
sctp_walk_errors(err, chunk->chunk_hdr) {
if (SCTP_ERROR_STALE_COOKIE == err->cause)
return sctp_sf_do_5_2_6_stale(net, ep, asoc, type,
arg, commands);
}
/* It is possible to have malformed error causes, and that
* will cause us to end the walk early. However, since
* we are discarding the packet, there should be no adverse
* affects.
*/
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/*
* Handle a Stale COOKIE Error
*
* Section: 5.2.6 Handle Stale COOKIE Error
* If the association is in the COOKIE-ECHOED state, the endpoint may elect
* one of the following three alternatives.
* ...
* 3) Send a new INIT chunk to the endpoint, adding a Cookie
* Preservative parameter requesting an extension to the lifetime of
* the State Cookie. When calculating the time extension, an
* implementation SHOULD use the RTT information measured based on the
* previous COOKIE ECHO / ERROR exchange, and should add no more
* than 1 second beyond the measured RTT, due to long State Cookie
* lifetimes making the endpoint more subject to a replay attack.
*
* Verification Tag: Not explicit, but safe to ignore.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
static sctp_disposition_t sctp_sf_do_5_2_6_stale(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
u32 stale;
sctp_cookie_preserve_param_t bht;
sctp_errhdr_t *err;
struct sctp_chunk *reply;
struct sctp_bind_addr *bp;
int attempts = asoc->init_err_counter + 1;
if (attempts > asoc->max_init_attempts) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_STALE_COOKIE));
return SCTP_DISPOSITION_DELETE_TCB;
}
err = (sctp_errhdr_t *)(chunk->skb->data);
/* When calculating the time extension, an implementation
* SHOULD use the RTT information measured based on the
* previous COOKIE ECHO / ERROR exchange, and should add no
* more than 1 second beyond the measured RTT, due to long
* State Cookie lifetimes making the endpoint more subject to
* a replay attack.
* Measure of Staleness's unit is usec. (1/1000000 sec)
* Suggested Cookie Life-span Increment's unit is msec.
* (1/1000 sec)
* In general, if you use the suggested cookie life, the value
* found in the field of measure of staleness should be doubled
* to give ample time to retransmit the new cookie and thus
* yield a higher probability of success on the reattempt.
*/
stale = ntohl(*(__be32 *)((u8 *)err + sizeof(sctp_errhdr_t)));
stale = (stale * 2) / 1000;
bht.param_hdr.type = SCTP_PARAM_COOKIE_PRESERVATIVE;
bht.param_hdr.length = htons(sizeof(bht));
bht.lifespan_increment = htonl(stale);
/* Build that new INIT chunk. */
bp = (struct sctp_bind_addr *) &asoc->base.bind_addr;
reply = sctp_make_init(asoc, bp, GFP_ATOMIC, sizeof(bht));
if (!reply)
goto nomem;
sctp_addto_chunk(reply, sizeof(bht), &bht);
/* Clear peer's init_tag cached in assoc as we are sending a new INIT */
sctp_add_cmd_sf(commands, SCTP_CMD_CLEAR_INIT_TAG, SCTP_NULL());
/* Stop pending T3-rtx and heartbeat timers */
sctp_add_cmd_sf(commands, SCTP_CMD_T3_RTX_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL());
/* Delete non-primary peer ip addresses since we are transitioning
* back to the COOKIE-WAIT state
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DEL_NON_PRIMARY, SCTP_NULL());
/* If we've sent any data bundled with COOKIE-ECHO we will need to
* resend
*/
sctp_add_cmd_sf(commands, SCTP_CMD_T1_RETRAN,
SCTP_TRANSPORT(asoc->peer.primary_path));
/* Cast away the const modifier, as we want to just
* rerun it through as a sideffect.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_INC, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_COOKIE_WAIT));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process an ABORT.
*
* Section: 9.1
* After checking the Verification Tag, the receiving endpoint shall
* remove the association from its record, and shall report the
* termination to its upper layer.
*
* Verification Tag: 8.5.1 Exceptions in Verification Tag Rules
* B) Rules for packet carrying ABORT:
*
* - The endpoint shall always fill in the Verification Tag field of the
* outbound packet with the destination endpoint's tag value if it
* is known.
*
* - If the ABORT is sent in response to an OOTB packet, the endpoint
* MUST follow the procedure described in Section 8.4.
*
* - The receiver MUST accept the packet if the Verification Tag
* matches either its own tag, OR the tag of its peer. Otherwise, the
* receiver MUST silently discard the packet and take no further
* action.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_9_1_abort(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest))
return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);
return __sctp_sf_do_9_1_abort(net, ep, asoc, type, arg, commands);
}
static sctp_disposition_t __sctp_sf_do_9_1_abort(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
unsigned int len;
__be16 error = SCTP_ERROR_NO_ERROR;
/* See if we have an error cause code in the chunk. */
len = ntohs(chunk->chunk_hdr->length);
if (len >= sizeof(struct sctp_chunkhdr) + sizeof(struct sctp_errhdr)) {
sctp_errhdr_t *err;
sctp_walk_errors(err, chunk->chunk_hdr);
if ((void *)err != (void *)chunk->chunk_end)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
error = ((sctp_errhdr_t *)chunk->skb->data)->cause;
}
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNRESET));
/* ASSOC_FAILED will DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(error));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
/*
* Process an ABORT. (COOKIE-WAIT state)
*
* See sctp_sf_do_9_1_abort() above.
*/
sctp_disposition_t sctp_sf_cookie_wait_abort(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
unsigned int len;
__be16 error = SCTP_ERROR_NO_ERROR;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* See if we have an error cause code in the chunk. */
len = ntohs(chunk->chunk_hdr->length);
if (len >= sizeof(struct sctp_chunkhdr) + sizeof(struct sctp_errhdr))
error = ((sctp_errhdr_t *)chunk->skb->data)->cause;
return sctp_stop_t1_and_abort(net, commands, error, ECONNREFUSED, asoc,
chunk->transport);
}
/*
* Process an incoming ICMP as an ABORT. (COOKIE-WAIT state)
*/
sctp_disposition_t sctp_sf_cookie_wait_icmp_abort(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
return sctp_stop_t1_and_abort(net, commands, SCTP_ERROR_NO_ERROR,
ENOPROTOOPT, asoc,
(struct sctp_transport *)arg);
}
/*
* Process an ABORT. (COOKIE-ECHOED state)
*/
sctp_disposition_t sctp_sf_cookie_echoed_abort(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return sctp_sf_cookie_wait_abort(net, ep, asoc, type, arg, commands);
}
/*
* Stop T1 timer and abort association with "INIT failed".
*
* This is common code called by several sctp_sf_*_abort() functions above.
*/
static sctp_disposition_t sctp_stop_t1_and_abort(struct net *net,
sctp_cmd_seq_t *commands,
__be16 error, int sk_err,
const struct sctp_association *asoc,
struct sctp_transport *transport)
{
pr_debug("%s: ABORT received (INIT)\n", __func__);
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(sk_err));
/* CMD_INIT_FAILED will DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(error));
return SCTP_DISPOSITION_ABORT;
}
/*
* sctp_sf_do_9_2_shut
*
* Section: 9.2
* Upon the reception of the SHUTDOWN, the peer endpoint shall
* - enter the SHUTDOWN-RECEIVED state,
*
* - stop accepting new data from its SCTP user
*
* - verify, by checking the Cumulative TSN Ack field of the chunk,
* that all its outstanding DATA chunks have been received by the
* SHUTDOWN sender.
*
* Once an endpoint as reached the SHUTDOWN-RECEIVED state it MUST NOT
* send a SHUTDOWN in response to a ULP request. And should discard
* subsequent SHUTDOWN chunks.
*
* If there are still outstanding DATA chunks left, the SHUTDOWN
* receiver shall continue to follow normal data transmission
* procedures defined in Section 6 until all outstanding DATA chunks
* are acknowledged; however, the SHUTDOWN receiver MUST NOT accept
* new data from its SCTP user.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_9_2_shutdown(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_shutdownhdr_t *sdh;
sctp_disposition_t disposition;
struct sctp_ulpevent *ev;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk,
sizeof(struct sctp_shutdown_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Convert the elaborate header. */
sdh = (sctp_shutdownhdr_t *)chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_shutdownhdr_t));
chunk->subh.shutdown_hdr = sdh;
ctsn = ntohl(sdh->cum_tsn_ack);
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn,
asoc->ctsn_ack_point);
return SCTP_DISPOSITION_DISCARD;
}
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (!TSN_lt(ctsn, asoc->next_tsn))
return sctp_sf_violation_ctsn(net, ep, asoc, type, arg, commands);
/* API 5.3.1.5 SCTP_SHUTDOWN_EVENT
* When a peer sends a SHUTDOWN, SCTP delivers this notification to
* inform the application that it should cease sending data.
*/
ev = sctp_ulpevent_make_shutdown_event(asoc, 0, GFP_ATOMIC);
if (!ev) {
disposition = SCTP_DISPOSITION_NOMEM;
goto out;
}
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Upon the reception of the SHUTDOWN, the peer endpoint shall
* - enter the SHUTDOWN-RECEIVED state,
* - stop accepting new data from its SCTP user
*
* [This is implicit in the new state.]
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_RECEIVED));
disposition = SCTP_DISPOSITION_CONSUME;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = sctp_sf_do_9_2_shutdown_ack(net, ep, asoc, type,
arg, commands);
}
if (SCTP_DISPOSITION_NOMEM == disposition)
goto out;
/* - verify, by checking the Cumulative TSN Ack field of the
* chunk, that all its outstanding DATA chunks have been
* received by the SHUTDOWN sender.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_CTSN,
SCTP_BE32(chunk->subh.shutdown_hdr->cum_tsn_ack));
out:
return disposition;
}
/*
* sctp_sf_do_9_2_shut_ctsn
*
* Once an endpoint has reached the SHUTDOWN-RECEIVED state,
* it MUST NOT send a SHUTDOWN in response to a ULP request.
* The Cumulative TSN Ack of the received SHUTDOWN chunk
* MUST be processed.
*/
sctp_disposition_t sctp_sf_do_9_2_shut_ctsn(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_shutdownhdr_t *sdh;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk,
sizeof(struct sctp_shutdown_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
sdh = (sctp_shutdownhdr_t *)chunk->skb->data;
ctsn = ntohl(sdh->cum_tsn_ack);
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn,
asoc->ctsn_ack_point);
return SCTP_DISPOSITION_DISCARD;
}
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (!TSN_lt(ctsn, asoc->next_tsn))
return sctp_sf_violation_ctsn(net, ep, asoc, type, arg, commands);
/* verify, by checking the Cumulative TSN Ack field of the
* chunk, that all its outstanding DATA chunks have been
* received by the SHUTDOWN sender.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_CTSN,
SCTP_BE32(sdh->cum_tsn_ack));
return SCTP_DISPOSITION_CONSUME;
}
/* RFC 2960 9.2
* If an endpoint is in SHUTDOWN-ACK-SENT state and receives an INIT chunk
* (e.g., if the SHUTDOWN COMPLETE was lost) with source and destination
* transport addresses (either in the IP addresses or in the INIT chunk)
* that belong to this association, it should discard the INIT chunk and
* retransmit the SHUTDOWN ACK chunk.
*/
sctp_disposition_t sctp_sf_do_9_2_reshutack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = (struct sctp_chunk *) arg;
struct sctp_chunk *reply;
/* Make sure that the chunk has a valid length */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Since we are not going to really process this INIT, there
* is no point in verifying chunk boundries. Just generate
* the SHUTDOWN ACK.
*/
reply = sctp_make_shutdown_ack(asoc, chunk);
if (NULL == reply)
goto nomem;
/* Set the transport for the SHUTDOWN ACK chunk and the timeout for
* the T2-SHUTDOWN timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* and restart the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* sctp_sf_do_ecn_cwr
*
* Section: Appendix A: Explicit Congestion Notification
*
* CWR:
*
* RFC 2481 details a specific bit for a sender to send in the header of
* its next outbound TCP segment to indicate to its peer that it has
* reduced its congestion window. This is termed the CWR bit. For
* SCTP the same indication is made by including the CWR chunk.
* This chunk contains one data element, i.e. the TSN number that
* was sent in the ECNE chunk. This element represents the lowest
* TSN number in the datagram that was originally marked with the
* CE bit.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_ecn_cwr(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_cwrhdr_t *cwr;
struct sctp_chunk *chunk = arg;
u32 lowest_tsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_ecne_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
cwr = (sctp_cwrhdr_t *) chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_cwrhdr_t));
lowest_tsn = ntohl(cwr->lowest_tsn);
/* Does this CWR ack the last sent congestion notification? */
if (TSN_lte(asoc->last_ecne_tsn, lowest_tsn)) {
/* Stop sending ECNE. */
sctp_add_cmd_sf(commands,
SCTP_CMD_ECN_CWR,
SCTP_U32(lowest_tsn));
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_sf_do_ecne
*
* Section: Appendix A: Explicit Congestion Notification
*
* ECN-Echo
*
* RFC 2481 details a specific bit for a receiver to send back in its
* TCP acknowledgements to notify the sender of the Congestion
* Experienced (CE) bit having arrived from the network. For SCTP this
* same indication is made by including the ECNE chunk. This chunk
* contains one data element, i.e. the lowest TSN associated with the IP
* datagram marked with the CE bit.....
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_ecne(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_ecnehdr_t *ecne;
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_ecne_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
ecne = (sctp_ecnehdr_t *) chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_ecnehdr_t));
/* If this is a newer ECNE than the last CWR packet we sent out */
sctp_add_cmd_sf(commands, SCTP_CMD_ECN_ECNE,
SCTP_U32(ntohl(ecne->lowest_tsn)));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Section: 6.2 Acknowledgement on Reception of DATA Chunks
*
* The SCTP endpoint MUST always acknowledge the reception of each valid
* DATA chunk.
*
* The guidelines on delayed acknowledgement algorithm specified in
* Section 4.2 of [RFC2581] SHOULD be followed. Specifically, an
* acknowledgement SHOULD be generated for at least every second packet
* (not every second DATA chunk) received, and SHOULD be generated within
* 200 ms of the arrival of any unacknowledged DATA chunk. In some
* situations it may be beneficial for an SCTP transmitter to be more
* conservative than the algorithms detailed in this document allow.
* However, an SCTP transmitter MUST NOT be more aggressive than the
* following algorithms allow.
*
* A SCTP receiver MUST NOT generate more than one SACK for every
* incoming packet, other than to update the offered window as the
* receiving application consumes new data.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_eat_data_6_2(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_arg_t force = SCTP_NOFORCE();
int error;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_data_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
error = sctp_eat_data(asoc, chunk, commands);
switch (error) {
case SCTP_IERROR_NO_ERROR:
break;
case SCTP_IERROR_HIGH_TSN:
case SCTP_IERROR_BAD_STREAM:
SCTP_INC_STATS(net, SCTP_MIB_IN_DATA_CHUNK_DISCARDS);
goto discard_noforce;
case SCTP_IERROR_DUP_TSN:
case SCTP_IERROR_IGNORE_TSN:
SCTP_INC_STATS(net, SCTP_MIB_IN_DATA_CHUNK_DISCARDS);
goto discard_force;
case SCTP_IERROR_NO_DATA:
return SCTP_DISPOSITION_ABORT;
case SCTP_IERROR_PROTO_VIOLATION:
return sctp_sf_abort_violation(net, ep, asoc, chunk, commands,
(u8 *)chunk->subh.data_hdr, sizeof(sctp_datahdr_t));
default:
BUG();
}
if (chunk->chunk_hdr->flags & SCTP_DATA_SACK_IMM)
force = SCTP_FORCE();
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
}
/* If this is the last chunk in a packet, we need to count it
* toward sack generation. Note that we need to SACK every
* OTHER packet containing data chunks, EVEN IF WE DISCARD
* THEM. We elect to NOT generate SACK's if the chunk fails
* the verification tag test.
*
* RFC 2960 6.2 Acknowledgement on Reception of DATA Chunks
*
* The SCTP endpoint MUST always acknowledge the reception of
* each valid DATA chunk.
*
* The guidelines on delayed acknowledgement algorithm
* specified in Section 4.2 of [RFC2581] SHOULD be followed.
* Specifically, an acknowledgement SHOULD be generated for at
* least every second packet (not every second DATA chunk)
* received, and SHOULD be generated within 200 ms of the
* arrival of any unacknowledged DATA chunk. In some
* situations it may be beneficial for an SCTP transmitter to
* be more conservative than the algorithms detailed in this
* document allow. However, an SCTP transmitter MUST NOT be
* more aggressive than the following algorithms allow.
*/
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, force);
return SCTP_DISPOSITION_CONSUME;
discard_force:
/* RFC 2960 6.2 Acknowledgement on Reception of DATA Chunks
*
* When a packet arrives with duplicate DATA chunk(s) and with
* no new DATA chunk(s), the endpoint MUST immediately send a
* SACK with no delay. If a packet arrives with duplicate
* DATA chunk(s) bundled with new DATA chunks, the endpoint
* MAY immediately send a SACK. Normally receipt of duplicate
* DATA chunks will occur when the original SACK chunk was lost
* and the peer's RTO has expired. The duplicate TSN number(s)
* SHOULD be reported in the SACK as duplicate.
*/
/* In our case, we split the MAY SACK advice up whether or not
* the last chunk is a duplicate.'
*/
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
return SCTP_DISPOSITION_DISCARD;
discard_noforce:
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, force);
return SCTP_DISPOSITION_DISCARD;
}
/*
* sctp_sf_eat_data_fast_4_4
*
* Section: 4 (4)
* (4) In SHUTDOWN-SENT state the endpoint MUST acknowledge any received
* DATA chunks without delay.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_eat_data_fast_4_4(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
int error;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_data_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
error = sctp_eat_data(asoc, chunk, commands);
switch (error) {
case SCTP_IERROR_NO_ERROR:
case SCTP_IERROR_HIGH_TSN:
case SCTP_IERROR_DUP_TSN:
case SCTP_IERROR_IGNORE_TSN:
case SCTP_IERROR_BAD_STREAM:
break;
case SCTP_IERROR_NO_DATA:
return SCTP_DISPOSITION_ABORT;
case SCTP_IERROR_PROTO_VIOLATION:
return sctp_sf_abort_violation(net, ep, asoc, chunk, commands,
(u8 *)chunk->subh.data_hdr, sizeof(sctp_datahdr_t));
default:
BUG();
}
/* Go a head and force a SACK, since we are shutting down. */
/* Implementor's Guide.
*
* While in SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately
* respond to each received packet containing one or more DATA chunk(s)
* with a SACK, a SHUTDOWN chunk, and restart the T2-shutdown timer
*/
if (chunk->end_of_packet) {
/* We must delay the chunk creation since the cumulative
* TSN has not been updated yet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SHUTDOWN, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* Section: 6.2 Processing a Received SACK
* D) Any time a SACK arrives, the endpoint performs the following:
*
* i) If Cumulative TSN Ack is less than the Cumulative TSN Ack Point,
* then drop the SACK. Since Cumulative TSN Ack is monotonically
* increasing, a SACK whose Cumulative TSN Ack is less than the
* Cumulative TSN Ack Point indicates an out-of-order SACK.
*
* ii) Set rwnd equal to the newly received a_rwnd minus the number
* of bytes still outstanding after processing the Cumulative TSN Ack
* and the Gap Ack Blocks.
*
* iii) If the SACK is missing a TSN that was previously
* acknowledged via a Gap Ack Block (e.g., the data receiver
* reneged on the data), then mark the corresponding DATA chunk
* as available for retransmit: Mark it as missing for fast
* retransmit as described in Section 7.2.4 and if no retransmit
* timer is running for the destination address to which the DATA
* chunk was originally transmitted, then T3-rtx is started for
* that destination address.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_eat_sack_6_2(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_sackhdr_t *sackh;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_sack_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Pull the SACK chunk from the data buffer */
sackh = sctp_sm_pull_sack(chunk);
/* Was this a bogus SACK? */
if (!sackh)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
chunk->subh.sack_hdr = sackh;
ctsn = ntohl(sackh->cum_tsn_ack);
/* i) If Cumulative TSN Ack is less than the Cumulative TSN
* Ack Point, then drop the SACK. Since Cumulative TSN
* Ack is monotonically increasing, a SACK whose
* Cumulative TSN Ack is less than the Cumulative TSN Ack
* Point indicates an out-of-order SACK.
*/
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn,
asoc->ctsn_ack_point);
return SCTP_DISPOSITION_DISCARD;
}
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (!TSN_lt(ctsn, asoc->next_tsn))
return sctp_sf_violation_ctsn(net, ep, asoc, type, arg, commands);
/* Return this SACK for further processing. */
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_SACK, SCTP_CHUNK(chunk));
/* Note: We do the rest of the work on the PROCESS_SACK
* sideeffect.
*/
return SCTP_DISPOSITION_CONSUME;
}
/*
* Generate an ABORT in response to a packet.
*
* Section: 8.4 Handle "Out of the blue" Packets, sctpimpguide 2.41
*
* 8) The receiver should respond to the sender of the OOTB packet with
* an ABORT. When sending the ABORT, the receiver of the OOTB packet
* MUST fill in the Verification Tag field of the outbound packet
* with the value found in the Verification Tag field of the OOTB
* packet and set the T-bit in the Chunk Flags to indicate that the
* Verification Tag is reflected. After sending this ABORT, the
* receiver of the OOTB packet shall discard the OOTB packet and take
* no further action.
*
* Verification Tag:
*
* The return value is the disposition of the chunk.
*/
static sctp_disposition_t sctp_sf_tabort_8_4_8(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *abort;
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (packet) {
/* Make an ABORT. The T bit will be set if the asoc
* is NULL.
*/
abort = sctp_make_abort(asoc, chunk, 0);
if (!abort) {
sctp_ootb_pkt_free(packet);
return SCTP_DISPOSITION_NOMEM;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Set the skb to the belonging sock for accounting. */
abort->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, abort);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
return SCTP_DISPOSITION_CONSUME;
}
return SCTP_DISPOSITION_NOMEM;
}
/*
* Received an ERROR chunk from peer. Generate SCTP_REMOTE_ERROR
* event as ULP notification for each cause included in the chunk.
*
* API 5.3.1.3 - SCTP_REMOTE_ERROR
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_operr_notify(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_errhdr_t *err;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ERROR chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_operr_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
sctp_walk_errors(err, chunk->chunk_hdr);
if ((void *)err != (void *)chunk->chunk_end)
return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
(void *)err, commands);
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_OPERR,
SCTP_CHUNK(chunk));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process an inbound SHUTDOWN ACK.
*
* From Section 9.2:
* Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall
* stop the T2-shutdown timer, send a SHUTDOWN COMPLETE chunk to its
* peer, and remove all record of the association.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_2_final(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *reply;
struct sctp_ulpevent *ev;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN_ACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* 10.2 H) SHUTDOWN COMPLETE notification
*
* When SCTP completes the shutdown procedures (section 9.2) this
* notification is passed to the upper layer.
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_SHUTDOWN_COMP,
0, 0, 0, NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
/* ...send a SHUTDOWN COMPLETE chunk to its peer, */
reply = sctp_make_shutdown_complete(asoc, chunk);
if (!reply)
goto nomem_chunk;
/* Do all the commands now (after allocation), so that we
* have consistent state if memory allocation failes
*/
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall
* stop the T2-shutdown timer,
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
/* ...and remove all record of the association. */
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
nomem_chunk:
sctp_ulpevent_free(ev);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* RFC 2960, 8.4 - Handle "Out of the blue" Packets, sctpimpguide 2.41.
*
* 5) If the packet contains a SHUTDOWN ACK chunk, the receiver should
* respond to the sender of the OOTB packet with a SHUTDOWN COMPLETE.
* When sending the SHUTDOWN COMPLETE, the receiver of the OOTB
* packet must fill in the Verification Tag field of the outbound
* packet with the Verification Tag received in the SHUTDOWN ACK and
* set the T-bit in the Chunk Flags to indicate that the Verification
* Tag is reflected.
*
* 8) The receiver should respond to the sender of the OOTB packet with
* an ABORT. When sending the ABORT, the receiver of the OOTB packet
* MUST fill in the Verification Tag field of the outbound packet
* with the value found in the Verification Tag field of the OOTB
* packet and set the T-bit in the Chunk Flags to indicate that the
* Verification Tag is reflected. After sending this ABORT, the
* receiver of the OOTB packet shall discard the OOTB packet and take
* no further action.
*/
sctp_disposition_t sctp_sf_ootb(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sk_buff *skb = chunk->skb;
sctp_chunkhdr_t *ch;
sctp_errhdr_t *err;
__u8 *ch_end;
int ootb_shut_ack = 0;
int ootb_cookie_ack = 0;
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
ch = (sctp_chunkhdr_t *) chunk->chunk_hdr;
do {
/* Report violation if the chunk is less then minimal */
if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Now that we know we at least have a chunk header,
* do things that are type appropriate.
*/
if (SCTP_CID_SHUTDOWN_ACK == ch->type)
ootb_shut_ack = 1;
/* RFC 2960, Section 3.3.7
* Moreover, under any circumstances, an endpoint that
* receives an ABORT MUST NOT respond to that ABORT by
* sending an ABORT of its own.
*/
if (SCTP_CID_ABORT == ch->type)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* RFC 8.4, 7) If the packet contains a "Stale cookie" ERROR
* or a COOKIE ACK the SCTP Packet should be silently
* discarded.
*/
if (SCTP_CID_COOKIE_ACK == ch->type)
ootb_cookie_ack = 1;
if (SCTP_CID_ERROR == ch->type) {
sctp_walk_errors(err, ch) {
if (SCTP_ERROR_STALE_COOKIE == err->cause) {
ootb_cookie_ack = 1;
break;
}
}
}
/* Report violation if chunk len overflows */
ch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));
if (ch_end > skb_tail_pointer(skb))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
ch = (sctp_chunkhdr_t *) ch_end;
} while (ch_end < skb_tail_pointer(skb));
if (ootb_shut_ack)
return sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands);
else if (ootb_cookie_ack)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
else
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
}
/*
* Handle an "Out of the blue" SHUTDOWN ACK.
*
* Section: 8.4 5, sctpimpguide 2.41.
*
* 5) If the packet contains a SHUTDOWN ACK chunk, the receiver should
* respond to the sender of the OOTB packet with a SHUTDOWN COMPLETE.
* When sending the SHUTDOWN COMPLETE, the receiver of the OOTB
* packet must fill in the Verification Tag field of the outbound
* packet with the Verification Tag received in the SHUTDOWN ACK and
* set the T-bit in the Chunk Flags to indicate that the Verification
* Tag is reflected.
*
* Inputs
* (endpoint, asoc, type, arg, commands)
*
* Outputs
* (sctp_disposition_t)
*
* The return value is the disposition of the chunk.
*/
static sctp_disposition_t sctp_sf_shut_8_4_5(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *shut;
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (packet) {
/* Make an SHUTDOWN_COMPLETE.
* The T bit will be set if the asoc is NULL.
*/
shut = sctp_make_shutdown_complete(asoc, chunk);
if (!shut) {
sctp_ootb_pkt_free(packet);
return SCTP_DISPOSITION_NOMEM;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(shut))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Set the skb to the belonging sock for accounting. */
shut->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, shut);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
/* If the chunk length is invalid, we don't want to process
* the reset of the packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* We need to discard the rest of the packet to prevent
* potential bomming attacks from additional bundled chunks.
* This is documented in SCTP Threats ID.
*/
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
return SCTP_DISPOSITION_NOMEM;
}
/*
* Handle SHUTDOWN ACK in COOKIE_ECHOED or COOKIE_WAIT state.
*
* Verification Tag: 8.5.1 E) Rules for packet carrying a SHUTDOWN ACK
* If the receiver is in COOKIE-ECHOED or COOKIE-WAIT state the
* procedures in section 8.4 SHOULD be followed, in other words it
* should be treated as an Out Of The Blue packet.
* [This means that we do NOT check the Verification Tag on these
* chunks. --piggy ]
*
*/
sctp_disposition_t sctp_sf_do_8_5_1_E_sa(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
/* Make sure that the SHUTDOWN_ACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Although we do have an association in this case, it corresponds
* to a restarted association. So the packet is treated as an OOTB
* packet and the state function that handles OOTB SHUTDOWN_ACK is
* called with a NULL association.
*/
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
return sctp_sf_shut_8_4_5(net, ep, NULL, type, arg, commands);
}
/* ADDIP Section 4.2 Upon reception of an ASCONF Chunk. */
sctp_disposition_t sctp_sf_do_asconf(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *asconf_ack = NULL;
struct sctp_paramhdr *err_param = NULL;
sctp_addiphdr_t *hdr;
__u32 serial;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* ADD-IP: Section 4.1.1
* This chunk MUST be sent in an authenticated way by using
* the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk
* is received unauthenticated it MUST be silently discarded as
* described in [I-D.ietf-tsvwg-sctp-auth].
*/
if (!net->sctp.addip_noauth && !chunk->auth)
return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);
/* Make sure that the ASCONF ADDIP chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_addip_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
hdr = (sctp_addiphdr_t *)chunk->skb->data;
serial = ntohl(hdr->serial);
/* Verify the ASCONF chunk before processing it. */
if (!sctp_verify_asconf(asoc, chunk, true, &err_param))
return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
(void *)err_param, commands);
/* ADDIP 5.2 E1) Compare the value of the serial number to the value
* the endpoint stored in a new association variable
* 'Peer-Serial-Number'.
*/
if (serial == asoc->peer.addip_serial + 1) {
/* If this is the first instance of ASCONF in the packet,
* we can clean our old ASCONF-ACKs.
*/
if (!chunk->has_asconf)
sctp_assoc_clean_asconf_ack_cache(asoc);
/* ADDIP 5.2 E4) When the Sequence Number matches the next one
* expected, process the ASCONF as described below and after
* processing the ASCONF Chunk, append an ASCONF-ACK Chunk to
* the response packet and cache a copy of it (in the event it
* later needs to be retransmitted).
*
* Essentially, do V1-V5.
*/
asconf_ack = sctp_process_asconf((struct sctp_association *)
asoc, chunk);
if (!asconf_ack)
return SCTP_DISPOSITION_NOMEM;
} else if (serial < asoc->peer.addip_serial + 1) {
/* ADDIP 5.2 E2)
* If the value found in the Sequence Number is less than the
* ('Peer- Sequence-Number' + 1), simply skip to the next
* ASCONF, and include in the outbound response packet
* any previously cached ASCONF-ACK response that was
* sent and saved that matches the Sequence Number of the
* ASCONF. Note: It is possible that no cached ASCONF-ACK
* Chunk exists. This will occur when an older ASCONF
* arrives out of order. In such a case, the receiver
* should skip the ASCONF Chunk and not include ASCONF-ACK
* Chunk for that chunk.
*/
asconf_ack = sctp_assoc_lookup_asconf_ack(asoc, hdr->serial);
if (!asconf_ack)
return SCTP_DISPOSITION_DISCARD;
/* Reset the transport so that we select the correct one
* this time around. This is to make sure that we don't
* accidentally use a stale transport that's been removed.
*/
asconf_ack->transport = NULL;
} else {
/* ADDIP 5.2 E5) Otherwise, the ASCONF Chunk is discarded since
* it must be either a stale packet or from an attacker.
*/
return SCTP_DISPOSITION_DISCARD;
}
/* ADDIP 5.2 E6) The destination address of the SCTP packet
* containing the ASCONF-ACK Chunks MUST be the source address of
* the SCTP packet that held the ASCONF Chunks.
*
* To do this properly, we'll set the destination address of the chunk
* and at the transmit time, will try look up the transport to use.
* Since ASCONFs may be bundled, the correct transport may not be
* created until we process the entire packet, thus this workaround.
*/
asconf_ack->dest = chunk->source;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(asconf_ack));
if (asoc->new_transport) {
sctp_sf_heartbeat(ep, asoc, type, asoc->new_transport, commands);
((struct sctp_association *)asoc)->new_transport = NULL;
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* ADDIP Section 4.3 General rules for address manipulation
* When building TLV parameters for the ASCONF Chunk that will add or
* delete IP addresses the D0 to D13 rules should be applied:
*/
sctp_disposition_t sctp_sf_do_asconf_ack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *asconf_ack = arg;
struct sctp_chunk *last_asconf = asoc->addip_last_asconf;
struct sctp_chunk *abort;
struct sctp_paramhdr *err_param = NULL;
sctp_addiphdr_t *addip_hdr;
__u32 sent_serial, rcvd_serial;
if (!sctp_vtag_verify(asconf_ack, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* ADD-IP, Section 4.1.2:
* This chunk MUST be sent in an authenticated way by using
* the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk
* is received unauthenticated it MUST be silently discarded as
* described in [I-D.ietf-tsvwg-sctp-auth].
*/
if (!net->sctp.addip_noauth && !asconf_ack->auth)
return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);
/* Make sure that the ADDIP chunk has a valid length. */
if (!sctp_chunk_length_valid(asconf_ack, sizeof(sctp_addip_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
addip_hdr = (sctp_addiphdr_t *)asconf_ack->skb->data;
rcvd_serial = ntohl(addip_hdr->serial);
/* Verify the ASCONF-ACK chunk before processing it. */
if (!sctp_verify_asconf(asoc, asconf_ack, false, &err_param))
return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
(void *)err_param, commands);
if (last_asconf) {
addip_hdr = (sctp_addiphdr_t *)last_asconf->subh.addip_hdr;
sent_serial = ntohl(addip_hdr->serial);
} else {
sent_serial = asoc->addip_serial - 1;
}
/* D0) If an endpoint receives an ASCONF-ACK that is greater than or
* equal to the next serial number to be used but no ASCONF chunk is
* outstanding the endpoint MUST ABORT the association. Note that a
* sequence number is greater than if it is no more than 2^^31-1
* larger than the current sequence number (using serial arithmetic).
*/
if (ADDIP_SERIAL_gte(rcvd_serial, sent_serial + 1) &&
!(asoc->addip_last_asconf)) {
abort = sctp_make_abort(asoc, asconf_ack,
sizeof(sctp_errhdr_t));
if (abort) {
sctp_init_cause(abort, SCTP_ERROR_ASCONF_ACK, 0);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(abort));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_ASCONF_ACK));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
if ((rcvd_serial == sent_serial) && asoc->addip_last_asconf) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
if (!sctp_process_asconf_ack((struct sctp_association *)asoc,
asconf_ack)) {
/* Successfully processed ASCONF_ACK. We can
* release the next asconf if we have one.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_NEXT_ASCONF,
SCTP_NULL());
return SCTP_DISPOSITION_CONSUME;
}
abort = sctp_make_abort(asoc, asconf_ack,
sizeof(sctp_errhdr_t));
if (abort) {
sctp_init_cause(abort, SCTP_ERROR_RSRC_LOW, 0);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(abort));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_ASCONF_ACK));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
return SCTP_DISPOSITION_DISCARD;
}
/*
* PR-SCTP Section 3.6 Receiver Side Implementation of PR-SCTP
*
* When a FORWARD TSN chunk arrives, the data receiver MUST first update
* its cumulative TSN point to the value carried in the FORWARD TSN
* chunk, and then MUST further advance its cumulative TSN point locally
* if possible.
* After the above processing, the data receiver MUST stop reporting any
* missing TSNs earlier than or equal to the new cumulative TSN point.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_eat_fwd_tsn(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_fwdtsn_hdr *fwdtsn_hdr;
struct sctp_fwdtsn_skip *skip;
__u16 len;
__u32 tsn;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Make sure that the FORWARD_TSN chunk has valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_fwdtsn_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data;
chunk->subh.fwdtsn_hdr = fwdtsn_hdr;
len = ntohs(chunk->chunk_hdr->length);
len -= sizeof(struct sctp_chunkhdr);
skb_pull(chunk->skb, len);
tsn = ntohl(fwdtsn_hdr->new_cum_tsn);
pr_debug("%s: TSN 0x%x\n", __func__, tsn);
/* The TSN is too high--silently discard the chunk and count on it
* getting retransmitted later.
*/
if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0)
goto discard_noforce;
/* Silently discard the chunk if stream-id is not valid */
sctp_walk_fwdtsn(skip, chunk) {
if (ntohs(skip->stream) >= asoc->c.sinit_max_instreams)
goto discard_noforce;
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_FWDTSN, SCTP_U32(tsn));
if (len > sizeof(struct sctp_fwdtsn_hdr))
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_FWDTSN,
SCTP_CHUNK(chunk));
/* Count this as receiving DATA. */
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
}
/* FIXME: For now send a SACK, but DATA processing may
* send another.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_NOFORCE());
return SCTP_DISPOSITION_CONSUME;
discard_noforce:
return SCTP_DISPOSITION_DISCARD;
}
sctp_disposition_t sctp_sf_eat_fwd_tsn_fast(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_fwdtsn_hdr *fwdtsn_hdr;
struct sctp_fwdtsn_skip *skip;
__u16 len;
__u32 tsn;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Make sure that the FORWARD_TSN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_fwdtsn_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data;
chunk->subh.fwdtsn_hdr = fwdtsn_hdr;
len = ntohs(chunk->chunk_hdr->length);
len -= sizeof(struct sctp_chunkhdr);
skb_pull(chunk->skb, len);
tsn = ntohl(fwdtsn_hdr->new_cum_tsn);
pr_debug("%s: TSN 0x%x\n", __func__, tsn);
/* The TSN is too high--silently discard the chunk and count on it
* getting retransmitted later.
*/
if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0)
goto gen_shutdown;
/* Silently discard the chunk if stream-id is not valid */
sctp_walk_fwdtsn(skip, chunk) {
if (ntohs(skip->stream) >= asoc->c.sinit_max_instreams)
goto gen_shutdown;
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_FWDTSN, SCTP_U32(tsn));
if (len > sizeof(struct sctp_fwdtsn_hdr))
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_FWDTSN,
SCTP_CHUNK(chunk));
/* Go a head and force a SACK, since we are shutting down. */
gen_shutdown:
/* Implementor's Guide.
*
* While in SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately
* respond to each received packet containing one or more DATA chunk(s)
* with a SACK, a SHUTDOWN chunk, and restart the T2-shutdown timer
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SHUTDOWN, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
return SCTP_DISPOSITION_CONSUME;
}
/*
* SCTP-AUTH Section 6.3 Receiving authenticated chukns
*
* The receiver MUST use the HMAC algorithm indicated in the HMAC
* Identifier field. If this algorithm was not specified by the
* receiver in the HMAC-ALGO parameter in the INIT or INIT-ACK chunk
* during association setup, the AUTH chunk and all chunks after it MUST
* be discarded and an ERROR chunk SHOULD be sent with the error cause
* defined in Section 4.1.
*
* If an endpoint with no shared key receives a Shared Key Identifier
* other than 0, it MUST silently discard all authenticated chunks. If
* the endpoint has at least one endpoint pair shared key for the peer,
* it MUST use the key specified by the Shared Key Identifier if a
* key has been configured for that Shared Key Identifier. If no
* endpoint pair shared key has been configured for that Shared Key
* Identifier, all authenticated chunks MUST be silently discarded.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* The return value is the disposition of the chunk.
*/
static sctp_ierror_t sctp_sf_authenticate(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
struct sctp_chunk *chunk)
{
struct sctp_authhdr *auth_hdr;
struct sctp_hmac *hmac;
unsigned int sig_len;
__u16 key_id;
__u8 *save_digest;
__u8 *digest;
/* Pull in the auth header, so we can do some more verification */
auth_hdr = (struct sctp_authhdr *)chunk->skb->data;
chunk->subh.auth_hdr = auth_hdr;
skb_pull(chunk->skb, sizeof(struct sctp_authhdr));
/* Make sure that we support the HMAC algorithm from the auth
* chunk.
*/
if (!sctp_auth_asoc_verify_hmac_id(asoc, auth_hdr->hmac_id))
return SCTP_IERROR_AUTH_BAD_HMAC;
/* Make sure that the provided shared key identifier has been
* configured
*/
key_id = ntohs(auth_hdr->shkey_id);
if (key_id != asoc->active_key_id && !sctp_auth_get_shkey(asoc, key_id))
return SCTP_IERROR_AUTH_BAD_KEYID;
/* Make sure that the length of the signature matches what
* we expect.
*/
sig_len = ntohs(chunk->chunk_hdr->length) - sizeof(sctp_auth_chunk_t);
hmac = sctp_auth_get_hmac(ntohs(auth_hdr->hmac_id));
if (sig_len != hmac->hmac_len)
return SCTP_IERROR_PROTO_VIOLATION;
/* Now that we've done validation checks, we can compute and
* verify the hmac. The steps involved are:
* 1. Save the digest from the chunk.
* 2. Zero out the digest in the chunk.
* 3. Compute the new digest
* 4. Compare saved and new digests.
*/
digest = auth_hdr->hmac;
skb_pull(chunk->skb, sig_len);
save_digest = kmemdup(digest, sig_len, GFP_ATOMIC);
if (!save_digest)
goto nomem;
memset(digest, 0, sig_len);
sctp_auth_calculate_hmac(asoc, chunk->skb,
(struct sctp_auth_chunk *)chunk->chunk_hdr,
GFP_ATOMIC);
/* Discard the packet if the digests do not match */
if (memcmp(save_digest, digest, sig_len)) {
kfree(save_digest);
return SCTP_IERROR_BAD_SIG;
}
kfree(save_digest);
chunk->auth = 1;
return SCTP_IERROR_NO_ERROR;
nomem:
return SCTP_IERROR_NOMEM;
}
sctp_disposition_t sctp_sf_eat_auth(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_authhdr *auth_hdr;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *err_chunk;
sctp_ierror_t error;
/* Make sure that the peer has AUTH capable */
if (!asoc->peer.auth_capable)
return sctp_sf_unk_chunk(net, ep, asoc, type, arg, commands);
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Make sure that the AUTH chunk has valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_auth_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
auth_hdr = (struct sctp_authhdr *)chunk->skb->data;
error = sctp_sf_authenticate(net, ep, asoc, type, chunk);
switch (error) {
case SCTP_IERROR_AUTH_BAD_HMAC:
/* Generate the ERROR chunk and discard the rest
* of the packet
*/
err_chunk = sctp_make_op_error(asoc, chunk,
SCTP_ERROR_UNSUP_HMAC,
&auth_hdr->hmac_id,
sizeof(__u16), 0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
/* Fall Through */
case SCTP_IERROR_AUTH_BAD_KEYID:
case SCTP_IERROR_BAD_SIG:
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case SCTP_IERROR_PROTO_VIOLATION:
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
case SCTP_IERROR_NOMEM:
return SCTP_DISPOSITION_NOMEM;
default: /* Prevent gcc warnings */
break;
}
if (asoc->active_key_id != ntohs(auth_hdr->shkey_id)) {
struct sctp_ulpevent *ev;
ev = sctp_ulpevent_make_authkey(asoc, ntohs(auth_hdr->shkey_id),
SCTP_AUTH_NEWKEY, GFP_ATOMIC);
if (!ev)
return -ENOMEM;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process an unknown chunk.
*
* Section: 3.2. Also, 2.1 in the implementor's guide.
*
* Chunk Types are encoded such that the highest-order two bits specify
* the action that must be taken if the processing endpoint does not
* recognize the Chunk Type.
*
* 00 - Stop processing this SCTP packet and discard it, do not process
* any further chunks within it.
*
* 01 - Stop processing this SCTP packet and discard it, do not process
* any further chunks within it, and report the unrecognized
* chunk in an 'Unrecognized Chunk Type'.
*
* 10 - Skip this chunk and continue processing.
*
* 11 - Skip this chunk and continue processing, but report in an ERROR
* Chunk using the 'Unrecognized Chunk Type' cause of error.
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_unk_chunk(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *unk_chunk = arg;
struct sctp_chunk *err_chunk;
sctp_chunkhdr_t *hdr;
pr_debug("%s: processing unknown chunk id:%d\n", __func__, type.chunk);
if (!sctp_vtag_verify(unk_chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the chunk has a valid length.
* Since we don't know the chunk type, we use a general
* chunkhdr structure to make a comparison.
*/
if (!sctp_chunk_length_valid(unk_chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
switch (type.chunk & SCTP_CID_ACTION_MASK) {
case SCTP_CID_ACTION_DISCARD:
/* Discard the packet. */
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case SCTP_CID_ACTION_DISCARD_ERR:
/* Generate an ERROR chunk as response. */
hdr = unk_chunk->chunk_hdr;
err_chunk = sctp_make_op_error(asoc, unk_chunk,
SCTP_ERROR_UNKNOWN_CHUNK, hdr,
SCTP_PAD4(ntohs(hdr->length)),
0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
/* Discard the packet. */
sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
return SCTP_DISPOSITION_CONSUME;
case SCTP_CID_ACTION_SKIP:
/* Skip the chunk. */
return SCTP_DISPOSITION_DISCARD;
case SCTP_CID_ACTION_SKIP_ERR:
/* Generate an ERROR chunk as response. */
hdr = unk_chunk->chunk_hdr;
err_chunk = sctp_make_op_error(asoc, unk_chunk,
SCTP_ERROR_UNKNOWN_CHUNK, hdr,
SCTP_PAD4(ntohs(hdr->length)),
0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
/* Skip the chunk. */
return SCTP_DISPOSITION_CONSUME;
default:
break;
}
return SCTP_DISPOSITION_DISCARD;
}
/*
* Discard the chunk.
*
* Section: 0.2, 5.2.3, 5.2.5, 5.2.6, 6.0, 8.4.6, 8.5.1c, 9.2
* [Too numerous to mention...]
* Verification Tag: No verification needed.
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_discard_chunk(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
/* Make sure that the chunk has a valid length.
* Since we don't know the chunk type, we use a general
* chunkhdr structure to make a comparison.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
pr_debug("%s: chunk:%d is discarded\n", __func__, type.chunk);
return SCTP_DISPOSITION_DISCARD;
}
/*
* Discard the whole packet.
*
* Section: 8.4 2)
*
* 2) If the OOTB packet contains an ABORT chunk, the receiver MUST
* silently discard the OOTB packet and take no further action.
*
* Verification Tag: No verification necessary
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_pdiscard(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
SCTP_INC_STATS(net, SCTP_MIB_IN_PKT_DISCARDS);
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
return SCTP_DISPOSITION_CONSUME;
}
/*
* The other end is violating protocol.
*
* Section: Not specified
* Verification Tag: Not specified
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* We simply tag the chunk as a violation. The state machine will log
* the violation and continue.
*/
sctp_disposition_t sctp_sf_violation(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
/* Make sure that the chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
return SCTP_DISPOSITION_VIOLATION;
}
/*
* Common function to handle a protocol violation.
*/
static sctp_disposition_t sctp_sf_abort_violation(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
void *arg,
sctp_cmd_seq_t *commands,
const __u8 *payload,
const size_t paylen)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *abort = NULL;
/* SCTP-AUTH, Section 6.3:
* It should be noted that if the receiver wants to tear
* down an association in an authenticated way only, the
* handling of malformed packets should not result in
* tearing down the association.
*
* This means that if we only want to abort associations
* in an authenticated way (i.e AUTH+ABORT), then we
* can't destroy this association just because the packet
* was malformed.
*/
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
goto discard;
/* Make the abort chunk. */
abort = sctp_make_abort_violation(asoc, chunk, payload, paylen);
if (!abort)
goto nomem;
if (asoc) {
/* Treat INIT-ACK as a special case during COOKIE-WAIT. */
if (chunk->chunk_hdr->type == SCTP_CID_INIT_ACK &&
!asoc->peer.i.init_tag) {
sctp_initack_chunk_t *initack;
initack = (sctp_initack_chunk_t *)chunk->chunk_hdr;
if (!sctp_chunk_length_valid(chunk,
sizeof(sctp_initack_chunk_t)))
abort->chunk_hdr->flags |= SCTP_CHUNK_FLAG_T;
else {
unsigned int inittag;
inittag = ntohl(initack->init_hdr.init_tag);
sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_INITTAG,
SCTP_U32(inittag));
}
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
if (asoc->state <= SCTP_STATE_COOKIE_ECHOED) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNREFUSED));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION));
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
}
} else {
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (!packet)
goto nomem_pkt;
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
abort->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, abort);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
}
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
discard:
sctp_sf_pdiscard(net, ep, asoc, SCTP_ST_CHUNK(0), arg, commands);
return SCTP_DISPOSITION_ABORT;
nomem_pkt:
sctp_chunk_free(abort);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Handle a protocol violation when the chunk length is invalid.
* "Invalid" length is identified as smaller than the minimal length a
* given chunk can be. For example, a SACK chunk has invalid length
* if its length is set to be smaller than the size of sctp_sack_chunk_t.
*
* We inform the other end by sending an ABORT with a Protocol Violation
* error code.
*
* Section: Not specified
* Verification Tag: Nothing to do
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (reply_msg, msg_up, counters)
*
* Generate an ABORT chunk and terminate the association.
*/
static sctp_disposition_t sctp_sf_violation_chunklen(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
static const char err_str[] = "The following chunk had invalid length:";
return sctp_sf_abort_violation(net, ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/*
* Handle a protocol violation when the parameter length is invalid.
* If the length is smaller than the minimum length of a given parameter,
* or accumulated length in multi parameters exceeds the end of the chunk,
* the length is considered as invalid.
*/
static sctp_disposition_t sctp_sf_violation_paramlen(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, void *ext,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_paramhdr *param = ext;
struct sctp_chunk *abort = NULL;
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
goto discard;
/* Make the abort chunk. */
abort = sctp_make_violation_paramlen(asoc, chunk, param);
if (!abort)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION));
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
discard:
sctp_sf_pdiscard(net, ep, asoc, SCTP_ST_CHUNK(0), arg, commands);
return SCTP_DISPOSITION_ABORT;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Handle a protocol violation when the peer trying to advance the
* cumulative tsn ack to a point beyond the max tsn currently sent.
*
* We inform the other end by sending an ABORT with a Protocol Violation
* error code.
*/
static sctp_disposition_t sctp_sf_violation_ctsn(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
static const char err_str[] = "The cumulative tsn ack beyond the max tsn currently sent:";
return sctp_sf_abort_violation(net, ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/* Handle protocol violation of an invalid chunk bundling. For example,
* when we have an association and we receive bundled INIT-ACK, or
* SHUDOWN-COMPLETE, our peer is clearly violationg the "MUST NOT bundle"
* statement from the specs. Additionally, there might be an attacker
* on the path and we may not want to continue this communication.
*/
static sctp_disposition_t sctp_sf_violation_chunk(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
static const char err_str[] = "The following chunk violates protocol:";
if (!asoc)
return sctp_sf_violation(net, ep, asoc, type, arg, commands);
return sctp_sf_abort_violation(net, ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/***************************************************************************
* These are the state functions for handling primitive (Section 10) events.
***************************************************************************/
/*
* sctp_sf_do_prm_asoc
*
* Section: 10.1 ULP-to-SCTP
* B) Associate
*
* Format: ASSOCIATE(local SCTP instance name, destination transport addr,
* outbound stream count)
* -> association id [,destination transport addr list] [,outbound stream
* count]
*
* This primitive allows the upper layer to initiate an association to a
* specific peer endpoint.
*
* The peer endpoint shall be specified by one of the transport addresses
* which defines the endpoint (see Section 1.4). If the local SCTP
* instance has not been initialized, the ASSOCIATE is considered an
* error.
* [This is not relevant for the kernel implementation since we do all
* initialization at boot time. It we hadn't initialized we wouldn't
* get anywhere near this code.]
*
* An association id, which is a local handle to the SCTP association,
* will be returned on successful establishment of the association. If
* SCTP is not able to open an SCTP association with the peer endpoint,
* an error is returned.
* [In the kernel implementation, the struct sctp_association needs to
* be created BEFORE causing this primitive to run.]
*
* Other association parameters may be returned, including the
* complete destination transport addresses of the peer as well as the
* outbound stream count of the local endpoint. One of the transport
* address from the returned destination addresses will be selected by
* the local endpoint as default primary path for sending SCTP packets
* to this peer. The returned "destination transport addr list" can
* be used by the ULP to change the default primary path or to force
* sending a packet to a specific transport address. [All of this
* stuff happens when the INIT ACK arrives. This is a NON-BLOCKING
* function.]
*
* Mandatory attributes:
*
* o local SCTP instance name - obtained from the INITIALIZE operation.
* [This is the argument asoc.]
* o destination transport addr - specified as one of the transport
* addresses of the peer endpoint with which the association is to be
* established.
* [This is asoc->peer.active_path.]
* o outbound stream count - the number of outbound streams the ULP
* would like to open towards this peer endpoint.
* [BUG: This is not currently implemented.]
* Optional attributes:
*
* None.
*
* The return value is a disposition.
*/
sctp_disposition_t sctp_sf_do_prm_asoc(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *repl;
struct sctp_association *my_asoc;
/* The comment below says that we enter COOKIE-WAIT AFTER
* sending the INIT, but that doesn't actually work in our
* implementation...
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_COOKIE_WAIT));
/* RFC 2960 5.1 Normal Establishment of an Association
*
* A) "A" first sends an INIT chunk to "Z". In the INIT, "A"
* must provide its Verification Tag (Tag_A) in the Initiate
* Tag field. Tag_A SHOULD be a random number in the range of
* 1 to 4294967295 (see 5.3.1 for Tag value selection). ...
*/
repl = sctp_make_init(asoc, &asoc->base.bind_addr, GFP_ATOMIC, 0);
if (!repl)
goto nomem;
/* Choose transport for INIT. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT,
SCTP_CHUNK(repl));
/* Cast away the const modifier, as we want to just
* rerun it through as a sideffect.
*/
my_asoc = (struct sctp_association *)asoc;
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(my_asoc));
/* After sending the INIT, "A" starts the T1-init timer and
* enters the COOKIE-WAIT state.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process the SEND primitive.
*
* Section: 10.1 ULP-to-SCTP
* E) Send
*
* Format: SEND(association id, buffer address, byte count [,context]
* [,stream id] [,life time] [,destination transport address]
* [,unorder flag] [,no-bundle flag] [,payload protocol-id] )
* -> result
*
* This is the main method to send user data via SCTP.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* o buffer address - the location where the user message to be
* transmitted is stored;
*
* o byte count - The size of the user data in number of bytes;
*
* Optional attributes:
*
* o context - an optional 32 bit integer that will be carried in the
* sending failure notification to the ULP if the transportation of
* this User Message fails.
*
* o stream id - to indicate which stream to send the data on. If not
* specified, stream 0 will be used.
*
* o life time - specifies the life time of the user data. The user data
* will not be sent by SCTP after the life time expires. This
* parameter can be used to avoid efforts to transmit stale
* user messages. SCTP notifies the ULP if the data cannot be
* initiated to transport (i.e. sent to the destination via SCTP's
* send primitive) within the life time variable. However, the
* user data will be transmitted if SCTP has attempted to transmit a
* chunk before the life time expired.
*
* o destination transport address - specified as one of the destination
* transport addresses of the peer endpoint to which this packet
* should be sent. Whenever possible, SCTP should use this destination
* transport address for sending the packets, instead of the current
* primary path.
*
* o unorder flag - this flag, if present, indicates that the user
* would like the data delivered in an unordered fashion to the peer
* (i.e., the U flag is set to 1 on all DATA chunks carrying this
* message).
*
* o no-bundle flag - instructs SCTP not to bundle this user data with
* other outbound DATA chunks. SCTP MAY still bundle even when
* this flag is present, when faced with network congestion.
*
* o payload protocol-id - A 32 bit unsigned integer that is to be
* passed to the peer indicating the type of payload protocol data
* being transmitted. This value is passed as opaque data by SCTP.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_prm_send(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_datamsg *msg = arg;
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_MSG, SCTP_DATAMSG(msg));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process the SHUTDOWN primitive.
*
* Section: 10.1:
* C) Shutdown
*
* Format: SHUTDOWN(association id)
* -> result
*
* Gracefully closes an association. Any locally queued user data
* will be delivered to the peer. The association will be terminated only
* after the peer acknowledges all the SCTP packets sent. A success code
* will be returned on successful termination of the association. If
* attempting to terminate the association results in a failure, an error
* code shall be returned.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* Optional attributes:
*
* None.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_2_prm_shutdown(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
int disposition;
/* From 9.2 Shutdown of an Association
* Upon receipt of the SHUTDOWN primitive from its upper
* layer, the endpoint enters SHUTDOWN-PENDING state and
* remains there until all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_PENDING));
disposition = SCTP_DISPOSITION_CONSUME;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = sctp_sf_do_9_2_start_shutdown(net, ep, asoc, type,
arg, commands);
}
return disposition;
}
/*
* Process the ABORT primitive.
*
* Section: 10.1:
* C) Abort
*
* Format: Abort(association id [, cause code])
* -> result
*
* Ungracefully closes an association. Any locally queued user data
* will be discarded and an ABORT chunk is sent to the peer. A success code
* will be returned on successful abortion of the association. If
* attempting to abort the association results in a failure, an error
* code shall be returned.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* Optional attributes:
*
* o cause code - reason of the abort to be passed to the peer
*
* None.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_1_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* From 9.1 Abort of an Association
* Upon receipt of the ABORT primitive from its upper
* layer, the endpoint enters CLOSED state and
* discard all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
struct sctp_chunk *abort = arg;
if (abort)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
/* Even if we can't send the ABORT due to low memory delete the
* TCB. This is a departure from our typical NOMEM handling.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
/* Delete the established association. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_USER_ABORT));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
/* We tried an illegal operation on an association which is closed. */
sctp_disposition_t sctp_sf_error_closed(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_ERROR, SCTP_ERROR(-EINVAL));
return SCTP_DISPOSITION_CONSUME;
}
/* We tried an illegal operation on an association which is shutting
* down.
*/
sctp_disposition_t sctp_sf_error_shutdown(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_ERROR,
SCTP_ERROR(-ESHUTDOWN));
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_cookie_wait_prm_shutdown
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues a shutdown while in COOKIE_WAIT state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_cookie_wait_prm_shutdown(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS);
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
}
/*
* sctp_cookie_echoed_prm_shutdown
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explcitly address this issue, but is the route through the
* state table when someone issues a shutdown while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_cookie_echoed_prm_shutdown(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, sctp_cmd_seq_t *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return sctp_sf_cookie_wait_prm_shutdown(net, ep, asoc, type, arg, commands);
}
/*
* sctp_sf_cookie_wait_prm_abort
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_WAIT state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_cookie_wait_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *abort = arg;
/* Stop T1-init timer */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
if (abort)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
/* Even if we can't send the ABORT due to low memory delete the
* TCB. This is a departure from our typical NOMEM handling.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNREFUSED));
/* Delete the established association. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_USER_ABORT));
return SCTP_DISPOSITION_ABORT;
}
/*
* sctp_sf_cookie_echoed_prm_abort
*
* Section: 4 Note: 3
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explcitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_cookie_echoed_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return sctp_sf_cookie_wait_prm_abort(net, ep, asoc, type, arg, commands);
}
/*
* sctp_sf_shutdown_pending_prm_abort
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in SHUTDOWN-PENDING state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_shutdown_pending_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
return sctp_sf_do_9_1_prm_abort(net, ep, asoc, type, arg, commands);
}
/*
* sctp_sf_shutdown_sent_prm_abort
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in SHUTDOWN-SENT state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_shutdown_sent_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Stop the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
return sctp_sf_do_9_1_prm_abort(net, ep, asoc, type, arg, commands);
}
/*
* sctp_sf_cookie_echoed_prm_abort
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explcitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_shutdown_ack_sent_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* The same T2 timer, so we should be able to use
* common function with the SHUTDOWN-SENT state.
*/
return sctp_sf_shutdown_sent_prm_abort(net, ep, asoc, type, arg, commands);
}
/*
* Process the REQUESTHEARTBEAT primitive
*
* 10.1 ULP-to-SCTP
* J) Request Heartbeat
*
* Format: REQUESTHEARTBEAT(association id, destination transport address)
*
* -> result
*
* Instructs the local endpoint to perform a HeartBeat on the specified
* destination transport address of the given association. The returned
* result should indicate whether the transmission of the HEARTBEAT
* chunk to the destination address is successful.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* o destination transport address - the transport address of the
* association on which a heartbeat should be issued.
*/
sctp_disposition_t sctp_sf_do_prm_requestheartbeat(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
if (SCTP_DISPOSITION_NOMEM == sctp_sf_heartbeat(ep, asoc, type,
(struct sctp_transport *)arg, commands))
return SCTP_DISPOSITION_NOMEM;
/*
* RFC 2960 (bis), section 8.3
*
* D) Request an on-demand HEARTBEAT on a specific destination
* transport address of a given association.
*
* The endpoint should increment the respective error counter of
* the destination transport address each time a HEARTBEAT is sent
* to that address and not acknowledged within one RTO.
*
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_HB_SENT,
SCTP_TRANSPORT(arg));
return SCTP_DISPOSITION_CONSUME;
}
/*
* ADDIP Section 4.1 ASCONF Chunk Procedures
* When an endpoint has an ASCONF signaled change to be sent to the
* remote endpoint it should do A1 to A9
*/
sctp_disposition_t sctp_sf_do_prm_asconf(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T4, SCTP_CHUNK(chunk));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(chunk));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Ignore the primitive event
*
* The return value is the disposition of the primitive.
*/
sctp_disposition_t sctp_sf_ignore_primitive(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
pr_debug("%s: primitive type:%d is ignored\n", __func__,
type.primitive);
return SCTP_DISPOSITION_DISCARD;
}
/***************************************************************************
* These are the state functions for the OTHER events.
***************************************************************************/
/*
* When the SCTP stack has no more user data to send or retransmit, this
* notification is given to the user. Also, at the time when a user app
* subscribes to this event, if there is no data to be sent or
* retransmit, the stack will immediately send up this notification.
*/
sctp_disposition_t sctp_sf_do_no_pending_tsn(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_ulpevent *event;
event = sctp_ulpevent_make_sender_dry_event(asoc, GFP_ATOMIC);
if (!event)
return SCTP_DISPOSITION_NOMEM;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(event));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Start the shutdown negotiation.
*
* From Section 9.2:
* Once all its outstanding data has been acknowledged, the endpoint
* shall send a SHUTDOWN chunk to its peer including in the Cumulative
* TSN Ack field the last sequential TSN it has received from the peer.
* It shall then start the T2-shutdown timer and enter the SHUTDOWN-SENT
* state. If the timer expires, the endpoint must re-send the SHUTDOWN
* with the updated last sequential TSN received from its peer.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_2_start_shutdown(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *reply;
/* Once all its outstanding data has been acknowledged, the
* endpoint shall send a SHUTDOWN chunk to its peer including
* in the Cumulative TSN Ack field the last sequential TSN it
* has received from the peer.
*/
reply = sctp_make_shutdown(asoc, NULL);
if (!reply)
goto nomem;
/* Set the transport for the SHUTDOWN chunk and the timeout for the
* T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* It shall then start the T2-shutdown timer */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
/* RFC 4960 Section 9.2
* The sender of the SHUTDOWN MAY also start an overall guard timer
* 'T5-shutdown-guard' to bound the overall time for shutdown sequence.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* and enter the SHUTDOWN-SENT state. */
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_SENT));
/* sctp-implguide 2.10 Issues with Heartbeating and failover
*
* HEARTBEAT ... is discontinued after sending either SHUTDOWN
* or SHUTDOWN-ACK.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Generate a SHUTDOWN ACK now that everything is SACK'd.
*
* From Section 9.2:
*
* If it has no more outstanding DATA chunks, the SHUTDOWN receiver
* shall send a SHUTDOWN ACK and start a T2-shutdown timer of its own,
* entering the SHUTDOWN-ACK-SENT state. If the timer expires, the
* endpoint must re-send the SHUTDOWN ACK.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_2_shutdown_ack(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = (struct sctp_chunk *) arg;
struct sctp_chunk *reply;
/* There are 2 ways of getting here:
* 1) called in response to a SHUTDOWN chunk
* 2) called when SCTP_EVENT_NO_PENDING_TSN event is issued.
*
* For the case (2), the arg parameter is set to NULL. We need
* to check that we have a chunk before accessing it's fields.
*/
if (chunk) {
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_shutdown_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
}
/* If it has no more outstanding DATA chunks, the SHUTDOWN receiver
* shall send a SHUTDOWN ACK ...
*/
reply = sctp_make_shutdown_ack(asoc, chunk);
if (!reply)
goto nomem;
/* Set the transport for the SHUTDOWN ACK chunk and the timeout for
* the T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* and start/restart a T2-shutdown timer of its own, */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* Enter the SHUTDOWN-ACK-SENT state. */
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_ACK_SENT));
/* sctp-implguide 2.10 Issues with Heartbeating and failover
*
* HEARTBEAT ... is discontinued after sending either SHUTDOWN
* or SHUTDOWN-ACK.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Ignore the event defined as other
*
* The return value is the disposition of the event.
*/
sctp_disposition_t sctp_sf_ignore_other(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
pr_debug("%s: the event other type:%d is ignored\n",
__func__, type.other);
return SCTP_DISPOSITION_DISCARD;
}
/************************************************************
* These are the state functions for handling timeout events.
************************************************************/
/*
* RTX Timeout
*
* Section: 6.3.3 Handle T3-rtx Expiration
*
* Whenever the retransmission timer T3-rtx expires for a destination
* address, do the following:
* [See below]
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_6_3_3_rtx(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_transport *transport = arg;
SCTP_INC_STATS(net, SCTP_MIB_T3_RTX_EXPIREDS);
if (asoc->overall_error_count >= asoc->max_retrans) {
if (asoc->peer.zero_window_announced &&
asoc->state == SCTP_STATE_SHUTDOWN_PENDING) {
/*
* We are here likely because the receiver had its rwnd
* closed for a while and we have not been able to
* transmit the locally queued data within the maximum
* retransmission attempts limit. Start the T5
* shutdown guard timer to give the receiver one last
* chance and some additional time to recover before
* aborting.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START_ONCE,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
}
}
/* E1) For the destination address for which the timer
* expires, adjust its ssthresh with rules defined in Section
* 7.2.3 and set the cwnd <- MTU.
*/
/* E2) For the destination address for which the timer
* expires, set RTO <- RTO * 2 ("back off the timer"). The
* maximum value discussed in rule C7 above (RTO.max) may be
* used to provide an upper bound to this doubling operation.
*/
/* E3) Determine how many of the earliest (i.e., lowest TSN)
* outstanding DATA chunks for the address for which the
* T3-rtx has expired will fit into a single packet, subject
* to the MTU constraint for the path corresponding to the
* destination transport address to which the retransmission
* is being sent (this may be different from the address for
* which the timer expires [see Section 6.4]). Call this
* value K. Bundle and retransmit those K DATA chunks in a
* single packet to the destination endpoint.
*
* Note: Any DATA chunks that were sent to the address for
* which the T3-rtx timer expired but did not fit in one MTU
* (rule E3 above), should be marked for retransmission and
* sent as soon as cwnd allows (normally when a SACK arrives).
*/
/* Do some failure management (Section 8.2). */
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE, SCTP_TRANSPORT(transport));
/* NB: Rules E4 and F1 are implicit in R1. */
sctp_add_cmd_sf(commands, SCTP_CMD_RETRAN, SCTP_TRANSPORT(transport));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Generate delayed SACK on timeout
*
* Section: 6.2 Acknowledgement on Reception of DATA Chunks
*
* The guidelines on delayed acknowledgement algorithm specified in
* Section 4.2 of [RFC2581] SHOULD be followed. Specifically, an
* acknowledgement SHOULD be generated for at least every second packet
* (not every second DATA chunk) received, and SHOULD be generated
* within 200 ms of the arrival of any unacknowledged DATA chunk. In
* some situations it may be beneficial for an SCTP transmitter to be
* more conservative than the algorithms detailed in this document
* allow. However, an SCTP transmitter MUST NOT be more aggressive than
* the following algorithms allow.
*/
sctp_disposition_t sctp_sf_do_6_2_sack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
SCTP_INC_STATS(net, SCTP_MIB_DELAY_SACK_EXPIREDS);
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_sf_t1_init_timer_expire
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* RFC 2960 Section 4 Notes
* 2) If the T1-init timer expires, the endpoint MUST retransmit INIT
* and re-start the T1-init timer without changing state. This MUST
* be repeated up to 'Max.Init.Retransmits' times. After that, the
* endpoint MUST abort the initialization process and report the
* error to SCTP user.
*
* Outputs
* (timers, events)
*
*/
sctp_disposition_t sctp_sf_t1_init_timer_expire(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *repl = NULL;
struct sctp_bind_addr *bp;
int attempts = asoc->init_err_counter + 1;
pr_debug("%s: timer T1 expired (INIT)\n", __func__);
SCTP_INC_STATS(net, SCTP_MIB_T1_INIT_EXPIREDS);
if (attempts <= asoc->max_init_attempts) {
bp = (struct sctp_bind_addr *) &asoc->base.bind_addr;
repl = sctp_make_init(asoc, bp, GFP_ATOMIC, 0);
if (!repl)
return SCTP_DISPOSITION_NOMEM;
/* Choose transport for INIT. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT,
SCTP_CHUNK(repl));
/* Issue a sideeffect to do the needed accounting. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
} else {
pr_debug("%s: giving up on INIT, attempts:%d "
"max_init_attempts:%d\n", __func__, attempts,
asoc->max_init_attempts);
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
return SCTP_DISPOSITION_DELETE_TCB;
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_sf_t1_cookie_timer_expire
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* RFC 2960 Section 4 Notes
* 3) If the T1-cookie timer expires, the endpoint MUST retransmit
* COOKIE ECHO and re-start the T1-cookie timer without changing
* state. This MUST be repeated up to 'Max.Init.Retransmits' times.
* After that, the endpoint MUST abort the initialization process and
* report the error to SCTP user.
*
* Outputs
* (timers, events)
*
*/
sctp_disposition_t sctp_sf_t1_cookie_timer_expire(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *repl = NULL;
int attempts = asoc->init_err_counter + 1;
pr_debug("%s: timer T1 expired (COOKIE-ECHO)\n", __func__);
SCTP_INC_STATS(net, SCTP_MIB_T1_COOKIE_EXPIREDS);
if (attempts <= asoc->max_init_attempts) {
repl = sctp_make_cookie_echo(asoc, NULL);
if (!repl)
return SCTP_DISPOSITION_NOMEM;
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT,
SCTP_CHUNK(repl));
/* Issue a sideeffect to do the needed accounting. */
sctp_add_cmd_sf(commands, SCTP_CMD_COOKIEECHO_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
return SCTP_DISPOSITION_DELETE_TCB;
}
return SCTP_DISPOSITION_CONSUME;
}
/* RFC2960 9.2 If the timer expires, the endpoint must re-send the SHUTDOWN
* with the updated last sequential TSN received from its peer.
*
* An endpoint should limit the number of retransmissions of the
* SHUTDOWN chunk to the protocol parameter 'Association.Max.Retrans'.
* If this threshold is exceeded the endpoint should destroy the TCB and
* MUST report the peer endpoint unreachable to the upper layer (and
* thus the association enters the CLOSED state). The reception of any
* packet from its peer (i.e. as the peer sends all of its queued DATA
* chunks) should clear the endpoint's retransmission count and restart
* the T2-Shutdown timer, giving its peer ample opportunity to transmit
* all of its queued DATA chunks that have not yet been sent.
*/
sctp_disposition_t sctp_sf_t2_timer_expire(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *reply = NULL;
pr_debug("%s: timer T2 expired\n", __func__);
SCTP_INC_STATS(net, SCTP_MIB_T2_SHUTDOWN_EXPIREDS);
((struct sctp_association *)asoc)->shutdown_retries++;
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* Note: CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
}
switch (asoc->state) {
case SCTP_STATE_SHUTDOWN_SENT:
reply = sctp_make_shutdown(asoc, NULL);
break;
case SCTP_STATE_SHUTDOWN_ACK_SENT:
reply = sctp_make_shutdown_ack(asoc, NULL);
break;
default:
BUG();
break;
}
if (!reply)
goto nomem;
/* Do some failure management (Section 8.2).
* If we remove the transport an SHUTDOWN was last sent to, don't
* do failure management.
*/
if (asoc->shutdown_last_sent_to)
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE,
SCTP_TRANSPORT(asoc->shutdown_last_sent_to));
/* Set the transport for the SHUTDOWN/ACK chunk and the timeout for
* the T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* Restart the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* ADDIP Section 4.1 ASCONF CHunk Procedures
* If the T4 RTO timer expires the endpoint should do B1 to B5
*/
sctp_disposition_t sctp_sf_t4_timer_expire(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = asoc->addip_last_asconf;
struct sctp_transport *transport = chunk->transport;
SCTP_INC_STATS(net, SCTP_MIB_T4_RTO_EXPIREDS);
/* ADDIP 4.1 B1) Increment the error counters and perform path failure
* detection on the appropriate destination address as defined in
* RFC2960 [5] section 8.1 and 8.2.
*/
if (transport)
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE,
SCTP_TRANSPORT(transport));
/* Reconfig T4 timer and transport. */
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T4, SCTP_CHUNK(chunk));
/* ADDIP 4.1 B2) Increment the association error counters and perform
* endpoint failure detection on the association as defined in
* RFC2960 [5] section 8.1 and 8.2.
* association error counter is incremented in SCTP_CMD_STRIKE.
*/
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
/* ADDIP 4.1 B3) Back-off the destination address RTO value to which
* the ASCONF chunk was sent by doubling the RTO timer value.
* This is done in SCTP_CMD_STRIKE.
*/
/* ADDIP 4.1 B4) Re-transmit the ASCONF Chunk last sent and if possible
* choose an alternate destination address (please refer to RFC2960
* [5] section 6.4.1). An endpoint MUST NOT add new parameters to this
* chunk, it MUST be the same (including its serial number) as the last
* ASCONF sent.
*/
sctp_chunk_hold(asoc->addip_last_asconf);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(asoc->addip_last_asconf));
/* ADDIP 4.1 B5) Restart the T-4 RTO timer. Note that if a different
* destination is selected, then the RTO used will be that of the new
* destination address.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
return SCTP_DISPOSITION_CONSUME;
}
/* sctpimpguide-05 Section 2.12.2
* The sender of the SHUTDOWN MAY also start an overall guard timer
* 'T5-shutdown-guard' to bound the overall time for shutdown sequence.
* At the expiration of this timer the sender SHOULD abort the association
* by sending an ABORT chunk.
*/
sctp_disposition_t sctp_sf_t5_timer_expire(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *reply = NULL;
pr_debug("%s: timer T5 expired\n", __func__);
SCTP_INC_STATS(net, SCTP_MIB_T5_SHUTDOWN_GUARD_EXPIREDS);
reply = sctp_make_abort(asoc, NULL, 0);
if (!reply)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Handle expiration of AUTOCLOSE timer. When the autoclose timer expires,
* the association is automatically closed by starting the shutdown process.
* The work that needs to be done is same as when SHUTDOWN is initiated by
* the user. So this routine looks same as sctp_sf_do_9_2_prm_shutdown().
*/
sctp_disposition_t sctp_sf_autoclose_timer_expire(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
int disposition;
SCTP_INC_STATS(net, SCTP_MIB_AUTOCLOSE_EXPIREDS);
/* From 9.2 Shutdown of an Association
* Upon receipt of the SHUTDOWN primitive from its upper
* layer, the endpoint enters SHUTDOWN-PENDING state and
* remains there until all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_PENDING));
disposition = SCTP_DISPOSITION_CONSUME;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = sctp_sf_do_9_2_start_shutdown(net, ep, asoc, type,
arg, commands);
}
return disposition;
}
/*****************************************************************************
* These are sa state functions which could apply to all types of events.
****************************************************************************/
/*
* This table entry is not implemented.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_not_impl(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
return SCTP_DISPOSITION_NOT_IMPL;
}
/*
* This table entry represents a bug.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_bug(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
return SCTP_DISPOSITION_BUG;
}
/*
* This table entry represents the firing of a timer in the wrong state.
* Since timer deletion cannot be guaranteed a timer 'may' end up firing
* when the association is in the wrong state. This event should
* be ignored, so as to prevent any rearming of the timer.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_timer_ignore(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
pr_debug("%s: timer %d ignored\n", __func__, type.chunk);
return SCTP_DISPOSITION_CONSUME;
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
/* Pull the SACK chunk based on the SACK header. */
static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk)
{
struct sctp_sackhdr *sack;
unsigned int len;
__u16 num_blocks;
__u16 num_dup_tsns;
/* Protect ourselves from reading too far into
* the skb from a bogus sender.
*/
sack = (struct sctp_sackhdr *) chunk->skb->data;
num_blocks = ntohs(sack->num_gap_ack_blocks);
num_dup_tsns = ntohs(sack->num_dup_tsns);
len = sizeof(struct sctp_sackhdr);
len += (num_blocks + num_dup_tsns) * sizeof(__u32);
if (len > chunk->skb->len)
return NULL;
skb_pull(chunk->skb, len);
return sack;
}
/* Create an ABORT packet to be sent as a response, with the specified
* error causes.
*/
static struct sctp_packet *sctp_abort_pkt_new(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
const void *payload,
size_t paylen)
{
struct sctp_packet *packet;
struct sctp_chunk *abort;
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (packet) {
/* Make an ABORT.
* The T bit will be set if the asoc is NULL.
*/
abort = sctp_make_abort(asoc, chunk, paylen);
if (!abort) {
sctp_ootb_pkt_free(packet);
return NULL;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Add specified error causes, i.e., payload, to the
* end of the chunk.
*/
sctp_addto_chunk(abort, paylen, payload);
/* Set the skb to the belonging sock for accounting. */
abort->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, abort);
}
return packet;
}
/* Allocate a packet for responding in the OOTB conditions. */
static struct sctp_packet *sctp_ootb_pkt_new(struct net *net,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_packet *packet;
struct sctp_transport *transport;
__u16 sport;
__u16 dport;
__u32 vtag;
/* Get the source and destination port from the inbound packet. */
sport = ntohs(chunk->sctp_hdr->dest);
dport = ntohs(chunk->sctp_hdr->source);
/* The V-tag is going to be the same as the inbound packet if no
* association exists, otherwise, use the peer's vtag.
*/
if (asoc) {
/* Special case the INIT-ACK as there is no peer's vtag
* yet.
*/
switch (chunk->chunk_hdr->type) {
case SCTP_CID_INIT_ACK:
{
sctp_initack_chunk_t *initack;
initack = (sctp_initack_chunk_t *)chunk->chunk_hdr;
vtag = ntohl(initack->init_hdr.init_tag);
break;
}
default:
vtag = asoc->peer.i.init_tag;
break;
}
} else {
/* Special case the INIT and stale COOKIE_ECHO as there is no
* vtag yet.
*/
switch (chunk->chunk_hdr->type) {
case SCTP_CID_INIT:
{
sctp_init_chunk_t *init;
init = (sctp_init_chunk_t *)chunk->chunk_hdr;
vtag = ntohl(init->init_hdr.init_tag);
break;
}
default:
vtag = ntohl(chunk->sctp_hdr->vtag);
break;
}
}
/* Make a transport for the bucket, Eliza... */
transport = sctp_transport_new(net, sctp_source(chunk), GFP_ATOMIC);
if (!transport)
goto nomem;
/* Cache a route for the transport with the chunk's destination as
* the source address.
*/
sctp_transport_route(transport, (union sctp_addr *)&chunk->dest,
sctp_sk(net->sctp.ctl_sock));
packet = sctp_packet_init(&transport->packet, transport, sport, dport);
packet = sctp_packet_config(packet, vtag, 0);
return packet;
nomem:
return NULL;
}
/* Free the packet allocated earlier for responding in the OOTB condition. */
void sctp_ootb_pkt_free(struct sctp_packet *packet)
{
sctp_transport_free(packet->transport);
}
/* Send a stale cookie error when a invalid COOKIE ECHO chunk is found */
static void sctp_send_stale_cookie_err(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_chunk *err_chunk)
{
struct sctp_packet *packet;
if (err_chunk) {
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (packet) {
struct sctp_signed_cookie *cookie;
/* Override the OOTB vtag from the cookie. */
cookie = chunk->subh.cookie_hdr;
packet->vtag = cookie->c.peer_vtag;
/* Set the skb to the belonging sock for accounting. */
err_chunk->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, err_chunk);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
} else
sctp_chunk_free (err_chunk);
}
}
/* Process a data chunk */
static int sctp_eat_data(const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands)
{
sctp_datahdr_t *data_hdr;
struct sctp_chunk *err;
size_t datalen;
sctp_verb_t deliver;
int tmp;
__u32 tsn;
struct sctp_tsnmap *map = (struct sctp_tsnmap *)&asoc->peer.tsn_map;
struct sock *sk = asoc->base.sk;
struct net *net = sock_net(sk);
u16 ssn;
u16 sid;
u8 ordered = 0;
data_hdr = chunk->subh.data_hdr = (sctp_datahdr_t *)chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_datahdr_t));
tsn = ntohl(data_hdr->tsn);
pr_debug("%s: TSN 0x%x\n", __func__, tsn);
/* ASSERT: Now skb->data is really the user data. */
/* Process ECN based congestion.
*
* Since the chunk structure is reused for all chunks within
* a packet, we use ecn_ce_done to track if we've already
* done CE processing for this packet.
*
* We need to do ECN processing even if we plan to discard the
* chunk later.
*/
if (asoc->peer.ecn_capable && !chunk->ecn_ce_done) {
struct sctp_af *af = SCTP_INPUT_CB(chunk->skb)->af;
chunk->ecn_ce_done = 1;
if (af->is_ce(sctp_gso_headskb(chunk->skb))) {
/* Do real work as sideffect. */
sctp_add_cmd_sf(commands, SCTP_CMD_ECN_CE,
SCTP_U32(tsn));
}
}
tmp = sctp_tsnmap_check(&asoc->peer.tsn_map, tsn);
if (tmp < 0) {
/* The TSN is too high--silently discard the chunk and
* count on it getting retransmitted later.
*/
if (chunk->asoc)
chunk->asoc->stats.outofseqtsns++;
return SCTP_IERROR_HIGH_TSN;
} else if (tmp > 0) {
/* This is a duplicate. Record it. */
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_DUP, SCTP_U32(tsn));
return SCTP_IERROR_DUP_TSN;
}
/* This is a new TSN. */
/* Discard if there is no room in the receive window.
* Actually, allow a little bit of overflow (up to a MTU).
*/
datalen = ntohs(chunk->chunk_hdr->length);
datalen -= sizeof(sctp_data_chunk_t);
deliver = SCTP_CMD_CHUNK_ULP;
/* Think about partial delivery. */
if ((datalen >= asoc->rwnd) && (!asoc->ulpq.pd_mode)) {
/* Even if we don't accept this chunk there is
* memory pressure.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_PART_DELIVER, SCTP_NULL());
}
/* Spill over rwnd a little bit. Note: While allowed, this spill over
* seems a bit troublesome in that frag_point varies based on
* PMTU. In cases, such as loopback, this might be a rather
* large spill over.
*/
if ((!chunk->data_accepted) && (!asoc->rwnd || asoc->rwnd_over ||
(datalen > asoc->rwnd + asoc->frag_point))) {
/* If this is the next TSN, consider reneging to make
* room. Note: Playing nice with a confused sender. A
* malicious sender can still eat up all our buffer
* space and in the future we may want to detect and
* do more drastic reneging.
*/
if (sctp_tsnmap_has_gap(map) &&
(sctp_tsnmap_get_ctsn(map) + 1) == tsn) {
pr_debug("%s: reneging for tsn:%u\n", __func__, tsn);
deliver = SCTP_CMD_RENEGE;
} else {
pr_debug("%s: discard tsn:%u len:%zu, rwnd:%d\n",
__func__, tsn, datalen, asoc->rwnd);
return SCTP_IERROR_IGNORE_TSN;
}
}
/*
* Also try to renege to limit our memory usage in the event that
* we are under memory pressure
* If we can't renege, don't worry about it, the sk_rmem_schedule
* in sctp_ulpevent_make_rcvmsg will drop the frame if we grow our
* memory usage too much
*/
if (*sk->sk_prot_creator->memory_pressure) {
if (sctp_tsnmap_has_gap(map) &&
(sctp_tsnmap_get_ctsn(map) + 1) == tsn) {
pr_debug("%s: under pressure, reneging for tsn:%u\n",
__func__, tsn);
deliver = SCTP_CMD_RENEGE;
}
}
/*
* Section 3.3.10.9 No User Data (9)
*
* Cause of error
* ---------------
* No User Data: This error cause is returned to the originator of a
* DATA chunk if a received DATA chunk has no user data.
*/
if (unlikely(0 == datalen)) {
err = sctp_make_abort_no_data(asoc, chunk, tsn);
if (err) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_DATA));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_IERROR_NO_DATA;
}
chunk->data_accepted = 1;
/* Note: Some chunks may get overcounted (if we drop) or overcounted
* if we renege and the chunk arrives again.
*/
if (chunk->chunk_hdr->flags & SCTP_DATA_UNORDERED) {
SCTP_INC_STATS(net, SCTP_MIB_INUNORDERCHUNKS);
if (chunk->asoc)
chunk->asoc->stats.iuodchunks++;
} else {
SCTP_INC_STATS(net, SCTP_MIB_INORDERCHUNKS);
if (chunk->asoc)
chunk->asoc->stats.iodchunks++;
ordered = 1;
}
/* RFC 2960 6.5 Stream Identifier and Stream Sequence Number
*
* If an endpoint receive a DATA chunk with an invalid stream
* identifier, it shall acknowledge the reception of the DATA chunk
* following the normal procedure, immediately send an ERROR chunk
* with cause set to "Invalid Stream Identifier" (See Section 3.3.10)
* and discard the DATA chunk.
*/
sid = ntohs(data_hdr->stream);
if (sid >= asoc->c.sinit_max_instreams) {
/* Mark tsn as received even though we drop it */
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_TSN, SCTP_U32(tsn));
err = sctp_make_op_error(asoc, chunk, SCTP_ERROR_INV_STRM,
&data_hdr->stream,
sizeof(data_hdr->stream),
sizeof(u16));
if (err)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
return SCTP_IERROR_BAD_STREAM;
}
/* Check to see if the SSN is possible for this TSN.
* The biggest gap we can record is 4K wide. Since SSNs wrap
* at an unsigned short, there is no way that an SSN can
* wrap and for a valid TSN. We can simply check if the current
* SSN is smaller then the next expected one. If it is, it wrapped
* and is invalid.
*/
ssn = ntohs(data_hdr->ssn);
if (ordered && SSN_lt(ssn, sctp_ssn_peek(&asoc->ssnmap->in, sid))) {
return SCTP_IERROR_PROTO_VIOLATION;
}
/* Send the data up to the user. Note: Schedule the
* SCTP_CMD_CHUNK_ULP cmd before the SCTP_CMD_GEN_SACK, as the SACK
* chunk needs the updated rwnd.
*/
sctp_add_cmd_sf(commands, deliver, SCTP_CHUNK(chunk));
return SCTP_IERROR_NO_ERROR;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5483_0 |
crossvul-cpp_data_bad_1330_0 | /*
* Copyright (c) Red Hat Inc.
* 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, sub license,
* 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 (including the
* next paragraph) 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 NON-INFRINGEMENT. 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.
*
* Authors: Dave Airlie <airlied@redhat.com>
* Jerome Glisse <jglisse@redhat.com>
* Pauli Nieminen <suokkos@gmail.com>
*/
/* simple list based uncached page pool
* - Pool collects resently freed pages for reuse
* - Use page->lru to keep a free list
* - doesn't track currently in use pages
*/
#define pr_fmt(fmt) "[TTM] " fmt
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/highmem.h>
#include <linux/mm_types.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/seq_file.h> /* for seq_printf */
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include <linux/atomic.h>
#include <drm/ttm/ttm_bo_driver.h>
#include <drm/ttm/ttm_page_alloc.h>
#include <drm/ttm/ttm_set_memory.h>
#define NUM_PAGES_TO_ALLOC (PAGE_SIZE/sizeof(struct page *))
#define SMALL_ALLOCATION 16
#define FREE_ALL_PAGES (~0U)
/* times are in msecs */
#define PAGE_FREE_INTERVAL 1000
/**
* struct ttm_page_pool - Pool to reuse recently allocated uc/wc pages.
*
* @lock: Protects the shared pool from concurrnet access. Must be used with
* irqsave/irqrestore variants because pool allocator maybe called from
* delayed work.
* @fill_lock: Prevent concurrent calls to fill.
* @list: Pool of free uc/wc pages for fast reuse.
* @gfp_flags: Flags to pass for alloc_page.
* @npages: Number of pages in pool.
*/
struct ttm_page_pool {
spinlock_t lock;
bool fill_lock;
struct list_head list;
gfp_t gfp_flags;
unsigned npages;
char *name;
unsigned long nfrees;
unsigned long nrefills;
unsigned int order;
};
/**
* Limits for the pool. They are handled without locks because only place where
* they may change is in sysfs store. They won't have immediate effect anyway
* so forcing serialization to access them is pointless.
*/
struct ttm_pool_opts {
unsigned alloc_size;
unsigned max_size;
unsigned small;
};
#define NUM_POOLS 6
/**
* struct ttm_pool_manager - Holds memory pools for fst allocation
*
* Manager is read only object for pool code so it doesn't need locking.
*
* @free_interval: minimum number of jiffies between freeing pages from pool.
* @page_alloc_inited: reference counting for pool allocation.
* @work: Work that is used to shrink the pool. Work is only run when there is
* some pages to free.
* @small_allocation: Limit in number of pages what is small allocation.
*
* @pools: All pool objects in use.
**/
struct ttm_pool_manager {
struct kobject kobj;
struct shrinker mm_shrink;
struct ttm_pool_opts options;
union {
struct ttm_page_pool pools[NUM_POOLS];
struct {
struct ttm_page_pool wc_pool;
struct ttm_page_pool uc_pool;
struct ttm_page_pool wc_pool_dma32;
struct ttm_page_pool uc_pool_dma32;
struct ttm_page_pool wc_pool_huge;
struct ttm_page_pool uc_pool_huge;
} ;
};
};
static struct attribute ttm_page_pool_max = {
.name = "pool_max_size",
.mode = S_IRUGO | S_IWUSR
};
static struct attribute ttm_page_pool_small = {
.name = "pool_small_allocation",
.mode = S_IRUGO | S_IWUSR
};
static struct attribute ttm_page_pool_alloc_size = {
.name = "pool_allocation_size",
.mode = S_IRUGO | S_IWUSR
};
static struct attribute *ttm_pool_attrs[] = {
&ttm_page_pool_max,
&ttm_page_pool_small,
&ttm_page_pool_alloc_size,
NULL
};
static void ttm_pool_kobj_release(struct kobject *kobj)
{
struct ttm_pool_manager *m =
container_of(kobj, struct ttm_pool_manager, kobj);
kfree(m);
}
static ssize_t ttm_pool_store(struct kobject *kobj,
struct attribute *attr, const char *buffer, size_t size)
{
struct ttm_pool_manager *m =
container_of(kobj, struct ttm_pool_manager, kobj);
int chars;
unsigned val;
chars = sscanf(buffer, "%u", &val);
if (chars == 0)
return size;
/* Convert kb to number of pages */
val = val / (PAGE_SIZE >> 10);
if (attr == &ttm_page_pool_max)
m->options.max_size = val;
else if (attr == &ttm_page_pool_small)
m->options.small = val;
else if (attr == &ttm_page_pool_alloc_size) {
if (val > NUM_PAGES_TO_ALLOC*8) {
pr_err("Setting allocation size to %lu is not allowed. Recommended size is %lu\n",
NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 7),
NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10));
return size;
} else if (val > NUM_PAGES_TO_ALLOC) {
pr_warn("Setting allocation size to larger than %lu is not recommended\n",
NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10));
}
m->options.alloc_size = val;
}
return size;
}
static ssize_t ttm_pool_show(struct kobject *kobj,
struct attribute *attr, char *buffer)
{
struct ttm_pool_manager *m =
container_of(kobj, struct ttm_pool_manager, kobj);
unsigned val = 0;
if (attr == &ttm_page_pool_max)
val = m->options.max_size;
else if (attr == &ttm_page_pool_small)
val = m->options.small;
else if (attr == &ttm_page_pool_alloc_size)
val = m->options.alloc_size;
val = val * (PAGE_SIZE >> 10);
return snprintf(buffer, PAGE_SIZE, "%u\n", val);
}
static const struct sysfs_ops ttm_pool_sysfs_ops = {
.show = &ttm_pool_show,
.store = &ttm_pool_store,
};
static struct kobj_type ttm_pool_kobj_type = {
.release = &ttm_pool_kobj_release,
.sysfs_ops = &ttm_pool_sysfs_ops,
.default_attrs = ttm_pool_attrs,
};
static struct ttm_pool_manager *_manager;
/**
* Select the right pool or requested caching state and ttm flags. */
static struct ttm_page_pool *ttm_get_pool(int flags, bool huge,
enum ttm_caching_state cstate)
{
int pool_index;
if (cstate == tt_cached)
return NULL;
if (cstate == tt_wc)
pool_index = 0x0;
else
pool_index = 0x1;
if (flags & TTM_PAGE_FLAG_DMA32) {
if (huge)
return NULL;
pool_index |= 0x2;
} else if (huge) {
pool_index |= 0x4;
}
return &_manager->pools[pool_index];
}
/* set memory back to wb and free the pages. */
static void ttm_pages_put(struct page *pages[], unsigned npages,
unsigned int order)
{
unsigned int i, pages_nr = (1 << order);
if (order == 0) {
if (ttm_set_pages_array_wb(pages, npages))
pr_err("Failed to set %d pages to wb!\n", npages);
}
for (i = 0; i < npages; ++i) {
if (order > 0) {
if (ttm_set_pages_wb(pages[i], pages_nr))
pr_err("Failed to set %d pages to wb!\n", pages_nr);
}
__free_pages(pages[i], order);
}
}
static void ttm_pool_update_free_locked(struct ttm_page_pool *pool,
unsigned freed_pages)
{
pool->npages -= freed_pages;
pool->nfrees += freed_pages;
}
/**
* Free pages from pool.
*
* To prevent hogging the ttm_swap process we only free NUM_PAGES_TO_ALLOC
* number of pages in one go.
*
* @pool: to free the pages from
* @free_all: If set to true will free all pages in pool
* @use_static: Safe to use static buffer
**/
static int ttm_page_pool_free(struct ttm_page_pool *pool, unsigned nr_free,
bool use_static)
{
static struct page *static_buf[NUM_PAGES_TO_ALLOC];
unsigned long irq_flags;
struct page *p;
struct page **pages_to_free;
unsigned freed_pages = 0,
npages_to_free = nr_free;
if (NUM_PAGES_TO_ALLOC < nr_free)
npages_to_free = NUM_PAGES_TO_ALLOC;
if (use_static)
pages_to_free = static_buf;
else
pages_to_free = kmalloc_array(npages_to_free,
sizeof(struct page *),
GFP_KERNEL);
if (!pages_to_free) {
pr_debug("Failed to allocate memory for pool free operation\n");
return 0;
}
restart:
spin_lock_irqsave(&pool->lock, irq_flags);
list_for_each_entry_reverse(p, &pool->list, lru) {
if (freed_pages >= npages_to_free)
break;
pages_to_free[freed_pages++] = p;
/* We can only remove NUM_PAGES_TO_ALLOC at a time. */
if (freed_pages >= NUM_PAGES_TO_ALLOC) {
/* remove range of pages from the pool */
__list_del(p->lru.prev, &pool->list);
ttm_pool_update_free_locked(pool, freed_pages);
/**
* Because changing page caching is costly
* we unlock the pool to prevent stalling.
*/
spin_unlock_irqrestore(&pool->lock, irq_flags);
ttm_pages_put(pages_to_free, freed_pages, pool->order);
if (likely(nr_free != FREE_ALL_PAGES))
nr_free -= freed_pages;
if (NUM_PAGES_TO_ALLOC >= nr_free)
npages_to_free = nr_free;
else
npages_to_free = NUM_PAGES_TO_ALLOC;
freed_pages = 0;
/* free all so restart the processing */
if (nr_free)
goto restart;
/* Not allowed to fall through or break because
* following context is inside spinlock while we are
* outside here.
*/
goto out;
}
}
/* remove range of pages from the pool */
if (freed_pages) {
__list_del(&p->lru, &pool->list);
ttm_pool_update_free_locked(pool, freed_pages);
nr_free -= freed_pages;
}
spin_unlock_irqrestore(&pool->lock, irq_flags);
if (freed_pages)
ttm_pages_put(pages_to_free, freed_pages, pool->order);
out:
if (pages_to_free != static_buf)
kfree(pages_to_free);
return nr_free;
}
/**
* Callback for mm to request pool to reduce number of page held.
*
* XXX: (dchinner) Deadlock warning!
*
* This code is crying out for a shrinker per pool....
*/
static unsigned long
ttm_pool_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
{
static DEFINE_MUTEX(lock);
static unsigned start_pool;
unsigned i;
unsigned pool_offset;
struct ttm_page_pool *pool;
int shrink_pages = sc->nr_to_scan;
unsigned long freed = 0;
unsigned int nr_free_pool;
if (!mutex_trylock(&lock))
return SHRINK_STOP;
pool_offset = ++start_pool % NUM_POOLS;
/* select start pool in round robin fashion */
for (i = 0; i < NUM_POOLS; ++i) {
unsigned nr_free = shrink_pages;
unsigned page_nr;
if (shrink_pages == 0)
break;
pool = &_manager->pools[(i + pool_offset)%NUM_POOLS];
page_nr = (1 << pool->order);
/* OK to use static buffer since global mutex is held. */
nr_free_pool = roundup(nr_free, page_nr) >> pool->order;
shrink_pages = ttm_page_pool_free(pool, nr_free_pool, true);
freed += (nr_free_pool - shrink_pages) << pool->order;
if (freed >= sc->nr_to_scan)
break;
shrink_pages <<= pool->order;
}
mutex_unlock(&lock);
return freed;
}
static unsigned long
ttm_pool_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
{
unsigned i;
unsigned long count = 0;
struct ttm_page_pool *pool;
for (i = 0; i < NUM_POOLS; ++i) {
pool = &_manager->pools[i];
count += (pool->npages << pool->order);
}
return count;
}
static int ttm_pool_mm_shrink_init(struct ttm_pool_manager *manager)
{
manager->mm_shrink.count_objects = ttm_pool_shrink_count;
manager->mm_shrink.scan_objects = ttm_pool_shrink_scan;
manager->mm_shrink.seeks = 1;
return register_shrinker(&manager->mm_shrink);
}
static void ttm_pool_mm_shrink_fini(struct ttm_pool_manager *manager)
{
unregister_shrinker(&manager->mm_shrink);
}
static int ttm_set_pages_caching(struct page **pages,
enum ttm_caching_state cstate, unsigned cpages)
{
int r = 0;
/* Set page caching */
switch (cstate) {
case tt_uncached:
r = ttm_set_pages_array_uc(pages, cpages);
if (r)
pr_err("Failed to set %d pages to uc!\n", cpages);
break;
case tt_wc:
r = ttm_set_pages_array_wc(pages, cpages);
if (r)
pr_err("Failed to set %d pages to wc!\n", cpages);
break;
default:
break;
}
return r;
}
/**
* Free pages the pages that failed to change the caching state. If there is
* any pages that have changed their caching state already put them to the
* pool.
*/
static void ttm_handle_caching_state_failure(struct list_head *pages,
int ttm_flags, enum ttm_caching_state cstate,
struct page **failed_pages, unsigned cpages)
{
unsigned i;
/* Failed pages have to be freed */
for (i = 0; i < cpages; ++i) {
list_del(&failed_pages[i]->lru);
__free_page(failed_pages[i]);
}
}
/**
* Allocate new pages with correct caching.
*
* This function is reentrant if caller updates count depending on number of
* pages returned in pages array.
*/
static int ttm_alloc_new_pages(struct list_head *pages, gfp_t gfp_flags,
int ttm_flags, enum ttm_caching_state cstate,
unsigned count, unsigned order)
{
struct page **caching_array;
struct page *p;
int r = 0;
unsigned i, j, cpages;
unsigned npages = 1 << order;
unsigned max_cpages = min(count << order, (unsigned)NUM_PAGES_TO_ALLOC);
/* allocate array for page caching change */
caching_array = kmalloc_array(max_cpages, sizeof(struct page *),
GFP_KERNEL);
if (!caching_array) {
pr_debug("Unable to allocate table for new pages\n");
return -ENOMEM;
}
for (i = 0, cpages = 0; i < count; ++i) {
p = alloc_pages(gfp_flags, order);
if (!p) {
pr_debug("Unable to get page %u\n", i);
/* store already allocated pages in the pool after
* setting the caching state */
if (cpages) {
r = ttm_set_pages_caching(caching_array,
cstate, cpages);
if (r)
ttm_handle_caching_state_failure(pages,
ttm_flags, cstate,
caching_array, cpages);
}
r = -ENOMEM;
goto out;
}
list_add(&p->lru, pages);
#ifdef CONFIG_HIGHMEM
/* gfp flags of highmem page should never be dma32 so we
* we should be fine in such case
*/
if (PageHighMem(p))
continue;
#endif
for (j = 0; j < npages; ++j) {
caching_array[cpages++] = p++;
if (cpages == max_cpages) {
r = ttm_set_pages_caching(caching_array,
cstate, cpages);
if (r) {
ttm_handle_caching_state_failure(pages,
ttm_flags, cstate,
caching_array, cpages);
goto out;
}
cpages = 0;
}
}
}
if (cpages) {
r = ttm_set_pages_caching(caching_array, cstate, cpages);
if (r)
ttm_handle_caching_state_failure(pages,
ttm_flags, cstate,
caching_array, cpages);
}
out:
kfree(caching_array);
return r;
}
/**
* Fill the given pool if there aren't enough pages and the requested number of
* pages is small.
*/
static void ttm_page_pool_fill_locked(struct ttm_page_pool *pool, int ttm_flags,
enum ttm_caching_state cstate,
unsigned count, unsigned long *irq_flags)
{
struct page *p;
int r;
unsigned cpages = 0;
/**
* Only allow one pool fill operation at a time.
* If pool doesn't have enough pages for the allocation new pages are
* allocated from outside of pool.
*/
if (pool->fill_lock)
return;
pool->fill_lock = true;
/* If allocation request is small and there are not enough
* pages in a pool we fill the pool up first. */
if (count < _manager->options.small
&& count > pool->npages) {
struct list_head new_pages;
unsigned alloc_size = _manager->options.alloc_size;
/**
* Can't change page caching if in irqsave context. We have to
* drop the pool->lock.
*/
spin_unlock_irqrestore(&pool->lock, *irq_flags);
INIT_LIST_HEAD(&new_pages);
r = ttm_alloc_new_pages(&new_pages, pool->gfp_flags, ttm_flags,
cstate, alloc_size, 0);
spin_lock_irqsave(&pool->lock, *irq_flags);
if (!r) {
list_splice(&new_pages, &pool->list);
++pool->nrefills;
pool->npages += alloc_size;
} else {
pr_debug("Failed to fill pool (%p)\n", pool);
/* If we have any pages left put them to the pool. */
list_for_each_entry(p, &new_pages, lru) {
++cpages;
}
list_splice(&new_pages, &pool->list);
pool->npages += cpages;
}
}
pool->fill_lock = false;
}
/**
* Allocate pages from the pool and put them on the return list.
*
* @return zero for success or negative error code.
*/
static int ttm_page_pool_get_pages(struct ttm_page_pool *pool,
struct list_head *pages,
int ttm_flags,
enum ttm_caching_state cstate,
unsigned count, unsigned order)
{
unsigned long irq_flags;
struct list_head *p;
unsigned i;
int r = 0;
spin_lock_irqsave(&pool->lock, irq_flags);
if (!order)
ttm_page_pool_fill_locked(pool, ttm_flags, cstate, count,
&irq_flags);
if (count >= pool->npages) {
/* take all pages from the pool */
list_splice_init(&pool->list, pages);
count -= pool->npages;
pool->npages = 0;
goto out;
}
/* find the last pages to include for requested number of pages. Split
* pool to begin and halve it to reduce search space. */
if (count <= pool->npages/2) {
i = 0;
list_for_each(p, &pool->list) {
if (++i == count)
break;
}
} else {
i = pool->npages + 1;
list_for_each_prev(p, &pool->list) {
if (--i == count)
break;
}
}
/* Cut 'count' number of pages from the pool */
list_cut_position(pages, &pool->list, p);
pool->npages -= count;
count = 0;
out:
spin_unlock_irqrestore(&pool->lock, irq_flags);
/* clear the pages coming from the pool if requested */
if (ttm_flags & TTM_PAGE_FLAG_ZERO_ALLOC) {
struct page *page;
list_for_each_entry(page, pages, lru) {
if (PageHighMem(page))
clear_highpage(page);
else
clear_page(page_address(page));
}
}
/* If pool didn't have enough pages allocate new one. */
if (count) {
gfp_t gfp_flags = pool->gfp_flags;
/* set zero flag for page allocation if required */
if (ttm_flags & TTM_PAGE_FLAG_ZERO_ALLOC)
gfp_flags |= __GFP_ZERO;
if (ttm_flags & TTM_PAGE_FLAG_NO_RETRY)
gfp_flags |= __GFP_RETRY_MAYFAIL;
/* ttm_alloc_new_pages doesn't reference pool so we can run
* multiple requests in parallel.
**/
r = ttm_alloc_new_pages(pages, gfp_flags, ttm_flags, cstate,
count, order);
}
return r;
}
/* Put all pages in pages list to correct pool to wait for reuse */
static void ttm_put_pages(struct page **pages, unsigned npages, int flags,
enum ttm_caching_state cstate)
{
struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate);
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate);
#endif
unsigned long irq_flags;
unsigned i;
if (pool == NULL) {
/* No pool for this memory type so free the pages */
i = 0;
while (i < npages) {
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
struct page *p = pages[i];
#endif
unsigned order = 0, j;
if (!pages[i]) {
++i;
continue;
}
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
if (!(flags & TTM_PAGE_FLAG_DMA32) &&
(npages - i) >= HPAGE_PMD_NR) {
for (j = 0; j < HPAGE_PMD_NR; ++j)
if (p++ != pages[i + j])
break;
if (j == HPAGE_PMD_NR)
order = HPAGE_PMD_ORDER;
}
#endif
if (page_count(pages[i]) != 1)
pr_err("Erroneous page count. Leaking pages.\n");
__free_pages(pages[i], order);
j = 1 << order;
while (j) {
pages[i++] = NULL;
--j;
}
}
return;
}
i = 0;
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
if (huge) {
unsigned max_size, n2free;
spin_lock_irqsave(&huge->lock, irq_flags);
while ((npages - i) >= HPAGE_PMD_NR) {
struct page *p = pages[i];
unsigned j;
if (!p)
break;
for (j = 0; j < HPAGE_PMD_NR; ++j)
if (p++ != pages[i + j])
break;
if (j != HPAGE_PMD_NR)
break;
list_add_tail(&pages[i]->lru, &huge->list);
for (j = 0; j < HPAGE_PMD_NR; ++j)
pages[i++] = NULL;
huge->npages++;
}
/* Check that we don't go over the pool limit */
max_size = _manager->options.max_size;
max_size /= HPAGE_PMD_NR;
if (huge->npages > max_size)
n2free = huge->npages - max_size;
else
n2free = 0;
spin_unlock_irqrestore(&huge->lock, irq_flags);
if (n2free)
ttm_page_pool_free(huge, n2free, false);
}
#endif
spin_lock_irqsave(&pool->lock, irq_flags);
while (i < npages) {
if (pages[i]) {
if (page_count(pages[i]) != 1)
pr_err("Erroneous page count. Leaking pages.\n");
list_add_tail(&pages[i]->lru, &pool->list);
pages[i] = NULL;
pool->npages++;
}
++i;
}
/* Check that we don't go over the pool limit */
npages = 0;
if (pool->npages > _manager->options.max_size) {
npages = pool->npages - _manager->options.max_size;
/* free at least NUM_PAGES_TO_ALLOC number of pages
* to reduce calls to set_memory_wb */
if (npages < NUM_PAGES_TO_ALLOC)
npages = NUM_PAGES_TO_ALLOC;
}
spin_unlock_irqrestore(&pool->lock, irq_flags);
if (npages)
ttm_page_pool_free(pool, npages, false);
}
/*
* On success pages list will hold count number of correctly
* cached pages.
*/
static int ttm_get_pages(struct page **pages, unsigned npages, int flags,
enum ttm_caching_state cstate)
{
struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate);
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate);
#endif
struct list_head plist;
struct page *p = NULL;
unsigned count, first;
int r;
/* No pool for cached pages */
if (pool == NULL) {
gfp_t gfp_flags = GFP_USER;
unsigned i;
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
unsigned j;
#endif
/* set zero flag for page allocation if required */
if (flags & TTM_PAGE_FLAG_ZERO_ALLOC)
gfp_flags |= __GFP_ZERO;
if (flags & TTM_PAGE_FLAG_NO_RETRY)
gfp_flags |= __GFP_RETRY_MAYFAIL;
if (flags & TTM_PAGE_FLAG_DMA32)
gfp_flags |= GFP_DMA32;
else
gfp_flags |= GFP_HIGHUSER;
i = 0;
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
if (!(gfp_flags & GFP_DMA32)) {
while (npages >= HPAGE_PMD_NR) {
gfp_t huge_flags = gfp_flags;
huge_flags |= GFP_TRANSHUGE_LIGHT | __GFP_NORETRY |
__GFP_KSWAPD_RECLAIM;
huge_flags &= ~__GFP_MOVABLE;
huge_flags &= ~__GFP_COMP;
p = alloc_pages(huge_flags, HPAGE_PMD_ORDER);
if (!p)
break;
for (j = 0; j < HPAGE_PMD_NR; ++j)
pages[i++] = p++;
npages -= HPAGE_PMD_NR;
}
}
#endif
first = i;
while (npages) {
p = alloc_page(gfp_flags);
if (!p) {
pr_debug("Unable to allocate page\n");
return -ENOMEM;
}
/* Swap the pages if we detect consecutive order */
if (i > first && pages[i - 1] == p - 1)
swap(p, pages[i - 1]);
pages[i++] = p;
--npages;
}
return 0;
}
count = 0;
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
if (huge && npages >= HPAGE_PMD_NR) {
INIT_LIST_HEAD(&plist);
ttm_page_pool_get_pages(huge, &plist, flags, cstate,
npages / HPAGE_PMD_NR,
HPAGE_PMD_ORDER);
list_for_each_entry(p, &plist, lru) {
unsigned j;
for (j = 0; j < HPAGE_PMD_NR; ++j)
pages[count++] = &p[j];
}
}
#endif
INIT_LIST_HEAD(&plist);
r = ttm_page_pool_get_pages(pool, &plist, flags, cstate,
npages - count, 0);
first = count;
list_for_each_entry(p, &plist, lru) {
struct page *tmp = p;
/* Swap the pages if we detect consecutive order */
if (count > first && pages[count - 1] == tmp - 1)
swap(tmp, pages[count - 1]);
pages[count++] = tmp;
}
if (r) {
/* If there is any pages in the list put them back to
* the pool.
*/
pr_debug("Failed to allocate extra pages for large request\n");
ttm_put_pages(pages, count, flags, cstate);
return r;
}
return 0;
}
static void ttm_page_pool_init_locked(struct ttm_page_pool *pool, gfp_t flags,
char *name, unsigned int order)
{
spin_lock_init(&pool->lock);
pool->fill_lock = false;
INIT_LIST_HEAD(&pool->list);
pool->npages = pool->nfrees = 0;
pool->gfp_flags = flags;
pool->name = name;
pool->order = order;
}
int ttm_page_alloc_init(struct ttm_mem_global *glob, unsigned max_pages)
{
int ret;
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
unsigned order = HPAGE_PMD_ORDER;
#else
unsigned order = 0;
#endif
WARN_ON(_manager);
pr_info("Initializing pool allocator\n");
_manager = kzalloc(sizeof(*_manager), GFP_KERNEL);
if (!_manager)
return -ENOMEM;
ttm_page_pool_init_locked(&_manager->wc_pool, GFP_HIGHUSER, "wc", 0);
ttm_page_pool_init_locked(&_manager->uc_pool, GFP_HIGHUSER, "uc", 0);
ttm_page_pool_init_locked(&_manager->wc_pool_dma32,
GFP_USER | GFP_DMA32, "wc dma", 0);
ttm_page_pool_init_locked(&_manager->uc_pool_dma32,
GFP_USER | GFP_DMA32, "uc dma", 0);
ttm_page_pool_init_locked(&_manager->wc_pool_huge,
(GFP_TRANSHUGE_LIGHT | __GFP_NORETRY |
__GFP_KSWAPD_RECLAIM) &
~(__GFP_MOVABLE | __GFP_COMP),
"wc huge", order);
ttm_page_pool_init_locked(&_manager->uc_pool_huge,
(GFP_TRANSHUGE_LIGHT | __GFP_NORETRY |
__GFP_KSWAPD_RECLAIM) &
~(__GFP_MOVABLE | __GFP_COMP)
, "uc huge", order);
_manager->options.max_size = max_pages;
_manager->options.small = SMALL_ALLOCATION;
_manager->options.alloc_size = NUM_PAGES_TO_ALLOC;
ret = kobject_init_and_add(&_manager->kobj, &ttm_pool_kobj_type,
&glob->kobj, "pool");
if (unlikely(ret != 0))
goto error;
ret = ttm_pool_mm_shrink_init(_manager);
if (unlikely(ret != 0))
goto error;
return 0;
error:
kobject_put(&_manager->kobj);
_manager = NULL;
return ret;
}
void ttm_page_alloc_fini(void)
{
int i;
pr_info("Finalizing pool allocator\n");
ttm_pool_mm_shrink_fini(_manager);
/* OK to use static buffer since global mutex is no longer used. */
for (i = 0; i < NUM_POOLS; ++i)
ttm_page_pool_free(&_manager->pools[i], FREE_ALL_PAGES, true);
kobject_put(&_manager->kobj);
_manager = NULL;
}
static void
ttm_pool_unpopulate_helper(struct ttm_tt *ttm, unsigned mem_count_update)
{
struct ttm_mem_global *mem_glob = ttm->bdev->glob->mem_glob;
unsigned i;
if (mem_count_update == 0)
goto put_pages;
for (i = 0; i < mem_count_update; ++i) {
if (!ttm->pages[i])
continue;
ttm_mem_global_free_page(mem_glob, ttm->pages[i], PAGE_SIZE);
}
put_pages:
ttm_put_pages(ttm->pages, ttm->num_pages, ttm->page_flags,
ttm->caching_state);
ttm->state = tt_unpopulated;
}
int ttm_pool_populate(struct ttm_tt *ttm, struct ttm_operation_ctx *ctx)
{
struct ttm_mem_global *mem_glob = ttm->bdev->glob->mem_glob;
unsigned i;
int ret;
if (ttm->state != tt_unpopulated)
return 0;
if (ttm_check_under_lowerlimit(mem_glob, ttm->num_pages, ctx))
return -ENOMEM;
ret = ttm_get_pages(ttm->pages, ttm->num_pages, ttm->page_flags,
ttm->caching_state);
if (unlikely(ret != 0)) {
ttm_pool_unpopulate_helper(ttm, 0);
return ret;
}
for (i = 0; i < ttm->num_pages; ++i) {
ret = ttm_mem_global_alloc_page(mem_glob, ttm->pages[i],
PAGE_SIZE, ctx);
if (unlikely(ret != 0)) {
ttm_pool_unpopulate_helper(ttm, i);
return -ENOMEM;
}
}
if (unlikely(ttm->page_flags & TTM_PAGE_FLAG_SWAPPED)) {
ret = ttm_tt_swapin(ttm);
if (unlikely(ret != 0)) {
ttm_pool_unpopulate(ttm);
return ret;
}
}
ttm->state = tt_unbound;
return 0;
}
EXPORT_SYMBOL(ttm_pool_populate);
void ttm_pool_unpopulate(struct ttm_tt *ttm)
{
ttm_pool_unpopulate_helper(ttm, ttm->num_pages);
}
EXPORT_SYMBOL(ttm_pool_unpopulate);
int ttm_populate_and_map_pages(struct device *dev, struct ttm_dma_tt *tt,
struct ttm_operation_ctx *ctx)
{
unsigned i, j;
int r;
r = ttm_pool_populate(&tt->ttm, ctx);
if (r)
return r;
for (i = 0; i < tt->ttm.num_pages; ++i) {
struct page *p = tt->ttm.pages[i];
size_t num_pages = 1;
for (j = i + 1; j < tt->ttm.num_pages; ++j) {
if (++p != tt->ttm.pages[j])
break;
++num_pages;
}
tt->dma_address[i] = dma_map_page(dev, tt->ttm.pages[i],
0, num_pages * PAGE_SIZE,
DMA_BIDIRECTIONAL);
if (dma_mapping_error(dev, tt->dma_address[i])) {
while (i--) {
dma_unmap_page(dev, tt->dma_address[i],
PAGE_SIZE, DMA_BIDIRECTIONAL);
tt->dma_address[i] = 0;
}
ttm_pool_unpopulate(&tt->ttm);
return -EFAULT;
}
for (j = 1; j < num_pages; ++j) {
tt->dma_address[i + 1] = tt->dma_address[i] + PAGE_SIZE;
++i;
}
}
return 0;
}
EXPORT_SYMBOL(ttm_populate_and_map_pages);
void ttm_unmap_and_unpopulate_pages(struct device *dev, struct ttm_dma_tt *tt)
{
unsigned i, j;
for (i = 0; i < tt->ttm.num_pages;) {
struct page *p = tt->ttm.pages[i];
size_t num_pages = 1;
if (!tt->dma_address[i] || !tt->ttm.pages[i]) {
++i;
continue;
}
for (j = i + 1; j < tt->ttm.num_pages; ++j) {
if (++p != tt->ttm.pages[j])
break;
++num_pages;
}
dma_unmap_page(dev, tt->dma_address[i], num_pages * PAGE_SIZE,
DMA_BIDIRECTIONAL);
i += num_pages;
}
ttm_pool_unpopulate(&tt->ttm);
}
EXPORT_SYMBOL(ttm_unmap_and_unpopulate_pages);
int ttm_page_alloc_debugfs(struct seq_file *m, void *data)
{
struct ttm_page_pool *p;
unsigned i;
char *h[] = {"pool", "refills", "pages freed", "size"};
if (!_manager) {
seq_printf(m, "No pool allocator running.\n");
return 0;
}
seq_printf(m, "%7s %12s %13s %8s\n",
h[0], h[1], h[2], h[3]);
for (i = 0; i < NUM_POOLS; ++i) {
p = &_manager->pools[i];
seq_printf(m, "%7s %12ld %13ld %8d\n",
p->name, p->nrefills,
p->nfrees, p->npages);
}
return 0;
}
EXPORT_SYMBOL(ttm_page_alloc_debugfs);
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1330_0 |
crossvul-cpp_data_good_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;
int num_descriptors;
size_t offset = offsetof(struct hid_descriptor, desc);
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;
}
if (hdesc->bLength < sizeof(struct hid_descriptor)) {
dbg_hid("hid descriptor is too short\n");
return -EINVAL;
}
hid->version = le16_to_cpu(hdesc->bcdHID);
hid->country = hdesc->bCountryCode;
num_descriptors = min_t(int, hdesc->bNumDescriptors,
(hdesc->bLength - offset) / sizeof(struct hid_class_descriptor));
for (n = 0; n < num_descriptors; 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/good_2914_0 |
crossvul-cpp_data_good_4791_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% M M AAA TTTTT L AAA BBBB %
% MM MM A A T L A A B B %
% M M M AAAAA T L AAAAA BBBB %
% M M A A T L A A B B %
% M M A A T LLLLL A A BBBB %
% %
% %
% Read MATLAB Image Format %
% %
% Software Design %
% Jaroslav Fojtik %
% 2001-2008 %
% %
% %
% Permission is hereby granted, free of charge, to any person obtaining a %
% copy of this software and associated documentation files ("ImageMagick"), %
% to deal in ImageMagick without restriction, including without limitation %
% the rights to use, copy, modify, merge, publish, distribute, sublicense, %
% and/or sell copies of ImageMagick, and to permit persons to whom the %
% ImageMagick is furnished to do so, subject to the following conditions: %
% %
% The above copyright notice and this permission notice shall be included in %
% all copies or substantial portions of ImageMagick. %
% %
% The software is provided "as is", without warranty of any kind, express or %
% implied, including but not limited to the warranties of merchantability, %
% fitness for a particular purpose and noninfringement. In no event shall %
% ImageMagick Studio be liable for any claim, damages or other liability, %
% whether in an action of contract, tort or otherwise, arising from, out of %
% or in connection with ImageMagick or the use or other dealings in %
% ImageMagick. %
% %
% Except as contained in this notice, the name of the ImageMagick Studio %
% shall not be used in advertising or otherwise to promote the sale, use or %
% other dealings in ImageMagick without prior written authorization from the %
% ImageMagick Studio. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace-private.h"
#include "magick/distort.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/transform.h"
#include "magick/utility-private.h"
#if defined(MAGICKCORE_ZLIB_DELEGATE)
#include "zlib.h"
#endif
/*
Forward declaration.
*/
static MagickBooleanType
WriteMATImage(const ImageInfo *,Image *);
/* Auto coloring method, sorry this creates some artefact inside data
MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black
MinReal+j*0 = white MaxReal+j*0 = black
MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black
*/
typedef struct
{
char identific[124];
unsigned short Version;
char EndianIndicator[2];
unsigned long DataType;
unsigned long ObjectSize;
unsigned long unknown1;
unsigned long unknown2;
unsigned short unknown5;
unsigned char StructureFlag;
unsigned char StructureClass;
unsigned long unknown3;
unsigned long unknown4;
unsigned long DimFlag;
unsigned long SizeX;
unsigned long SizeY;
unsigned short Flag1;
unsigned short NameFlag;
}
MATHeader;
static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
static const char *OsDesc=
#ifdef __WIN32__
"PCWIN";
#else
#ifdef __APPLE__
"MAC";
#else
"LNX86";
#endif
#endif
typedef enum
{
miINT8 = 1, /* 8 bit signed */
miUINT8, /* 8 bit unsigned */
miINT16, /* 16 bit signed */
miUINT16, /* 16 bit unsigned */
miINT32, /* 32 bit signed */
miUINT32, /* 32 bit unsigned */
miSINGLE, /* IEEE 754 single precision float */
miRESERVE1,
miDOUBLE, /* IEEE 754 double precision float */
miRESERVE2,
miRESERVE3,
miINT64, /* 64 bit signed */
miUINT64, /* 64 bit unsigned */
miMATRIX, /* MATLAB array */
miCOMPRESSED, /* Compressed Data */
miUTF8, /* Unicode UTF-8 Encoded Character Data */
miUTF16, /* Unicode UTF-16 Encoded Character Data */
miUTF32 /* Unicode UTF-32 Encoded Character Data */
} mat5_data_type;
typedef enum
{
mxCELL_CLASS=1, /* cell array */
mxSTRUCT_CLASS, /* structure */
mxOBJECT_CLASS, /* object */
mxCHAR_CLASS, /* character array */
mxSPARSE_CLASS, /* sparse array */
mxDOUBLE_CLASS, /* double precision array */
mxSINGLE_CLASS, /* single precision floating point */
mxINT8_CLASS, /* 8 bit signed integer */
mxUINT8_CLASS, /* 8 bit unsigned integer */
mxINT16_CLASS, /* 16 bit signed integer */
mxUINT16_CLASS, /* 16 bit unsigned integer */
mxINT32_CLASS, /* 32 bit signed integer */
mxUINT32_CLASS, /* 32 bit unsigned integer */
mxINT64_CLASS, /* 64 bit signed integer */
mxUINT64_CLASS, /* 64 bit unsigned integer */
mxFUNCTION_CLASS /* Function handle */
} arrayclasstype;
#define FLAG_COMPLEX 0x8
#define FLAG_GLOBAL 0x4
#define FLAG_LOGICAL 0x2
static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum};
static void InsertComplexDoubleRow(double *p, int y, Image * image, double MinVal,
double MaxVal)
{
ExceptionInfo
*exception;
double f;
int x;
register PixelPacket *q;
if (MinVal == 0)
MinVal = -1;
if (MaxVal == 0)
MaxVal = 1;
exception=(&image->exception);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
return;
for (x = 0; x < (ssize_t) image->columns; x++)
{
if (*p > 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q));
if (f + GetPixelRed(q) > QuantumRange)
SetPixelRed(q,QuantumRange);
else
SetPixelRed(q,GetPixelRed(q)+(int) f);
if ((int) f / 2.0 > GetPixelGreen(q))
{
SetPixelGreen(q,0);
SetPixelBlue(q,0);
}
else
{
SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelBlue(q));
}
}
if (*p < 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q));
if (f + GetPixelBlue(q) > QuantumRange)
SetPixelBlue(q,QuantumRange);
else
SetPixelBlue(q,GetPixelBlue(q)+(int) f);
if ((int) f / 2.0 > q->green)
{
SetPixelRed(q,0);
SetPixelGreen(q,0);
}
else
{
SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelRed(q));
}
}
p++;
q++;
}
if (!SyncAuthenticPixels(image,exception))
return;
return;
}
static void InsertComplexFloatRow(float *p, int y, Image * image, double MinVal,
double MaxVal)
{
ExceptionInfo
*exception;
double f;
int x;
register PixelPacket *q;
if (MinVal == 0)
MinVal = -1;
if (MaxVal == 0)
MaxVal = 1;
exception=(&image->exception);
q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
if (q == (PixelPacket *) NULL)
return;
for (x = 0; x < (ssize_t) image->columns; x++)
{
if (*p > 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q));
if (f + GetPixelRed(q) > QuantumRange)
SetPixelRed(q,QuantumRange);
else
SetPixelRed(q,GetPixelRed(q)+(int) f);
if ((int) f / 2.0 > GetPixelGreen(q))
{
SetPixelGreen(q,0);
SetPixelBlue(q,0);
}
else
{
SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelBlue(q));
}
}
if (*p < 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q));
if (f + GetPixelBlue(q) > QuantumRange)
SetPixelBlue(q,QuantumRange);
else
SetPixelBlue(q,GetPixelBlue(q)+(int) f);
if ((int) f / 2.0 > q->green)
{
SetPixelGreen(q,0);
SetPixelRed(q,0);
}
else
{
SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelRed(q));
}
}
p++;
q++;
}
if (!SyncAuthenticPixels(image,exception))
return;
return;
}
/************** READERS ******************/
/* This function reads one block of floats*/
static void ReadBlobFloatsLSB(Image * image, size_t len, float *data)
{
while (len >= 4)
{
*data++ = ReadBlobFloat(image);
len -= sizeof(float);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)
{
while (len >= 4)
{
*data++ = ReadBlobFloat(image);
len -= sizeof(float);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
/* This function reads one block of doubles*/
static void ReadBlobDoublesLSB(Image * image, size_t len, double *data)
{
while (len >= 8)
{
*data++ = ReadBlobDouble(image);
len -= sizeof(double);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)
{
while (len >= 8)
{
*data++ = ReadBlobDouble(image);
len -= sizeof(double);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
/* Calculate minimum and maximum from a given block of data */
static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)
{
MagickOffsetType filepos;
int i, x;
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
double *dblrow;
float *fltrow;
if (endian_indicator == LSBEndian)
{
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
}
else /* MI */
{
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
}
filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */
for (i = 0; i < SizeY; i++)
{
if (CellType==miDOUBLE)
{
ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);
dblrow = (double *)BImgBuff;
if (i == 0)
{
*Min = *Max = *dblrow;
}
for (x = 0; x < SizeX; x++)
{
if (*Min > *dblrow)
*Min = *dblrow;
if (*Max < *dblrow)
*Max = *dblrow;
dblrow++;
}
}
if (CellType==miSINGLE)
{
ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);
fltrow = (float *)BImgBuff;
if (i == 0)
{
*Min = *Max = *fltrow;
}
for (x = 0; x < (ssize_t) SizeX; x++)
{
if (*Min > *fltrow)
*Min = *fltrow;
if (*Max < *fltrow)
*Max = *fltrow;
fltrow++;
}
}
}
(void) SeekBlob(image, filepos, SEEK_SET);
}
static void FixSignedValues(PixelPacket *q, int y)
{
while(y-->0)
{
/* Please note that negative values will overflow
Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255>
<-1;-128> + 127+1 = <0; 127> */
SetPixelRed(q,GetPixelRed(q)+QuantumRange/2+1);
SetPixelGreen(q,GetPixelGreen(q)+QuantumRange/2+1);
SetPixelBlue(q,GetPixelBlue(q)+QuantumRange/2+1);
q++;
}
}
/** Fix whole row of logical/binary data. It means pack it. */
static void FixLogical(unsigned char *Buff,int ldblk)
{
unsigned char mask=128;
unsigned char *BuffL = Buff;
unsigned char val = 0;
while(ldblk-->0)
{
if(*Buff++ != 0)
val |= mask;
mask >>= 1;
if(mask==0)
{
*BuffL++ = val;
val = 0;
mask = 128;
}
}
*BuffL = val;
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
static voidpf AcquireZIPMemory(voidpf context,unsigned int items,
unsigned int size)
{
(void) context;
return((voidpf) AcquireQuantumMemory(items,size));
}
static void RelinquishZIPMemory(voidpf context,voidpf memory)
{
(void) context;
memory=RelinquishMagickMemory(memory);
}
#endif
#if defined(MAGICKCORE_ZLIB_DELEGATE)
/** This procedure decompreses an image block for a new MATLAB format. */
static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception)
{
Image *image2;
void *CacheBlock, *DecompressBlock;
z_stream zip_info;
FILE *mat_file;
size_t magick_size;
size_t extent;
int file;
int status;
if(clone_info==NULL) return NULL;
if(clone_info->file) /* Close file opened from previous transaction. */
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *));
if(CacheBlock==NULL) return NULL;
DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));
if(DecompressBlock==NULL)
{
RelinquishMagickMemory(CacheBlock);
return NULL;
}
mat_file=0;
file = AcquireUniqueFileResource(clone_info->filename);
if (file != -1)
mat_file = fdopen(file,"w");
if(!mat_file)
{
RelinquishMagickMemory(CacheBlock);
RelinquishMagickMemory(DecompressBlock);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Gannot create file stream for PS image");
return NULL;
}
zip_info.zalloc=AcquireZIPMemory;
zip_info.zfree=RelinquishZIPMemory;
zip_info.opaque = (voidpf) NULL;
inflateInit(&zip_info);
/* zip_info.next_out = 8*4;*/
zip_info.avail_in = 0;
zip_info.total_out = 0;
while(Size>0 && !EOFBlob(orig))
{
magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock);
zip_info.next_in = (Bytef *) CacheBlock;
zip_info.avail_in = (uInt) magick_size;
while(zip_info.avail_in>0)
{
zip_info.avail_out = 4096;
zip_info.next_out = (Bytef *) DecompressBlock;
status = inflate(&zip_info,Z_NO_FLUSH);
extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file);
(void) extent;
if(status == Z_STREAM_END) goto DblBreak;
}
Size -= magick_size;
}
DblBreak:
inflateEnd(&zip_info);
(void)fclose(mat_file);
RelinquishMagickMemory(CacheBlock);
RelinquishMagickMemory(DecompressBlock);
if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
if( (image2 = AcquireImage(clone_info))==NULL ) goto EraseFile;
status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
DeleteImageFromList(&image2);
EraseFile:
fclose(clone_info->file);
clone_info->file = NULL;
UnlinkFile:
(void) remove_utf8(clone_info->filename);
return NULL;
}
return image2;
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d M A T L A B i m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadMATImage() reads an MAT X image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadMATImage method is:
%
% Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: Method ReadMATImage returns a pointer to the image after
% reading. A null image is returned if there is a memory shortage or if
% the image cannot be read.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
PixelPacket *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
size_t Unknown6;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=CloneImageInfo(image_info);
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
Unknown6 = ReadBlobXXXLong(image2);
(void) Unknown6;
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
SetImageColorspace(image,GRAYColorspace);
image->type=GrayscaleType;
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
quantum_info=DestroyQuantumInfo(quantum_info);
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/good_4791_0 |
crossvul-cpp_data_bad_3209_1 | /*
* 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/bad_3209_1 |
crossvul-cpp_data_good_2684_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 "ip6.h"
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static const char tstr[] = "[|MOBILITY]";
/* Mobility header */
struct ip6_mobility {
uint8_t ip6m_pproto; /* following payload protocol (for PG) */
uint8_t ip6m_len; /* length in units of 8 octets */
uint8_t ip6m_type; /* message type */
uint8_t reserved; /* reserved */
uint16_t ip6m_cksum; /* sum of IPv6 pseudo-header and MH */
union {
uint16_t ip6m_un_data16[1]; /* type-specific field */
uint8_t ip6m_un_data8[2]; /* type-specific field */
} ip6m_dataun;
};
#define ip6m_data16 ip6m_dataun.ip6m_un_data16
#define ip6m_data8 ip6m_dataun.ip6m_un_data8
#define IP6M_MINLEN 8
/* http://www.iana.org/assignments/mobility-parameters/mobility-parameters.xhtml */
/* message type */
#define IP6M_BINDING_REQUEST 0 /* Binding Refresh Request */
#define IP6M_HOME_TEST_INIT 1 /* Home Test Init */
#define IP6M_CAREOF_TEST_INIT 2 /* Care-of Test Init */
#define IP6M_HOME_TEST 3 /* Home Test */
#define IP6M_CAREOF_TEST 4 /* Care-of Test */
#define IP6M_BINDING_UPDATE 5 /* Binding Update */
#define IP6M_BINDING_ACK 6 /* Binding Acknowledgement */
#define IP6M_BINDING_ERROR 7 /* Binding Error */
#define IP6M_MAX 7
static const struct tok ip6m_str[] = {
{ IP6M_BINDING_REQUEST, "BRR" },
{ IP6M_HOME_TEST_INIT, "HoTI" },
{ IP6M_CAREOF_TEST_INIT, "CoTI" },
{ IP6M_HOME_TEST, "HoT" },
{ IP6M_CAREOF_TEST, "CoT" },
{ IP6M_BINDING_UPDATE, "BU" },
{ IP6M_BINDING_ACK, "BA" },
{ IP6M_BINDING_ERROR, "BE" },
{ 0, NULL }
};
static const unsigned ip6m_hdrlen[IP6M_MAX + 1] = {
IP6M_MINLEN, /* IP6M_BINDING_REQUEST */
IP6M_MINLEN + 8, /* IP6M_HOME_TEST_INIT */
IP6M_MINLEN + 8, /* IP6M_CAREOF_TEST_INIT */
IP6M_MINLEN + 16, /* IP6M_HOME_TEST */
IP6M_MINLEN + 16, /* IP6M_CAREOF_TEST */
IP6M_MINLEN + 4, /* IP6M_BINDING_UPDATE */
IP6M_MINLEN + 4, /* IP6M_BINDING_ACK */
IP6M_MINLEN + 16, /* IP6M_BINDING_ERROR */
};
/* Mobility Header Options */
#define IP6MOPT_MINLEN 2
#define IP6MOPT_PAD1 0x0 /* Pad1 */
#define IP6MOPT_PADN 0x1 /* PadN */
#define IP6MOPT_REFRESH 0x2 /* Binding Refresh Advice */
#define IP6MOPT_REFRESH_MINLEN 4
#define IP6MOPT_ALTCOA 0x3 /* Alternate Care-of Address */
#define IP6MOPT_ALTCOA_MINLEN 18
#define IP6MOPT_NONCEID 0x4 /* Nonce Indices */
#define IP6MOPT_NONCEID_MINLEN 6
#define IP6MOPT_AUTH 0x5 /* Binding Authorization Data */
#define IP6MOPT_AUTH_MINLEN 12
static int
mobility_opt_print(netdissect_options *ndo,
const u_char *bp, const unsigned len)
{
unsigned i, optlen;
for (i = 0; i < len; i += optlen) {
ND_TCHECK(bp[i]);
if (bp[i] == IP6MOPT_PAD1)
optlen = 1;
else {
if (i + 1 < len) {
ND_TCHECK(bp[i + 1]);
optlen = bp[i + 1] + 2;
}
else
goto trunc;
}
if (i + optlen > len)
goto trunc;
ND_TCHECK(bp[i + optlen]);
switch (bp[i]) {
case IP6MOPT_PAD1:
ND_PRINT((ndo, "(pad1)"));
break;
case IP6MOPT_PADN:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(padn: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(padn)"));
break;
case IP6MOPT_REFRESH:
if (len - i < IP6MOPT_REFRESH_MINLEN) {
ND_PRINT((ndo, "(refresh: trunc)"));
goto trunc;
}
/* units of 4 secs */
ND_PRINT((ndo, "(refresh: %u)",
EXTRACT_16BITS(&bp[i+2]) << 2));
break;
case IP6MOPT_ALTCOA:
if (len - i < IP6MOPT_ALTCOA_MINLEN) {
ND_PRINT((ndo, "(altcoa: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2])));
break;
case IP6MOPT_NONCEID:
if (len - i < IP6MOPT_NONCEID_MINLEN) {
ND_PRINT((ndo, "(ni: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)",
EXTRACT_16BITS(&bp[i+2]),
EXTRACT_16BITS(&bp[i+4])));
break;
case IP6MOPT_AUTH:
if (len - i < IP6MOPT_AUTH_MINLEN) {
ND_PRINT((ndo, "(auth: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(auth)"));
break;
default:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i]));
goto trunc;
}
ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1]));
break;
}
}
return 0;
trunc:
return 1;
}
/*
* Mobility Header
*/
int
mobility_print(netdissect_options *ndo,
const u_char *bp, const u_char *bp2 _U_)
{
const struct ip6_mobility *mh;
const u_char *ep;
unsigned mhlen, hlen;
uint8_t type;
mh = (const struct ip6_mobility *)bp;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if (!ND_TTEST(mh->ip6m_len)) {
/*
* There's not enough captured data to include the
* mobility header length.
*
* Our caller expects us to return the length, however,
* so return a value that will run to the end of the
* captured data.
*
* XXX - "ip6_print()" doesn't do anything with the
* returned length, however, as it breaks out of the
* header-processing loop.
*/
mhlen = ep - bp;
goto trunc;
}
mhlen = (mh->ip6m_len + 1) << 3;
/* XXX ip6m_cksum */
ND_TCHECK(mh->ip6m_type);
type = mh->ip6m_type;
if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) {
ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type));
goto trunc;
}
ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type)));
switch (type) {
case IP6M_BINDING_REQUEST:
hlen = IP6M_MINLEN;
break;
case IP6M_HOME_TEST_INIT:
case IP6M_CAREOF_TEST_INIT:
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_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_2684_0 |
crossvul-cpp_data_good_1297_0 | /*
* card-setcos.c: Support for PKI cards by Setec
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
* Copyright (C) 2005 Antti Tapaninen <aet@cc.hut.fi>
* Copyright (C) 2005 Zetes
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
#define _FINEID_BROKEN_SELECT_FLAG 1
static const struct sc_atr_table setcos_atrs[] = {
/* some Nokia branded SC */
{ "3B:1F:11:00:67:80:42:46:49:53:45:10:52:66:FF:81:90:00", NULL, NULL, SC_CARD_TYPE_SETCOS_GENERIC, 0, NULL },
/* RSA SecurID 3100 */
{ "3B:9F:94:40:1E:00:67:16:43:46:49:53:45:10:52:66:FF:81:90:00", NULL, NULL, SC_CARD_TYPE_SETCOS_PKI, 0, NULL },
/* FINEID 1016 (SetCOS 4.3.1B3/PKCS#15, VRK) */
{ "3b:9f:94:40:1e:00:67:00:43:46:49:53:45:10:52:66:ff:81:90:00", "ff:ff:ff:ff:ff:ff:ff:00:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID, SC_CARD_FLAG_RNG, NULL },
/* FINEID 2032 (EIDApplet/7816-15, VRK test) */
{ "3b:6b:00:ff:80:62:00:a2:56:46:69:6e:45:49:44", "ff:ff:00:ff:ff:ff:00:ff:ff:ff:ff:ff:ff:ff:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL },
/* FINEID 2132 (EIDApplet/7816-15, 3rdparty test) */
{ "3b:64:00:ff:80:62:00:a2", "ff:ff:00:ff:ff:ff:00:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL },
/* FINEID 2064 (EIDApplet/7816-15, VRK) */
{ "3b:7b:00:00:00:80:62:00:51:56:46:69:6e:45:49:44", "ff:ff:00:ff:ff:ff:ff:f0:ff:ff:ff:ff:ff:ff:ff:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL },
/* FINEID 2164 (EIDApplet/7816-15, 3rdparty) */
{ "3b:64:00:00:80:62:00:51", "ff:ff:ff:ff:ff:ff:f0:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL },
/* FINEID 2264 (EIDApplet/7816-15, OPK/EMV/AVANT) */
{ "3b:6e:00:00:00:62:00:00:57:41:56:41:4e:54:10:81:90:00", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL },
{ "3b:7b:94:00:00:80:62:11:51:56:46:69:6e:45:49:44", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL },
/* FINEID cards 1.3.2011 with Samsung chips (round connector) that supports 2048 bit keys. */
{ "3b:7b:94:00:00:80:62:12:51:56:46:69:6e:45:49:44", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2_2048, 0, NULL },
/* FINEID card for organisations, chip unknown. */
{ "3b:7b:18:00:00:80:62:01:54:56:46:69:6e:45:49:44", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, _FINEID_BROKEN_SELECT_FLAG, NULL },
/* Swedish NIDEL card */
{ "3b:9f:94:80:1f:c3:00:68:10:44:05:01:46:49:53:45:31:c8:07:90:00:18", NULL, NULL, SC_CARD_TYPE_SETCOS_NIDEL, 0, NULL },
/* Setcos 4.4.1 */
{ "3b:9f:94:80:1f:c3:00:68:11:44:05:01:46:49:53:45:31:c8:00:00:00:00", "ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:00:00:00:00", NULL, SC_CARD_TYPE_SETCOS_44, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
#define SETCOS_IS_EID_APPLET(card) ((card)->type == SC_CARD_TYPE_SETCOS_EID_V2_0 || (card)->type == SC_CARD_TYPE_SETCOS_EID_V2_1)
/* Setcos 4.4 Life Cycle Status Integer */
#define SETEC_LCSI_CREATE 0x01
#define SETEC_LCSI_INIT 0x03
#define SETEC_LCSI_ACTIVATED 0x07
#define SETEC_LCSI_DEACTIVATE 0x06
#define SETEC_LCSI_TEMINATE 0x0F /* MF only */
static struct sc_card_operations setcos_ops;
static struct sc_card_driver setcos_drv = {
"Setec cards",
"setcos",
&setcos_ops,
NULL, 0, NULL
};
static int match_hist_bytes(sc_card_t *card, const char *str, size_t len)
{
const char *src = (const char *) card->reader->atr_info.hist_bytes;
size_t srclen = card->reader->atr_info.hist_bytes_len;
size_t offset = 0;
if (len == 0)
len = strlen(str);
if (srclen < len)
return 0;
while (srclen - offset > len) {
if (memcmp(src + offset, str, len) == 0) {
return 1;
}
offset++;
}
return 0;
}
static int setcos_match_card(sc_card_t *card)
{
sc_apdu_t apdu;
u8 buf[6];
int i;
i = _sc_match_atr(card, setcos_atrs, &card->type);
if (i < 0) {
/* Unknown card, but has the FinEID application for sure */
if (match_hist_bytes(card, "FinEID", 0)) {
card->type = SC_CARD_TYPE_SETCOS_FINEID_V2_2048;
return 1;
}
if (match_hist_bytes(card, "FISE", 0)) {
card->type = SC_CARD_TYPE_SETCOS_GENERIC;
return 1;
}
/* Check if it's a EID2.x applet by reading the version info */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xCA, 0xDF, 0x30);
apdu.cla = 0x00;
apdu.resp = buf;
apdu.resplen = 5;
apdu.le = 5;
i = sc_transmit_apdu(card, &apdu);
if (i == 0 && apdu.sw1 == 0x90 && apdu.sw2 == 0x00 && apdu.resplen == 5) {
if (memcmp(buf, "v2.0", 4) == 0)
card->type = SC_CARD_TYPE_SETCOS_EID_V2_0;
else if (memcmp(buf, "v2.1", 4) == 0)
card->type = SC_CARD_TYPE_SETCOS_EID_V2_1;
else {
buf[sizeof(buf) - 1] = '\0';
sc_log(card->ctx, "SetCOS EID applet %s is not supported", (char *) buf);
return 0;
}
return 1;
}
return 0;
}
card->flags = setcos_atrs[i].flags;
return 1;
}
static int select_pkcs15_app(sc_card_t * card)
{
sc_path_t app;
int r;
/* Regular PKCS#15 AID */
sc_format_path("A000000063504B43532D3135", &app);
app.type = SC_PATH_TYPE_DF_NAME;
r = sc_select_file(card, &app, NULL);
return r;
}
static int setcos_init(sc_card_t *card)
{
card->name = "SetCOS";
/* Handle unknown or forced cards */
if (card->type < 0) {
card->type = SC_CARD_TYPE_SETCOS_GENERIC;
}
switch (card->type) {
case SC_CARD_TYPE_SETCOS_FINEID:
case SC_CARD_TYPE_SETCOS_FINEID_V2_2048:
case SC_CARD_TYPE_SETCOS_NIDEL:
card->cla = 0x00;
select_pkcs15_app(card);
if (card->flags & SC_CARD_FLAG_RNG)
card->caps |= SC_CARD_CAP_RNG;
break;
case SC_CARD_TYPE_SETCOS_44:
case SC_CARD_TYPE_SETCOS_EID_V2_0:
case SC_CARD_TYPE_SETCOS_EID_V2_1:
card->cla = 0x00;
card->caps |= SC_CARD_CAP_USE_FCI_AC;
card->caps |= SC_CARD_CAP_RNG;
card->caps |= SC_CARD_CAP_APDU_EXT;
break;
default:
/* XXX: Get SetCOS version */
card->cla = 0x80; /* SetCOS 4.3.x */
/* State that we have an RNG */
card->caps |= SC_CARD_CAP_RNG;
break;
}
switch (card->type) {
case SC_CARD_TYPE_SETCOS_PKI:
case SC_CARD_TYPE_SETCOS_FINEID_V2_2048:
{
unsigned long flags;
flags = SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_PAD_PKCS1;
flags |= SC_ALGORITHM_RSA_HASH_NONE | SC_ALGORITHM_RSA_HASH_SHA1;
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
break;
case SC_CARD_TYPE_SETCOS_44:
case SC_CARD_TYPE_SETCOS_NIDEL:
case SC_CARD_TYPE_SETCOS_EID_V2_0:
case SC_CARD_TYPE_SETCOS_EID_V2_1:
{
unsigned long flags;
flags = SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_PAD_PKCS1;
flags |= SC_ALGORITHM_RSA_HASH_NONE | SC_ALGORITHM_RSA_HASH_SHA1;
flags |= SC_ALGORITHM_ONBOARD_KEY_GEN;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
break;
}
return 0;
}
static const struct sc_card_operations *iso_ops = NULL;
static int setcos_construct_fci_44(sc_card_t *card, const sc_file_t *file, u8 *out, size_t *outlen)
{
u8 *p = out;
u8 buf[64];
const u8 *pin_key_info;
int len;
/* Command */
*p++ = 0x6F;
p++;
/* Size (set to 0 for keys/PINs on a Java card) */
if (SETCOS_IS_EID_APPLET(card) &&
(file->type == SC_FILE_TYPE_INTERNAL_EF ||
(file->type == SC_FILE_TYPE_WORKING_EF && file->ef_structure == 0x22)))
buf[0] = buf[1] = 0x00;
else {
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
}
sc_asn1_put_tag(0x81, buf, 2, p, *outlen - (p - out), &p);
/* Type */
if (file->type_attr_len) {
memcpy(buf, file->type_attr, file->type_attr_len);
sc_asn1_put_tag(0x82, buf, file->type_attr_len, p, *outlen - (p - out), &p);
} else {
u8 bLen = 1;
buf[0] = file->shareable ? 0x40 : 0;
switch (file->type) {
case SC_FILE_TYPE_INTERNAL_EF: /* RSA keyfile */
buf[0] = 0x11;
break;
case SC_FILE_TYPE_WORKING_EF:
if (file->ef_structure == 0x22) { /* pin-file */
buf[0] = 0x0A; /* EF linear fixed EF for ISF keys */
if (SETCOS_IS_EID_APPLET(card))
bLen = 1;
else {
/* Setcos V4.4 */
bLen = 5;
buf[1] = 0x41; /* fixed */
buf[2] = file->record_length >> 8; /* 2 byte record length */
buf[3] = file->record_length & 0xFF;
buf[4] = file->size / file->record_length; /* record count */
}
} else {
buf[0] |= file->ef_structure & 7; /* set file-type, only for EF, not for DF objects */
}
break;
case SC_FILE_TYPE_DF:
buf[0] = 0x38;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
sc_asn1_put_tag(0x82, buf, bLen, p, *outlen - (p - out), &p);
}
/* File ID */
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p);
/* DF name */
if (file->type == SC_FILE_TYPE_DF) {
if (file->name[0] != 0)
sc_asn1_put_tag(0x84, (u8 *) file->name, file->namelen, p, *outlen - (p - out), &p);
else { /* Name required -> take the FID if not specified */
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x84, buf, 2, p, *outlen - (p - out), &p);
}
}
/* Security Attributes */
memcpy(buf, file->sec_attr, file->sec_attr_len);
sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p);
/* Life cycle status */
if (file->prop_attr_len) {
memcpy(buf, file->prop_attr, file->prop_attr_len);
sc_asn1_put_tag(0x8A, buf, file->prop_attr_len, p, *outlen - (p - out), &p);
}
/* PIN definitions */
if (file->type == SC_FILE_TYPE_DF) {
if (card->type == SC_CARD_TYPE_SETCOS_EID_V2_1) {
pin_key_info = (const u8*)"\xC1\x04\x81\x82\x83\x84";
len = 6;
}
else if (card->type == SC_CARD_TYPE_SETCOS_EID_V2_0) {
pin_key_info = (const u8*)"\xC1\x04\x81\x82"; /* Max 2 PINs supported */
len = 4;
}
else {
/* Pin/key info: define 4 pins, no keys */
if(file->path.len == 2)
pin_key_info = (const u8*)"\xC1\x04\x81\x82\x83\x84\xC2\x00"; /* root-MF: use local pin-file */
else
pin_key_info = (const u8 *)"\xC1\x04\x01\x02\x03\x04\xC2\x00"; /* sub-DF: use parent pin-file in root-MF */
len = 8;
}
sc_asn1_put_tag(0xA5, pin_key_info, len, p, *outlen - (p - out), &p);
}
/* Length */
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int setcos_construct_fci(sc_card_t *card, const sc_file_t *file, u8 *out, size_t *outlen)
{
if (card->type == SC_CARD_TYPE_SETCOS_44 ||
card->type == SC_CARD_TYPE_SETCOS_NIDEL ||
SETCOS_IS_EID_APPLET(card))
return setcos_construct_fci_44(card, file, out, outlen);
else
return iso_ops->construct_fci(card, file, out, outlen);
}
static u8 acl_to_byte(const sc_acl_entry_t *e)
{
switch (e->method) {
case SC_AC_NONE:
return 0x00;
case SC_AC_CHV:
switch (e->key_ref) {
case 1:
return 0x01;
break;
case 2:
return 0x02;
break;
default:
return 0x00;
}
break;
case SC_AC_TERM:
return 0x04;
case SC_AC_NEVER:
return 0x0F;
}
return 0x00;
}
static unsigned int acl_to_byte_44(const struct sc_acl_entry *e, u8* p_bNumber)
{
/* Handle special fixed values */
if (e == (sc_acl_entry_t *) 1) /* SC_AC_NEVER */
return SC_AC_NEVER;
else if ((e == (sc_acl_entry_t *) 2) || /* SC_AC_NONE */
(e == (sc_acl_entry_t *) 3) || /* SC_AC_UNKNOWN */
(e == (sc_acl_entry_t *) 0))
return SC_AC_NONE;
/* Handle standard values */
*p_bNumber = e->key_ref;
return(e->method);
}
/* If pin is present in the pins list, return it's index.
* If it's not yet present, add it to the list and return the index. */
static int setcos_pin_index_44(int *pins, int len, int pin)
{
int i;
for (i = 0; i < len; i++) {
if (pins[i] == pin)
return i;
if (pins[i] == -1) {
pins[i] = pin;
return i;
}
}
assert(i != len); /* Too much PINs, shouldn't happen */
return 0;
}
/* The ACs are always for the SETEC_LCSI_ACTIVATED state, even if
* we have to create the file in the SC_FILE_STATUS_INITIALISATION state. */
static int setcos_create_file_44(sc_card_t *card, sc_file_t *file)
{
const u8 bFileStatus = file->status == SC_FILE_STATUS_CREATION ?
SETEC_LCSI_CREATE : SETEC_LCSI_ACTIVATED;
u8 bCommands_always = 0;
int pins[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
u8 bCommands_pin[sizeof(pins)/sizeof(pins[0])]; /* both 7 entries big */
u8 bCommands_key = 0;
u8 bNumber = 0;
u8 bKeyNumber = 0;
unsigned int bMethod = 0;
/* -1 means RFU */
const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/
SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1};
const int ef_idx[8] = { /* note: SC_AC_OP_SELECT to be ignored, actually RFU */
SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
-1, SC_AC_OP_ERASE, -1};
const int efi_idx[8] = { /* internal EF used for RSA keys */
SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
-1, SC_AC_OP_ERASE, -1};
/* Set file creation status */
sc_file_set_prop_attr(file, &bFileStatus, 1);
/* Build ACI from local structure = get AC for each operation group */
if (file->sec_attr_len == 0) {
const int* p_idx;
int i;
int len = 0;
u8 bBuf[64];
/* Get specific operation groups for specified file-type */
switch (file->type){
case SC_FILE_TYPE_DF: /* DF */
p_idx = df_idx;
break;
case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */
p_idx = efi_idx;
break;
default: /* SC_FILE_TYPE_WORKING_EF */
p_idx = ef_idx;
break;
}
/* Get enabled commands + required Keys/Pins */
memset(bCommands_pin, 0, sizeof(bCommands_pin));
for (i = 7; i >= 0; i--) { /* for each AC Setcos operation */
bCommands_always <<= 1;
bCommands_key <<= 1;
if (p_idx[i] == -1) /* -1 means that bit is RFU -> set to 0 */
continue;
bMethod = acl_to_byte_44(file->acl[ p_idx[i] ], &bNumber);
/* Convert to OpenSc-index, convert to pin/key number */
switch(bMethod){
case SC_AC_NONE: /* always allowed */
bCommands_always |= 1;
break;
case SC_AC_CHV: /* pin */
if ((bNumber & 0x7F) == 0 || (bNumber & 0x7F) > 7) {
sc_log(card->ctx, "SetCOS 4.4 PIN refs can only be 1..7\n");
return SC_ERROR_INVALID_ARGUMENTS;
}
bCommands_pin[setcos_pin_index_44(pins, sizeof(pins), (int) bNumber)] |= 1 << i;
break;
case SC_AC_TERM: /* key */
bKeyNumber = bNumber; /* There should be only 1 key */
bCommands_key |= 1;
break;
}
}
/* Add the commands that are always allowed */
if (bCommands_always) {
bBuf[len++] = 1;
bBuf[len++] = bCommands_always;
}
/* Add commands that require pins */
for (i = 0; i < (int)sizeof(bCommands_pin) && pins[i] != -1; i++) {
bBuf[len++] = 2;
bBuf[len++] = bCommands_pin[i];
if (SETCOS_IS_EID_APPLET(card))
bBuf[len++] = pins[i]; /* pin ref */
else
bBuf[len++] = pins[i] & 0x07; /* pin ref */
}
/* Add commands that require the key */
if (bCommands_key) {
bBuf[len++] = 2 | 0x20; /* indicate keyNumber present */
bBuf[len++] = bCommands_key;
bBuf[len++] = bKeyNumber;
}
/* RSA signing/decryption requires AC adaptive coding, can't be put
in AC simple coding. Only implemented for pins, not for a key. */
if ( (file->type == SC_FILE_TYPE_INTERNAL_EF) &&
(acl_to_byte_44(file->acl[SC_AC_OP_CRYPTO], &bNumber) == SC_AC_CHV) ) {
bBuf[len++] = 0x83;
bBuf[len++] = 0x01;
bBuf[len++] = 0x2A; /* INS byte for the sign/decrypt APDU */
bBuf[len++] = bNumber & 0x07; /* pin ref */
}
sc_file_set_sec_attr(file, bBuf, len);
}
return iso_ops->create_file(card, file);
}
static int setcos_create_file(sc_card_t *card, sc_file_t *file)
{
if (card->type == SC_CARD_TYPE_SETCOS_44 || SETCOS_IS_EID_APPLET(card))
return setcos_create_file_44(card, file);
if (file->prop_attr_len == 0)
sc_file_set_prop_attr(file, (const u8 *) "\x03\x00\x00", 3);
if (file->sec_attr_len == 0) {
int idx[6], i;
u8 buf[6];
if (file->type == SC_FILE_TYPE_DF) {
const int df_idx[6] = {
SC_AC_OP_SELECT, SC_AC_OP_LOCK, SC_AC_OP_DELETE,
SC_AC_OP_CREATE, SC_AC_OP_REHABILITATE,
SC_AC_OP_INVALIDATE
};
for (i = 0; i < 6; i++)
idx[i] = df_idx[i];
} else {
const int ef_idx[6] = {
SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE,
SC_AC_OP_ERASE, SC_AC_OP_REHABILITATE,
SC_AC_OP_INVALIDATE
};
for (i = 0; i < 6; i++)
idx[i] = ef_idx[i];
}
for (i = 0; i < 6; i++) {
const struct sc_acl_entry *entry;
entry = sc_file_get_acl_entry(file, idx[i]);
buf[i] = acl_to_byte(entry);
}
sc_file_set_sec_attr(file, buf, 6);
}
return iso_ops->create_file(card, file);
}
static int setcos_set_security_env2(sc_card_t *card,
const sc_security_env_t *env, int se_num)
{
sc_apdu_t apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 *p;
int r, locked = 0;
assert(card != NULL && env != NULL);
if (card->type == SC_CARD_TYPE_SETCOS_44 ||
card->type == SC_CARD_TYPE_SETCOS_NIDEL ||
SETCOS_IS_EID_APPLET(card)) {
if (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) {
sc_log(card->ctx, "symmetric keyref not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
if (se_num > 0) {
sc_log(card->ctx, "restore security environment not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0, 0);
switch (env->operation) {
case SC_SEC_OPERATION_DECIPHER:
/* Should be 0x81 */
apdu.p1 = 0x41;
apdu.p2 = 0xB8;
break;
case SC_SEC_OPERATION_SIGN:
/* Should be 0x41 */
apdu.p1 = ((card->type == SC_CARD_TYPE_SETCOS_FINEID_V2) ||
(card->type == SC_CARD_TYPE_SETCOS_FINEID_V2_2048) ||
(card->type == SC_CARD_TYPE_SETCOS_44) ||
(card->type == SC_CARD_TYPE_SETCOS_NIDEL) ||
SETCOS_IS_EID_APPLET(card)) ? 0x41 : 0x81;
apdu.p2 = 0xB6;
break;
default:
return SC_ERROR_INVALID_ARGUMENTS;
}
apdu.le = 0;
p = sbuf;
if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) {
*p++ = 0x80; /* algorithm reference */
*p++ = 0x01;
*p++ = env->algorithm_ref & 0xFF;
}
if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) {
*p++ = 0x81;
*p++ = env->file_ref.len;
memcpy(p, env->file_ref.value, env->file_ref.len);
p += env->file_ref.len;
}
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT &&
!(card->type == SC_CARD_TYPE_SETCOS_NIDEL ||
card->type == SC_CARD_TYPE_SETCOS_FINEID_V2_2048)) {
if (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC)
*p++ = 0x83;
else
*p++ = 0x84;
*p++ = env->key_ref_len;
memcpy(p, env->key_ref, env->key_ref_len);
p += env->key_ref_len;
}
r = p - sbuf;
apdu.lc = r;
apdu.datalen = r;
apdu.data = sbuf;
apdu.resplen = 0;
if (se_num > 0) {
r = sc_lock(card);
LOG_TEST_RET(card->ctx, r, "sc_lock() failed");
locked = 1;
}
if (apdu.datalen != 0) {
r = sc_transmit_apdu(card, &apdu);
if (r) {
sc_log(card->ctx,
"%s: APDU transmit failed", sc_strerror(r));
goto err;
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r) {
sc_log(card->ctx,
"%s: Card returned error", sc_strerror(r));
goto err;
}
}
if (se_num <= 0)
return 0;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num);
r = sc_transmit_apdu(card, &apdu);
sc_unlock(card);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
err:
if (locked)
sc_unlock(card);
return r;
}
static int setcos_set_security_env(sc_card_t *card,
const sc_security_env_t *env, int se_num)
{
if (env->flags & SC_SEC_ENV_ALG_PRESENT) {
sc_security_env_t tmp;
tmp = *env;
tmp.flags &= ~SC_SEC_ENV_ALG_PRESENT;
tmp.flags |= SC_SEC_ENV_ALG_REF_PRESENT;
if (tmp.algorithm != SC_ALGORITHM_RSA) {
sc_log(card->ctx, "Only RSA algorithm supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
switch (card->type) {
case SC_CARD_TYPE_SETCOS_PKI:
case SC_CARD_TYPE_SETCOS_FINEID:
case SC_CARD_TYPE_SETCOS_FINEID_V2_2048:
case SC_CARD_TYPE_SETCOS_NIDEL:
case SC_CARD_TYPE_SETCOS_44:
case SC_CARD_TYPE_SETCOS_EID_V2_0:
case SC_CARD_TYPE_SETCOS_EID_V2_1:
break;
default:
sc_log(card->ctx, "Card does not support RSA.\n");
return SC_ERROR_NOT_SUPPORTED;
break;
}
tmp.algorithm_ref = 0x00;
/* potential FIXME: return an error, if an unsupported
* pad or hash was requested, although this shouldn't happen.
*/
if (env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1)
tmp.algorithm_ref = 0x02;
if (tmp.algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1)
tmp.algorithm_ref |= 0x10;
return setcos_set_security_env2(card, &tmp, se_num);
}
return setcos_set_security_env2(card, env, se_num);
}
static void add_acl_entry(sc_file_t *file, int op, u8 byte)
{
unsigned int method, key_ref = SC_AC_KEY_REF_NONE;
switch (byte >> 4) {
case 0:
method = SC_AC_NONE;
break;
case 1:
method = SC_AC_CHV;
key_ref = 1;
break;
case 2:
method = SC_AC_CHV;
key_ref = 2;
break;
case 4:
method = SC_AC_TERM;
break;
case 15:
method = SC_AC_NEVER;
break;
default:
method = SC_AC_UNKNOWN;
break;
}
sc_file_add_acl_entry(file, op, method, key_ref);
}
static void parse_sec_attr(sc_file_t *file, const u8 * buf, size_t len)
{
int i;
int idx[6];
if (len < 6)
return;
if (file->type == SC_FILE_TYPE_DF) {
const int df_idx[6] = {
SC_AC_OP_SELECT, SC_AC_OP_LOCK, SC_AC_OP_DELETE,
SC_AC_OP_CREATE, SC_AC_OP_REHABILITATE,
SC_AC_OP_INVALIDATE
};
for (i = 0; i < 6; i++)
idx[i] = df_idx[i];
} else {
const int ef_idx[6] = {
SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE,
SC_AC_OP_ERASE, SC_AC_OP_REHABILITATE,
SC_AC_OP_INVALIDATE
};
for (i = 0; i < 6; i++)
idx[i] = ef_idx[i];
}
for (i = 0; i < 6; i++)
add_acl_entry(file, idx[i], buf[i]);
}
static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len)
{
/* OpenSc Operation values for each command operation-type */
const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/
SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1};
const int ef_idx[8] = {
SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
-1, SC_AC_OP_ERASE, -1};
const int efi_idx[8] = { /* internal EF used for RSA keys */
SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
-1, SC_AC_OP_ERASE, -1};
u8 bValue;
int i;
int iKeyRef = 0;
int iMethod;
int iPinCount;
int iOffset = 0;
int iOperation;
const int* p_idx;
/* Check all sub-AC definitions within the total AC */
while (len > 1) { /* minimum length = 2 */
size_t iACLen = buf[iOffset] & 0x0F;
if (iACLen > len)
break;
iMethod = SC_AC_NONE; /* default no authentication required */
if (buf[iOffset] & 0X80) { /* AC in adaptive coding */
/* Evaluates only the command-byte, not the optional P1/P2/Option bytes */
size_t iParmLen = 1; /* command-byte is always present */
size_t iKeyLen = 0; /* Encryption key is optional */
if (buf[iOffset] & 0x20) iKeyLen++;
if (buf[iOffset+1] & 0x40) iParmLen++;
if (buf[iOffset+1] & 0x20) iParmLen++;
if (buf[iOffset+1] & 0x10) iParmLen++;
if (buf[iOffset+1] & 0x08) iParmLen++;
/* Get KeyNumber if available */
if(iKeyLen) {
int iSC;
if (len < 1+(size_t)iACLen)
break;
iSC = buf[iOffset+iACLen];
switch( (iSC>>5) & 0x03 ){
case 0:
iMethod = SC_AC_TERM; /* key authentication */
break;
case 1:
iMethod = SC_AC_AUT; /* key authentication */
break;
case 2:
case 3:
iMethod = SC_AC_PRO; /* secure messaging */
break;
}
iKeyRef = iSC & 0x1F; /* get key number */
}
/* Get PinNumber if available */
if (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */
if (len < 1+1+1+(size_t)iParmLen)
break;
iKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */
iMethod = SC_AC_CHV;
}
/* Convert SETCOS command to OpenSC command group */
if (len < 1+2)
break;
switch(buf[iOffset+2]){
case 0x2A: /* crypto operation */
iOperation = SC_AC_OP_CRYPTO;
break;
case 0x46: /* key-generation operation */
iOperation = SC_AC_OP_UPDATE;
break;
default:
iOperation = SC_AC_OP_SELECT;
break;
}
sc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef);
}
else { /* AC in simple coding */
/* Initial AC is treated as an operational AC */
/* Get specific Cmd groups for specified file-type */
switch (file->type) {
case SC_FILE_TYPE_DF: /* DF */
p_idx = df_idx;
break;
case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */
p_idx = efi_idx;
break;
default: /* EF */
p_idx = ef_idx;
break;
}
/* Encryption key present ? */
iPinCount = iACLen > 0 ? iACLen - 1 : 0;
if (buf[iOffset] & 0x20) {
int iSC;
if (len < 1 + (size_t)iACLen)
break;
iSC = buf[iOffset + iACLen];
switch( (iSC>>5) & 0x03 ) {
case 0:
iMethod = SC_AC_TERM; /* key authentication */
break;
case 1:
iMethod = SC_AC_AUT; /* key authentication */
break;
case 2:
case 3:
iMethod = SC_AC_PRO; /* secure messaging */
break;
}
iKeyRef = iSC & 0x1F; /* get key number */
iPinCount--; /* one byte used for keyReference */
}
/* Pin present ? */
if ( iPinCount > 0 ) {
if (len < 1 + 2)
break;
iKeyRef = buf[iOffset + 2]; /* pin ref */
iMethod = SC_AC_CHV;
}
/* Add AC for each command-operationType into OpenSc structure */
bValue = buf[iOffset + 1];
for (i = 0; i < 8; i++) {
if((bValue & 1) && (p_idx[i] >= 0))
sc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef);
bValue >>= 1;
}
}
/* Current field treated, get next AC sub-field */
iOffset += iACLen +1; /* AC + PTL-byte */
len -= iACLen +1;
}
}
static int setcos_select_file(sc_card_t *card,
const sc_path_t *in_path, sc_file_t **file)
{
int r;
r = iso_ops->select_file(card, in_path, file);
/* Certain FINeID cards for organisations return 6A88 instead of 6A82 for missing files */
if (card->flags & _FINEID_BROKEN_SELECT_FLAG && r == SC_ERROR_DATA_OBJECT_NOT_FOUND)
return SC_ERROR_FILE_NOT_FOUND;
if (r)
return r;
if (file != NULL) {
if (card->type == SC_CARD_TYPE_SETCOS_44 ||
card->type == SC_CARD_TYPE_SETCOS_NIDEL ||
SETCOS_IS_EID_APPLET(card))
parse_sec_attr_44(*file, (*file)->sec_attr, (*file)->sec_attr_len);
else
parse_sec_attr(*file, (*file)->sec_attr, (*file)->sec_attr_len);
}
return 0;
}
static int setcos_list_files(sc_card_t *card, u8 * buf, size_t buflen)
{
sc_apdu_t apdu;
int r;
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, 0, 0);
if (card->type == SC_CARD_TYPE_SETCOS_44 ||
card->type == SC_CARD_TYPE_SETCOS_NIDEL ||
SETCOS_IS_EID_APPLET(card))
apdu.cla = 0x80;
apdu.resp = buf;
apdu.resplen = buflen;
apdu.le = buflen > 256 ? 256 : buflen;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (card->type == SC_CARD_TYPE_SETCOS_44 && apdu.sw1 == 0x6A && apdu.sw2 == 0x82)
return 0; /* no files found */
if (apdu.resplen == 0)
return sc_check_sw(card, apdu.sw1, apdu.sw2);
return apdu.resplen;
}
static int setcos_process_fci(sc_card_t *card, sc_file_t *file,
const u8 *buf, size_t buflen)
{
int r = iso_ops->process_fci(card, file, buf, buflen);
/* SetCOS 4.4: RSA key file is an internal EF but it's
* file descriptor doesn't seem to follow ISO7816. */
if (r >= 0 && (card->type == SC_CARD_TYPE_SETCOS_44 ||
SETCOS_IS_EID_APPLET(card))) {
const u8 *tag;
size_t taglen = 1;
tag = (u8 *) sc_asn1_find_tag(card->ctx, buf, buflen, 0x82, &taglen);
if (tag != NULL && taglen == 1 && *tag == 0x11)
file->type = SC_FILE_TYPE_INTERNAL_EF;
}
return r;
}
/* Write internal data, e.g. add default pin-records to pin-file */
static int setcos_putdata(struct sc_card *card, struct sc_cardctl_setcos_data_obj* data_obj)
{
int r;
struct sc_apdu apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_3_SHORT;
apdu.cla = 0x00;
apdu.ins = 0xDA;
apdu.p1 = data_obj->P1;
apdu.p2 = data_obj->P2;
apdu.lc = data_obj->DataLen;
apdu.datalen = data_obj->DataLen;
apdu.data = data_obj->Data;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "PUT_DATA returned error");
LOG_FUNC_RETURN(card->ctx, r);
}
/* Read internal data, e.g. get RSA public key */
static int setcos_getdata(struct sc_card *card, struct sc_cardctl_setcos_data_obj* data_obj)
{
int r;
struct sc_apdu apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.cla = 0x00;
apdu.ins = 0xCA; /* GET DATA */
apdu.p1 = data_obj->P1;
apdu.p2 = data_obj->P2;
apdu.lc = 0;
apdu.datalen = 0;
apdu.data = data_obj->Data;
apdu.le = 256;
apdu.resp = data_obj->Data;
apdu.resplen = data_obj->DataLen;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "GET_DATA returned error");
if (apdu.resplen > data_obj->DataLen)
r = SC_ERROR_WRONG_LENGTH;
else
data_obj->DataLen = apdu.resplen;
LOG_FUNC_RETURN(card->ctx, r);
}
/* Generate or store a key */
static int setcos_generate_store_key(sc_card_t *card,
struct sc_cardctl_setcos_gen_store_key_info *data)
{
struct sc_apdu apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
int r, len;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Setup key-generation parameters */
len = 0;
if (data->op_type == OP_TYPE_GENERATE)
sbuf[len++] = 0x92; /* algo ID: RSA CRT */
else
sbuf[len++] = 0x9A; /* algo ID: EXTERNALLY GENERATED RSA CRT */
sbuf[len++] = 0x00;
sbuf[len++] = data->mod_len / 256; /* 2 bytes for modulus bitlength */
sbuf[len++] = data->mod_len % 256;
sbuf[len++] = data->pubexp_len / 256; /* 2 bytes for pubexp bitlength */
sbuf[len++] = data->pubexp_len % 256;
memcpy(sbuf + len, data->pubexp, (data->pubexp_len + 7) / 8);
len += (data->pubexp_len + 7) / 8;
if (data->op_type == OP_TYPE_STORE) {
sbuf[len++] = data->primep_len / 256;
sbuf[len++] = data->primep_len % 256;
memcpy(sbuf + len, data->primep, (data->primep_len + 7) / 8);
len += (data->primep_len + 7) / 8;
sbuf[len++] = data->primeq_len / 256;
sbuf[len++] = data->primeq_len % 256;
memcpy(sbuf + len, data->primeq, (data->primeq_len + 7) / 8);
len += (data->primeq_len + 7) / 8;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00);
apdu.cla = 0x00;
apdu.data = sbuf;
apdu.datalen = len;
apdu.lc = len;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "STORE/GENERATE_KEY returned error");
LOG_FUNC_RETURN(card->ctx, r);
}
static int setcos_activate_file(sc_card_t *card)
{
int r;
u8 sbuf[2];
sc_apdu_t apdu;
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x44, 0x00, 0x00);
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "ACTIVATE_FILE returned error");
LOG_FUNC_RETURN(card->ctx, r);
}
static int setcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
if (card->type != SC_CARD_TYPE_SETCOS_44 && !SETCOS_IS_EID_APPLET(card))
return SC_ERROR_NOT_SUPPORTED;
switch(cmd) {
case SC_CARDCTL_SETCOS_PUTDATA:
return setcos_putdata(card,
(struct sc_cardctl_setcos_data_obj*) ptr);
break;
case SC_CARDCTL_SETCOS_GETDATA:
return setcos_getdata(card,
(struct sc_cardctl_setcos_data_obj*) ptr);
break;
case SC_CARDCTL_SETCOS_GENERATE_STORE_KEY:
return setcos_generate_store_key(card,
(struct sc_cardctl_setcos_gen_store_key_info *) ptr);
case SC_CARDCTL_SETCOS_ACTIVATE_FILE:
return setcos_activate_file(card);
}
return SC_ERROR_NOT_SUPPORTED;
}
static struct sc_card_driver *sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
setcos_ops = *iso_drv->ops;
setcos_ops.match_card = setcos_match_card;
setcos_ops.init = setcos_init;
if (iso_ops == NULL)
iso_ops = iso_drv->ops;
setcos_ops.create_file = setcos_create_file;
setcos_ops.set_security_env = setcos_set_security_env;
setcos_ops.select_file = setcos_select_file;
setcos_ops.list_files = setcos_list_files;
setcos_ops.process_fci = setcos_process_fci;
setcos_ops.construct_fci = setcos_construct_fci;
setcos_ops.card_ctl = setcos_card_ctl;
return &setcos_drv;
}
struct sc_card_driver *sc_get_setcos_driver(void)
{
return sc_get_driver();
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1297_0 |
crossvul-cpp_data_good_1374_0 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre
* Copyright (c) Telecom ParisTech 2005-2012
*
* This file is part of GPAC / MPEG2-TS sub-project
*
* GPAC is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GPAC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <gpac/mpegts.h>
#ifndef GPAC_DISABLE_MPEG2TS
#include <string.h>
#include <gpac/constants.h>
#include <gpac/internal/media_dev.h>
#include <gpac/download.h>
#ifndef GPAC_DISABLE_STREAMING
#include <gpac/internal/ietf_dev.h>
#endif
#ifdef GPAC_CONFIG_LINUX
#include <unistd.h>
#endif
#ifdef GPAC_ENABLE_MPE
#include <gpac/dvb_mpe.h>
#endif
#ifdef GPAC_ENABLE_DSMCC
#include <gpac/ait.h>
#endif
#define DEBUG_TS_PACKET 0
GF_EXPORT
const char *gf_m2ts_get_stream_name(u32 streamType)
{
switch (streamType) {
case GF_M2TS_VIDEO_MPEG1:
return "MPEG-1 Video";
case GF_M2TS_VIDEO_MPEG2:
return "MPEG-2 Video";
case GF_M2TS_AUDIO_MPEG1:
return "MPEG-1 Audio";
case GF_M2TS_AUDIO_MPEG2:
return "MPEG-2 Audio";
case GF_M2TS_PRIVATE_SECTION:
return "Private Section";
case GF_M2TS_PRIVATE_DATA:
return "Private Data";
case GF_M2TS_AUDIO_AAC:
return "AAC Audio";
case GF_M2TS_VIDEO_MPEG4:
return "MPEG-4 Video";
case GF_M2TS_VIDEO_H264:
return "MPEG-4/H264 Video";
case GF_M2TS_VIDEO_SVC:
return "H264-SVC Video";
case GF_M2TS_VIDEO_HEVC:
return "HEVC Video";
case GF_M2TS_VIDEO_SHVC:
return "SHVC Video";
case GF_M2TS_VIDEO_SHVC_TEMPORAL:
return "SHVC Video Temporal Sublayer";
case GF_M2TS_VIDEO_MHVC:
return "MHVC Video";
case GF_M2TS_VIDEO_MHVC_TEMPORAL:
return "MHVC Video Temporal Sublayer";
case GF_M2TS_AUDIO_AC3:
return "Dolby AC3 Audio";
case GF_M2TS_AUDIO_DTS:
return "Dolby DTS Audio";
case GF_M2TS_SUBTITLE_DVB:
return "DVB Subtitle";
case GF_M2TS_SYSTEMS_MPEG4_PES:
return "MPEG-4 SL (PES)";
case GF_M2TS_SYSTEMS_MPEG4_SECTIONS:
return "MPEG-4 SL (Section)";
case GF_M2TS_MPE_SECTIONS:
return "MPE (Section)";
case GF_M2TS_METADATA_PES:
return "Metadata (PES)";
case GF_M2TS_METADATA_ID3_HLS:
return "ID3/HLS Metadata (PES)";
default:
return "Unknown";
}
}
static u32 gf_m2ts_reframe_default(GF_M2TS_Demuxer *ts, GF_M2TS_PES *pes, Bool same_pts, unsigned char *data, u32 data_len, GF_M2TS_PESHeader *pes_hdr)
{
GF_M2TS_PES_PCK pck;
pck.flags = 0;
if (pes->rap) pck.flags |= GF_M2TS_PES_PCK_RAP;
if (!same_pts) pck.flags |= GF_M2TS_PES_PCK_AU_START;
pck.DTS = pes->DTS;
pck.PTS = pes->PTS;
pck.data = (char *)data;
pck.data_len = data_len;
pck.stream = pes;
ts->on_event(ts, GF_M2TS_EVT_PES_PCK, &pck);
/*we consumed all data*/
return 0;
}
static u32 gf_m2ts_reframe_reset(GF_M2TS_Demuxer *ts, GF_M2TS_PES *pes, Bool same_pts, unsigned char *data, u32 data_len, GF_M2TS_PESHeader *pes_hdr)
{
if (pes->pck_data) {
gf_free(pes->pck_data);
pes->pck_data = NULL;
}
pes->pck_data_len = pes->pck_alloc_len = 0;
if (pes->prev_data) {
gf_free(pes->prev_data);
pes->prev_data = NULL;
}
pes->prev_data_len = 0;
pes->pes_len = 0;
pes->prev_PTS = 0;
pes->reframe = NULL;
pes->cc = -1;
pes->temi_tc_desc_len = 0;
return 0;
}
static void add_text(char **buffer, u32 *size, u32 *pos, char *msg, u32 msg_len)
{
if (!msg || !buffer) return;
if (*pos+msg_len>*size) {
*size = *pos+msg_len-*size+256;
*buffer = (char *)gf_realloc(*buffer, *size);
}
strncpy((*buffer)+(*pos), msg, msg_len);
*pos += msg_len;
}
static GF_Err id3_parse_tag(char *data, u32 length, char **output, u32 *output_size, u32 *output_pos)
{
GF_BitStream *bs;
u32 pos;
if ((data[0] != 'I') || (data[1] != 'D') || (data[2] != '3'))
return GF_NOT_SUPPORTED;
bs = gf_bs_new(data, length, GF_BITSTREAM_READ);
gf_bs_skip_bytes(bs, 3);
/*u8 major = */gf_bs_read_u8(bs);
/*u8 minor = */gf_bs_read_u8(bs);
/*u8 unsync = */gf_bs_read_int(bs, 1);
/*u8 ext_hdr = */ gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 6);
u32 size = gf_id3_read_size(bs);
pos = (u32) gf_bs_get_position(bs);
if (size != length-pos)
size = length-pos;
while (size && (gf_bs_available(bs)>=10) ) {
u32 ftag = gf_bs_read_u32(bs);
u32 fsize = gf_id3_read_size(bs);
/*u16 fflags = */gf_bs_read_u16(bs);
size -= 10;
//TODO, handle more ID3 tags ?
if (ftag==ID3V2_FRAME_TXXX) {
u32 pos = (u32) gf_bs_get_position(bs);
char *text = data+pos;
add_text(output, output_size, output_pos, text, fsize);
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] ID3 tag not handled, patch welcome\n", gf_4cc_to_str(ftag) ) );
}
gf_bs_skip_bytes(bs, fsize);
}
gf_bs_del(bs);
return GF_OK;
}
static u32 gf_m2ts_reframe_id3_pes(GF_M2TS_Demuxer *ts, GF_M2TS_PES *pes, Bool same_pts, unsigned char *data, u32 data_len, GF_M2TS_PESHeader *pes_hdr)
{
char frame_header[256];
char *output_text = NULL;
u32 output_len = 0;
u32 pos = 0;
GF_M2TS_PES_PCK pck;
pck.flags = 0;
if (pes->rap) pck.flags |= GF_M2TS_PES_PCK_RAP;
if (!same_pts) pck.flags |= GF_M2TS_PES_PCK_AU_START;
pck.DTS = pes->DTS;
pck.PTS = pes->PTS;
sprintf(frame_header, LLU" --> NEXT\n", pes->PTS);
add_text(&output_text, &output_len, &pos, frame_header, (u32)strlen(frame_header));
id3_parse_tag((char *)data, data_len, &output_text, &output_len, &pos);
add_text(&output_text, &output_len, &pos, "\n\n", 2);
pck.data = (char *)output_text;
pck.data_len = pos;
pck.stream = pes;
ts->on_event(ts, GF_M2TS_EVT_PES_PCK, &pck);
gf_free(output_text);
/*we consumed all data*/
return 0;
}
static u32 gf_m2ts_sync(GF_M2TS_Demuxer *ts, char *data, u32 size, Bool simple_check)
{
u32 i=0;
/*if first byte is sync assume we're sync*/
if (simple_check && (data[i]==0x47)) return 0;
while (i < size) {
if (i+192 >= size) return size;
if ((data[i]==0x47) && (data[i+188]==0x47))
break;
if (i+192 >= size) return size;
if ((data[i]==0x47) && (data[i+192]==0x47)) {
ts->prefix_present = 1;
break;
}
i++;
}
if (i) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] re-sync skipped %d bytes\n", i) );
}
return i;
}
GF_EXPORT
Bool gf_m2ts_crc32_check(u8 *data, u32 len)
{
u32 crc = gf_crc_32(data, len);
u32 crc_val = GF_4CC((u8) data[len], (u8) data[len+1], (u8) data[len+2], (u8) data[len+3]);
return (crc==crc_val) ? GF_TRUE : GF_FALSE;
}
static GF_M2TS_SectionFilter *gf_m2ts_section_filter_new(gf_m2ts_section_callback process_section_callback, Bool process_individual)
{
GF_M2TS_SectionFilter *sec;
GF_SAFEALLOC(sec, GF_M2TS_SectionFilter);
if (!sec) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] gf_m2ts_section_filter_new : OUT OF MEMORY\n"));
return NULL;
}
sec->cc = -1;
sec->process_section = process_section_callback;
sec->process_individual = process_individual;
return sec;
}
static void gf_m2ts_reset_sections(GF_List *sections)
{
u32 count;
GF_M2TS_Section *section;
//GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Deleting sections\n"));
count = gf_list_count(sections);
while (count) {
section = gf_list_get(sections, 0);
gf_list_rem(sections, 0);
if (section->data) gf_free(section->data);
gf_free(section);
count--;
}
}
static void gf_m2ts_section_filter_reset(GF_M2TS_SectionFilter *sf)
{
if (sf->section) {
gf_free(sf->section);
sf->section = NULL;
}
while (sf->table) {
GF_M2TS_Table *t = sf->table;
sf->table = t->next;
gf_m2ts_reset_sections(t->sections);
gf_list_del(t->sections);
gf_free(t);
}
sf->cc = -1;
sf->length = sf->received = 0;
sf->demux_restarted = 1;
}
static void gf_m2ts_section_filter_del(GF_M2TS_SectionFilter *sf)
{
gf_m2ts_section_filter_reset(sf);
gf_free(sf);
}
static void gf_m2ts_metadata_descriptor_del(GF_M2TS_MetadataDescriptor *metad)
{
if (metad) {
if (metad->service_id_record) gf_free(metad->service_id_record);
if (metad->decoder_config) gf_free(metad->decoder_config);
if (metad->decoder_config_id) gf_free(metad->decoder_config_id);
gf_free(metad);
}
}
GF_EXPORT
void gf_m2ts_es_del(GF_M2TS_ES *es, GF_M2TS_Demuxer *ts)
{
gf_list_del_item(es->program->streams, es);
if (es->flags & GF_M2TS_ES_IS_SECTION) {
GF_M2TS_SECTION_ES *ses = (GF_M2TS_SECTION_ES *)es;
if (ses->sec) gf_m2ts_section_filter_del(ses->sec);
#ifdef GPAC_ENABLE_MPE
if (es->flags & GF_M2TS_ES_IS_MPE)
gf_dvb_mpe_section_del(es);
#endif
} else if (es->pid!=es->program->pmt_pid) {
GF_M2TS_PES *pes = (GF_M2TS_PES *)es;
if ((pes->flags & GF_M2TS_INHERIT_PCR) && ts->ess[es->program->pcr_pid]==es)
ts->ess[es->program->pcr_pid] = NULL;
if (pes->pck_data) gf_free(pes->pck_data);
if (pes->prev_data) gf_free(pes->prev_data);
if (pes->buf) gf_free(pes->buf);
if (pes->reassemble_buf) gf_free(pes->reassemble_buf);
if (pes->temi_tc_desc) gf_free(pes->temi_tc_desc);
if (pes->metadata_descriptor) gf_m2ts_metadata_descriptor_del(pes->metadata_descriptor);
}
if (es->slcfg) gf_free(es->slcfg);
gf_free(es);
}
static void gf_m2ts_reset_sdt(GF_M2TS_Demuxer *ts)
{
while (gf_list_count(ts->SDTs)) {
GF_M2TS_SDT *sdt = (GF_M2TS_SDT *)gf_list_last(ts->SDTs);
gf_list_rem_last(ts->SDTs);
if (sdt->provider) gf_free(sdt->provider);
if (sdt->service) gf_free(sdt->service);
gf_free(sdt);
}
}
GF_EXPORT
GF_M2TS_SDT *gf_m2ts_get_sdt_info(GF_M2TS_Demuxer *ts, u32 program_id)
{
u32 i;
for (i=0; i<gf_list_count(ts->SDTs); i++) {
GF_M2TS_SDT *sdt = (GF_M2TS_SDT *)gf_list_get(ts->SDTs, i);
if (sdt->service_id==program_id) return sdt;
}
return NULL;
}
static void gf_m2ts_section_complete(GF_M2TS_Demuxer *ts, GF_M2TS_SectionFilter *sec, GF_M2TS_SECTION_ES *ses)
{
//seek mode, only process PAT and PMT
if (ts->seek_mode && (sec->section[0] != GF_M2TS_TABLE_ID_PAT) && (sec->section[0] != GF_M2TS_TABLE_ID_PMT)) {
/*clean-up (including broken sections)*/
if (sec->section) gf_free(sec->section);
sec->section = NULL;
sec->length = sec->received = 0;
return;
}
if (!sec->process_section) {
if ((ts->on_event && (sec->section[0]==GF_M2TS_TABLE_ID_AIT)) ) {
#ifdef GPAC_ENABLE_DSMCC
GF_M2TS_SL_PCK pck;
pck.data_len = sec->length;
pck.data = sec->section;
pck.stream = (GF_M2TS_ES *)ses;
//ts->on_event(ts, GF_M2TS_EVT_AIT_FOUND, &pck);
on_ait_section(ts, GF_M2TS_EVT_AIT_FOUND, &pck);
#endif
} else if ((ts->on_event && (sec->section[0]==GF_M2TS_TABLE_ID_DSM_CC_ENCAPSULATED_DATA || sec->section[0]==GF_M2TS_TABLE_ID_DSM_CC_UN_MESSAGE ||
sec->section[0]==GF_M2TS_TABLE_ID_DSM_CC_DOWNLOAD_DATA_MESSAGE || sec->section[0]==GF_M2TS_TABLE_ID_DSM_CC_STREAM_DESCRIPTION || sec->section[0]==GF_M2TS_TABLE_ID_DSM_CC_PRIVATE)) ) {
#ifdef GPAC_ENABLE_DSMCC
GF_M2TS_SL_PCK pck;
pck.data_len = sec->length;
pck.data = sec->section;
pck.stream = (GF_M2TS_ES *)ses;
on_dsmcc_section(ts,GF_M2TS_EVT_DSMCC_FOUND,&pck);
//ts->on_event(ts, GF_M2TS_EVT_DSMCC_FOUND, &pck);
#endif
}
#ifdef GPAC_ENABLE_MPE
else if (ts->on_mpe_event && ((ses && (ses->flags & GF_M2TS_EVT_DVB_MPE)) || (sec->section[0]==GF_M2TS_TABLE_ID_INT)) ) {
GF_M2TS_SL_PCK pck;
pck.data_len = sec->length;
pck.data = sec->section;
pck.stream = (GF_M2TS_ES *)ses;
ts->on_mpe_event(ts, GF_M2TS_EVT_DVB_MPE, &pck);
}
#endif
else if (ts->on_event) {
GF_M2TS_SL_PCK pck;
pck.data_len = sec->length;
pck.data = sec->section;
pck.stream = (GF_M2TS_ES *)ses;
ts->on_event(ts, GF_M2TS_EVT_DVB_GENERAL, &pck);
}
} else {
Bool has_syntax_indicator;
u8 table_id;
u16 extended_table_id;
u32 status, section_start, i;
GF_M2TS_Table *t, *prev_t;
unsigned char *data;
Bool section_valid = 0;
status = 0;
/*parse header*/
data = (u8 *)sec->section;
/*look for proper table*/
table_id = data[0];
if (ts->on_event) {
switch (table_id) {
case GF_M2TS_TABLE_ID_PAT:
case GF_M2TS_TABLE_ID_SDT_ACTUAL:
case GF_M2TS_TABLE_ID_PMT:
case GF_M2TS_TABLE_ID_NIT_ACTUAL:
case GF_M2TS_TABLE_ID_TDT:
case GF_M2TS_TABLE_ID_TOT:
{
GF_M2TS_SL_PCK pck;
pck.data_len = sec->length;
pck.data = sec->section;
pck.stream = (GF_M2TS_ES *)ses;
ts->on_event(ts, GF_M2TS_EVT_DVB_GENERAL, &pck);
}
}
}
has_syntax_indicator = (data[1] & 0x80) ? 1 : 0;
if (has_syntax_indicator) {
extended_table_id = (data[3]<<8) | data[4];
} else {
extended_table_id = 0;
}
prev_t = NULL;
t = sec->table;
while (t) {
if ((t->table_id==table_id) && (t->ex_table_id == extended_table_id)) break;
prev_t = t;
t = t->next;
}
/*create table*/
if (!t) {
GF_SAFEALLOC(t, GF_M2TS_Table);
if (!t) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Fail to alloc table %d %d\n", table_id, extended_table_id));
return;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Creating table %d %d\n", table_id, extended_table_id));
t->table_id = table_id;
t->ex_table_id = extended_table_id;
t->last_version_number = 0xFF;
t->sections = gf_list_new();
if (prev_t) prev_t->next = t;
else sec->table = t;
}
if (has_syntax_indicator) {
if (sec->length < 4) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] corrupted section length %d less than CRC \n", sec->length));
} else {
/*remove crc32*/
sec->length -= 4;
if (gf_m2ts_crc32_check((char *)data, sec->length)) {
s32 cur_sec_num;
t->version_number = (data[5] >> 1) & 0x1f;
if (t->last_section_number && t->section_number && (t->version_number != t->last_version_number)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] table transmission interrupted: previous table (v=%d) %d/%d sections - new table (v=%d) %d/%d sections\n", t->last_version_number, t->section_number, t->last_section_number, t->version_number, data[6] + 1, data[7] + 1) );
gf_m2ts_reset_sections(t->sections);
t->section_number = 0;
}
t->current_next_indicator = (data[5] & 0x1) ? 1 : 0;
/*add one to section numbers to detect if we missed or not the first section in the table*/
cur_sec_num = data[6] + 1;
t->last_section_number = data[7] + 1;
section_start = 8;
/*we missed something*/
if (!sec->process_individual && t->section_number + 1 != cur_sec_num) {
/* TODO - Check how to handle sections when the first complete section does
not have its sec num 0 */
section_valid = 0;
if (t->is_init) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] corrupted table (lost section %d)\n", cur_sec_num ? cur_sec_num-1 : 31) );
}
} else {
section_valid = 1;
t->section_number = cur_sec_num;
}
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] corrupted section (CRC32 failed)\n"));
}
}
} else {
section_valid = 1;
section_start = 3;
}
/*process section*/
if (section_valid) {
GF_M2TS_Section *section;
GF_SAFEALLOC(section, GF_M2TS_Section);
if (!section) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Fail to create section\n"));
return;
}
section->data_size = sec->length - section_start;
section->data = (unsigned char*)gf_malloc(sizeof(unsigned char)*section->data_size);
memcpy(section->data, sec->section + section_start, sizeof(unsigned char)*section->data_size);
gf_list_add(t->sections, section);
if (t->section_number == 1) {
status |= GF_M2TS_TABLE_START;
if (t->last_version_number == t->version_number) {
t->is_repeat = 1;
} else {
t->is_repeat = 0;
}
/*only update version number in the first section of the table*/
t->last_version_number = t->version_number;
}
if (t->is_init) {
if (t->is_repeat) {
status |= GF_M2TS_TABLE_REPEAT;
} else {
status |= GF_M2TS_TABLE_UPDATE;
}
} else {
status |= GF_M2TS_TABLE_FOUND;
}
if (t->last_section_number == t->section_number) {
u32 table_size;
status |= GF_M2TS_TABLE_END;
table_size = 0;
for (i=0; i<gf_list_count(t->sections); i++) {
GF_M2TS_Section *section = gf_list_get(t->sections, i);
table_size += section->data_size;
}
if (t->is_repeat) {
if (t->table_size != table_size) {
status |= GF_M2TS_TABLE_UPDATE;
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] Repeated section found with different sizes (old table %d bytes, new table %d bytes)\n", t->table_size, table_size) );
t->table_size = table_size;
}
} else {
t->table_size = table_size;
}
t->is_init = 1;
/*reset section number*/
t->section_number = 0;
t->is_repeat = 0;
}
if (sec->process_individual) {
/*send each section of the table and not the aggregated table*/
if (sec->process_section)
sec->process_section(ts, ses, t->sections, t->table_id, t->ex_table_id, t->version_number, (u8) (t->last_section_number - 1), status);
gf_m2ts_reset_sections(t->sections);
} else {
if (status&GF_M2TS_TABLE_END) {
if (sec->process_section)
sec->process_section(ts, ses, t->sections, t->table_id, t->ex_table_id, t->version_number, (u8) (t->last_section_number - 1), status);
gf_m2ts_reset_sections(t->sections);
}
}
} else {
sec->cc = -1;
t->section_number = 0;
}
}
/*clean-up (including broken sections)*/
if (sec->section) gf_free(sec->section);
sec->section = NULL;
sec->length = sec->received = 0;
}
static Bool gf_m2ts_is_long_section(u8 table_id)
{
switch (table_id) {
case GF_M2TS_TABLE_ID_MPEG4_BIFS:
case GF_M2TS_TABLE_ID_MPEG4_OD:
case GF_M2TS_TABLE_ID_INT:
case GF_M2TS_TABLE_ID_EIT_ACTUAL_PF:
case GF_M2TS_TABLE_ID_EIT_OTHER_PF:
case GF_M2TS_TABLE_ID_ST:
case GF_M2TS_TABLE_ID_SIT:
case GF_M2TS_TABLE_ID_DSM_CC_PRIVATE:
case GF_M2TS_TABLE_ID_MPE_FEC:
case GF_M2TS_TABLE_ID_DSM_CC_DOWNLOAD_DATA_MESSAGE:
case GF_M2TS_TABLE_ID_DSM_CC_UN_MESSAGE:
return 1;
default:
if (table_id >= GF_M2TS_TABLE_ID_EIT_SCHEDULE_MIN && table_id <= GF_M2TS_TABLE_ID_EIT_SCHEDULE_MAX)
return 1;
else
return 0;
}
}
static u32 gf_m2ts_get_section_length(char byte0, char byte1, char byte2)
{
u32 length;
if (gf_m2ts_is_long_section(byte0)) {
length = 3 + ( ((((u32)byte1)<<8) | (byte2&0xff)) & 0xfff );
} else {
length = 3 + ( ((((u32)byte1)<<8) | (byte2&0xff)) & 0x3ff );
}
return length;
}
static void gf_m2ts_gather_section(GF_M2TS_Demuxer *ts, GF_M2TS_SectionFilter *sec, GF_M2TS_SECTION_ES *ses, GF_M2TS_Header *hdr, unsigned char *data, u32 data_size)
{
u32 payload_size = data_size;
u8 expect_cc = (sec->cc<0) ? hdr->continuity_counter : (sec->cc + 1) & 0xf;
Bool disc = (expect_cc == hdr->continuity_counter) ? 0 : 1;
sec->cc = expect_cc;
/*may happen if hdr->adaptation_field=2 no payload in TS packet*/
if (!data_size) return;
if (hdr->payload_start) {
u32 ptr_field;
ptr_field = data[0];
if (ptr_field+1>data_size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Invalid section start (@ptr_field=%d, @data_size=%d)\n", ptr_field, data_size) );
return;
}
/*end of previous section*/
if (!sec->length && sec->received) {
/* the length of the section could not be determined from the previous TS packet because we had only 1 or 2 bytes */
if (sec->received == 1)
sec->length = gf_m2ts_get_section_length(sec->section[0], data[1], data[2]);
else /* (sec->received == 2) */
sec->length = gf_m2ts_get_section_length(sec->section[0], sec->section[1], data[1]);
sec->section = (char*)gf_realloc(sec->section, sizeof(char)*sec->length);
}
if (sec->length && sec->received + ptr_field >= sec->length) {
u32 len = sec->length - sec->received;
memcpy(sec->section + sec->received, data+1, sizeof(char)*len);
sec->received += len;
if (ptr_field > len)
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Invalid pointer field (@ptr_field=%d, @remaining=%d)\n", ptr_field, len) );
gf_m2ts_section_complete(ts, sec, ses);
}
data += ptr_field+1;
data_size -= ptr_field+1;
payload_size -= ptr_field+1;
aggregated_section:
if (sec->section) gf_free(sec->section);
sec->length = sec->received = 0;
sec->section = (char*)gf_malloc(sizeof(char)*data_size);
memcpy(sec->section, data, sizeof(char)*data_size);
sec->received = data_size;
} else if (disc) {
if (sec->section) gf_free(sec->section);
sec->section = NULL;
sec->received = sec->length = 0;
return;
} else if (!sec->section) {
return;
} else {
if (sec->length && sec->received+data_size > sec->length)
data_size = sec->length - sec->received;
if (sec->length) {
memcpy(sec->section + sec->received, data, sizeof(char)*data_size);
} else {
sec->section = (char*)gf_realloc(sec->section, sizeof(char)*(sec->received+data_size));
memcpy(sec->section + sec->received, data, sizeof(char)*data_size);
}
sec->received += data_size;
}
/*alloc final buffer*/
if (!sec->length && (sec->received >= 3)) {
sec->length = gf_m2ts_get_section_length(sec->section[0], sec->section[1], sec->section[2]);
sec->section = (char*)gf_realloc(sec->section, sizeof(char)*sec->length);
if (sec->received > sec->length) {
data_size -= sec->received - sec->length;
sec->received = sec->length;
}
}
if (!sec->length || sec->received < sec->length) return;
/*OK done*/
gf_m2ts_section_complete(ts, sec, ses);
if (payload_size > data_size) {
data += data_size;
/* detect padding after previous section */
if (data[0] != 0xFF) {
data_size = payload_size - data_size;
payload_size = data_size;
goto aggregated_section;
}
}
}
static void gf_m2ts_process_sdt(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *ses, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
u32 pos, evt_type;
u32 nb_sections;
u32 data_size;
unsigned char *data;
GF_M2TS_Section *section;
/*wait for the last section */
if (!(status&GF_M2TS_TABLE_END)) return;
/*skip if already received*/
if (status&GF_M2TS_TABLE_REPEAT) {
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_SDT_REPEAT, NULL);
return;
}
if (table_id != GF_M2TS_TABLE_ID_SDT_ACTUAL) {
return;
}
gf_m2ts_reset_sdt(ts);
nb_sections = gf_list_count(sections);
if (nb_sections > 1) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] SDT on multiple sections not supported\n"));
}
section = (GF_M2TS_Section *)gf_list_get(sections, 0);
data = section->data;
data_size = section->data_size;
//orig_net_id = (data[0] << 8) | data[1];
pos = 3;
while (pos < data_size) {
GF_M2TS_SDT *sdt;
u32 descs_size, d_pos, ulen;
GF_SAFEALLOC(sdt, GF_M2TS_SDT);
if (!sdt) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] Fail to create SDT\n"));
return;
}
gf_list_add(ts->SDTs, sdt);
sdt->service_id = (data[pos]<<8) + data[pos+1];
sdt->EIT_schedule = (data[pos+2] & 0x2) ? 1 : 0;
sdt->EIT_present_following = (data[pos+2] & 0x1);
sdt->running_status = (data[pos+3]>>5) & 0x7;
sdt->free_CA_mode = (data[pos+3]>>4) & 0x1;
descs_size = ((data[pos+3]&0xf)<<8) | data[pos+4];
pos += 5;
d_pos = 0;
while (d_pos < descs_size) {
u8 d_tag = data[pos+d_pos];
u8 d_len = data[pos+d_pos+1];
switch (d_tag) {
case GF_M2TS_DVB_SERVICE_DESCRIPTOR:
if (sdt->provider) gf_free(sdt->provider);
sdt->provider = NULL;
if (sdt->service) gf_free(sdt->service);
sdt->service = NULL;
d_pos+=2;
sdt->service_type = data[pos+d_pos];
ulen = data[pos+d_pos+1];
d_pos += 2;
sdt->provider = (char*)gf_malloc(sizeof(char)*(ulen+1));
memcpy(sdt->provider, data+pos+d_pos, sizeof(char)*ulen);
sdt->provider[ulen] = 0;
d_pos += ulen;
ulen = data[pos+d_pos];
d_pos += 1;
sdt->service = (char*)gf_malloc(sizeof(char)*(ulen+1));
memcpy(sdt->service, data+pos+d_pos, sizeof(char)*ulen);
sdt->service[ulen] = 0;
d_pos += ulen;
break;
default:
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Skipping descriptor (0x%x) not supported\n", d_tag));
d_pos += d_len;
if (d_len == 0) d_pos = descs_size;
break;
}
}
pos += descs_size;
}
evt_type = GF_M2TS_EVT_SDT_FOUND;
if (ts->on_event) ts->on_event(ts, evt_type, NULL);
}
static void gf_m2ts_process_mpeg4section(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *es, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
GF_M2TS_SL_PCK sl_pck;
u32 nb_sections, i;
GF_M2TS_Section *section;
/*skip if already received*/
if (status & GF_M2TS_TABLE_REPEAT)
if (!(es->flags & GF_M2TS_ES_SEND_REPEATED_SECTIONS))
return;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Sections for PID %d\n", es->pid) );
/*send all sections (eg SL-packets)*/
nb_sections = gf_list_count(sections);
for (i=0; i<nb_sections; i++) {
section = (GF_M2TS_Section *)gf_list_get(sections, i);
sl_pck.data = (char *)section->data;
sl_pck.data_len = section->data_size;
sl_pck.stream = (GF_M2TS_ES *)es;
sl_pck.version_number = version_number;
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_SL_PCK, &sl_pck);
}
}
static void gf_m2ts_process_nit(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *nit_es, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] NIT table processing (not yet implemented)"));
}
static void gf_m2ts_process_tdt_tot(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *tdt_tot_es, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
unsigned char *data;
u32 data_size, nb_sections;
u32 date, yp, mp, k;
GF_M2TS_Section *section;
GF_M2TS_TDT_TOT *time_table;
const char *table_name;
/*wait for the last section */
if ( !(status & GF_M2TS_TABLE_END) )
return;
switch (table_id) {
case GF_M2TS_TABLE_ID_TDT:
table_name = "TDT";
break;
case GF_M2TS_TABLE_ID_TOT:
table_name = "TOT";
break;
default:
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Unimplemented table_id %u for PID %u\n", table_id, GF_M2TS_PID_TDT_TOT_ST));
return;
}
nb_sections = gf_list_count(sections);
if (nb_sections > 1) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] %s on multiple sections not supported\n", table_name));
}
section = (GF_M2TS_Section *)gf_list_get(sections, 0);
data = section->data;
data_size = section->data_size;
/*TOT only contains 40 bits of UTC_time; TDT add descriptors and a CRC*/
if ((table_id==GF_M2TS_TABLE_ID_TDT) && (data_size != 5)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] Corrupted TDT size\n", table_name));
}
GF_SAFEALLOC(time_table, GF_M2TS_TDT_TOT);
if (!time_table) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Fail to alloc DVB time table\n"));
return;
}
/*UTC_time - see annex C of DVB-SI ETSI EN 300468*/
/* decodes an Modified Julian Date (MJD) into a Co-ordinated Universal Time (UTC)
See annex C of DVB-SI ETSI EN 300468 */
date = data[0]*256 + data[1];
yp = (u32)((date - 15078.2)/365.25);
mp = (u32)((date - 14956.1 - (u32)(yp * 365.25))/30.6001);
time_table->day = (u32)(date - 14956 - (u32)(yp * 365.25) - (u32)(mp * 30.6001));
if (mp == 14 || mp == 15) k = 1;
else k = 0;
time_table->year = yp + k + 1900;
time_table->month = mp - 1 - k*12;
time_table->hour = 10*((data[2]&0xf0)>>4) + (data[2]&0x0f);
time_table->minute = 10*((data[3]&0xf0)>>4) + (data[3]&0x0f);
time_table->second = 10*((data[4]&0xf0)>>4) + (data[4]&0x0f);
assert(time_table->hour<24 && time_table->minute<60 && time_table->second<60);
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Stream UTC time is %u/%02u/%02u %02u:%02u:%02u\n", time_table->year, time_table->month, time_table->day, time_table->hour, time_table->minute, time_table->second));
switch (table_id) {
case GF_M2TS_TABLE_ID_TDT:
if (ts->TDT_time) gf_free(ts->TDT_time);
ts->TDT_time = time_table;
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_TDT, time_table);
break;
case GF_M2TS_TABLE_ID_TOT:
#if 0
{
u32 pos, loop_len;
loop_len = ((data[5]&0x0f) << 8) | (data[6] & 0xff);
data += 7;
pos = 0;
while (pos < loop_len) {
u8 tag = data[pos];
pos += 2;
if (tag == GF_M2TS_DVB_LOCAL_TIME_OFFSET_DESCRIPTOR) {
char tmp_time[10];
u16 offset_hours, offset_minutes;
now->country_code[0] = data[pos];
now->country_code[1] = data[pos+1];
now->country_code[2] = data[pos+2];
now->country_region_id = data[pos+3]>>2;
sprintf(tmp_time, "%02x", data[pos+4]);
offset_hours = atoi(tmp_time);
sprintf(tmp_time, "%02x", data[pos+5]);
offset_minutes = atoi(tmp_time);
now->local_time_offset_seconds = (offset_hours * 60 + offset_minutes) * 60;
if (data[pos+3] & 1) now->local_time_offset_seconds *= -1;
dvb_decode_mjd_to_unix_time(data+pos+6, &now->unix_next_toc);
sprintf(tmp_time, "%02x", data[pos+11]);
offset_hours = atoi(tmp_time);
sprintf(tmp_time, "%02x", data[pos+12]);
offset_minutes = atoi(tmp_time);
now->next_time_offset_seconds = (offset_hours * 60 + offset_minutes) * 60;
if (data[pos+3] & 1) now->next_time_offset_seconds *= -1;
pos+= 13;
}
}
/*TODO: check lengths are ok*/
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_TOT, time_table);
}
#endif
/*check CRC32*/
if (ts->tdt_tot->length<4) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] corrupted %s table (less than 4 bytes but CRC32 should be present\n", table_name));
goto error_exit;
}
if (!gf_m2ts_crc32_check(ts->tdt_tot->section, ts->tdt_tot->length-4)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] corrupted %s table (CRC32 failed)\n", table_name));
goto error_exit;
}
if (ts->TDT_time) gf_free(ts->TDT_time);
ts->TDT_time = time_table;
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_TOT, time_table);
break;
default:
assert(0);
goto error_exit;
}
return; /*success*/
error_exit:
gf_free(time_table);
return;
}
static GF_M2TS_MetadataPointerDescriptor *gf_m2ts_read_metadata_pointer_descriptor(GF_BitStream *bs, u32 length)
{
u32 size;
GF_M2TS_MetadataPointerDescriptor *d;
GF_SAFEALLOC(d, GF_M2TS_MetadataPointerDescriptor);
if (!d) return NULL;
d->application_format = gf_bs_read_u16(bs);
size = 2;
if (d->application_format == 0xFFFF) {
d->application_format_identifier = gf_bs_read_u32(bs);
size += 4;
}
d->format = gf_bs_read_u8(bs);
size += 1;
if (d->format == 0xFF) {
d->format_identifier = gf_bs_read_u32(bs);
size += 4;
}
d->service_id = gf_bs_read_u8(bs);
d->locator_record_flag = (gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE);
d->carriage_flag = (enum metadata_carriage)gf_bs_read_int(bs, 2);
gf_bs_read_int(bs, 5); /*reserved */
size += 2;
if (d->locator_record_flag) {
d->locator_length = gf_bs_read_u8(bs);
d->locator_data = (char *)gf_malloc(d->locator_length);
size += 1 + d->locator_length;
gf_bs_read_data(bs, d->locator_data, d->locator_length);
}
if (d->carriage_flag != 3) {
d->program_number = gf_bs_read_u16(bs);
size += 2;
}
if (d->carriage_flag == 1) {
d->ts_location = gf_bs_read_u16(bs);
d->ts_id = gf_bs_read_u16(bs);
size += 4;
}
if (length-size > 0) {
d->data_size = length-size;
d->data = (char *)gf_malloc(d->data_size);
gf_bs_read_data(bs, d->data, d->data_size);
}
return d;
}
static void gf_m2ts_metadata_pointer_descriptor_del(GF_M2TS_MetadataPointerDescriptor *metapd)
{
if (metapd) {
if (metapd->locator_data) gf_free(metapd->locator_data);
if (metapd->data) gf_free(metapd->data);
gf_free(metapd);
}
}
static GF_M2TS_MetadataDescriptor *gf_m2ts_read_metadata_descriptor(GF_BitStream *bs, u32 length)
{
u32 size;
GF_M2TS_MetadataDescriptor *d;
GF_SAFEALLOC(d, GF_M2TS_MetadataDescriptor);
if (!d) return NULL;
d->application_format = gf_bs_read_u16(bs);
size = 2;
if (d->application_format == 0xFFFF) {
d->application_format_identifier = gf_bs_read_u32(bs);
size += 4;
}
d->format = gf_bs_read_u8(bs);
size += 1;
if (d->format == 0xFF) {
d->format_identifier = gf_bs_read_u32(bs);
size += 4;
}
d->service_id = gf_bs_read_u8(bs);
d->decoder_config_flags = gf_bs_read_int(bs, 3);
d->dsmcc_flag = (gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE);
gf_bs_read_int(bs, 4); /* reserved */
size += 2;
if (d->dsmcc_flag) {
d->service_id_record_length = gf_bs_read_u8(bs);
d->service_id_record = (char *)gf_malloc(d->service_id_record_length);
size += 1 + d->service_id_record_length;
gf_bs_read_data(bs, d->service_id_record, d->service_id_record_length);
}
if (d->decoder_config_flags == 1) {
d->decoder_config_length = gf_bs_read_u8(bs);
d->decoder_config = (char *)gf_malloc(d->decoder_config_length);
size += 1 + d->decoder_config_length;
gf_bs_read_data(bs, d->decoder_config, d->decoder_config_length);
}
if (d->decoder_config_flags == 3) {
d->decoder_config_id_length = gf_bs_read_u8(bs);
d->decoder_config_id = (char *)gf_malloc(d->decoder_config_id_length);
size += 1 + d->decoder_config_id_length;
gf_bs_read_data(bs, d->decoder_config_id, d->decoder_config_id_length);
}
if (d->decoder_config_flags == 4) {
d->decoder_config_service_id = gf_bs_read_u8(bs);
size++;
}
return d;
}
static void gf_m2ts_process_pmt(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *pmt, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
u32 info_length, pos, desc_len, evt_type, nb_es,i;
u32 nb_sections;
u32 data_size;
u32 nb_hevc, nb_hevc_temp, nb_shvc, nb_shvc_temp, nb_mhvc, nb_mhvc_temp;
unsigned char *data;
GF_M2TS_Section *section;
GF_Err e = GF_OK;
/*wait for the last section */
if (!(status&GF_M2TS_TABLE_END)) return;
nb_es = 0;
/*skip if already received but no update detected (eg same data) */
if ((status&GF_M2TS_TABLE_REPEAT) && !(status&GF_M2TS_TABLE_UPDATE)) {
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program);
return;
}
if (pmt->sec->demux_restarted) {
pmt->sec->demux_restarted = 0;
return;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PMT Found or updated\n"));
nb_sections = gf_list_count(sections);
if (nb_sections > 1) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("PMT on multiple sections not supported\n"));
}
section = (GF_M2TS_Section *)gf_list_get(sections, 0);
data = section->data;
data_size = section->data_size;
pmt->program->pcr_pid = ((data[0] & 0x1f) << 8) | data[1];
info_length = ((data[2]&0xf)<<8) | data[3];
if (info_length != 0) {
/* ...Read Descriptors ... */
u8 tag, len;
u32 first_loop_len = 0;
tag = data[4];
len = data[5];
while (info_length > first_loop_len) {
if (tag == GF_M2TS_MPEG4_IOD_DESCRIPTOR) {
u32 size;
GF_BitStream *iod_bs;
iod_bs = gf_bs_new((char *)data+8, len-2, GF_BITSTREAM_READ);
if (pmt->program->pmt_iod) gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod);
e = gf_odf_parse_descriptor(iod_bs , (GF_Descriptor **) &pmt->program->pmt_iod, &size);
gf_bs_del(iod_bs );
if (e==GF_OK) {
/*remember program number for service/program selection*/
if (pmt->program->pmt_iod) pmt->program->pmt_iod->ServiceID = pmt->program->number;
/*if empty IOD (freebox case), discard it and use dynamic declaration of object*/
if (!gf_list_count(pmt->program->pmt_iod->ESDescriptors)) {
gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod);
pmt->program->pmt_iod = NULL;
}
}
} else if (tag == GF_M2TS_METADATA_POINTER_DESCRIPTOR) {
GF_BitStream *metadatapd_bs;
GF_M2TS_MetadataPointerDescriptor *metapd;
metadatapd_bs = gf_bs_new((char *)data+6, len, GF_BITSTREAM_READ);
metapd = gf_m2ts_read_metadata_pointer_descriptor(metadatapd_bs, len);
gf_bs_del(metadatapd_bs);
if (metapd->application_format_identifier == GF_M2TS_META_ID3 &&
metapd->format_identifier == GF_M2TS_META_ID3 &&
metapd->carriage_flag == METADATA_CARRIAGE_SAME_TS) {
/*HLS ID3 Metadata */
pmt->program->metadata_pointer_descriptor = metapd;
} else {
/* don't know what to do with it for now, delete */
gf_m2ts_metadata_pointer_descriptor_del(metapd);
}
} else {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Skipping descriptor (0x%x) and others not supported\n", tag));
}
first_loop_len += 2 + len;
}
}
if (data_size <= 4 + info_length) return;
data += 4 + info_length;
data_size -= 4 + info_length;
pos = 0;
/* count de number of program related PMT received */
for(i=0; i<gf_list_count(ts->programs); i++) {
GF_M2TS_Program *prog = (GF_M2TS_Program *)gf_list_get(ts->programs,i);
if(prog->pmt_pid == pmt->pid) {
break;
}
}
nb_hevc = nb_hevc_temp = nb_shvc = nb_shvc_temp = nb_mhvc = nb_mhvc_temp = 0;
while (pos<data_size) {
GF_M2TS_PES *pes = NULL;
GF_M2TS_SECTION_ES *ses = NULL;
GF_M2TS_ES *es = NULL;
Bool inherit_pcr = 0;
u32 pid, stream_type, reg_desc_format;
stream_type = data[0];
pid = ((data[1] & 0x1f) << 8) | data[2];
desc_len = ((data[3] & 0xf) << 8) | data[4];
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("stream_type :%d \n",stream_type));
switch (stream_type) {
/* PES */
case GF_M2TS_VIDEO_MPEG1:
case GF_M2TS_VIDEO_MPEG2:
case GF_M2TS_VIDEO_DCII:
case GF_M2TS_VIDEO_MPEG4:
case GF_M2TS_SYSTEMS_MPEG4_PES:
case GF_M2TS_VIDEO_H264:
case GF_M2TS_VIDEO_SVC:
case GF_M2TS_VIDEO_MVCD:
case GF_M2TS_VIDEO_HEVC:
case GF_M2TS_VIDEO_HEVC_MCTS:
case GF_M2TS_VIDEO_HEVC_TEMPORAL:
case GF_M2TS_VIDEO_SHVC:
case GF_M2TS_VIDEO_SHVC_TEMPORAL:
case GF_M2TS_VIDEO_MHVC:
case GF_M2TS_VIDEO_MHVC_TEMPORAL:
inherit_pcr = 1;
case GF_M2TS_AUDIO_MPEG1:
case GF_M2TS_AUDIO_MPEG2:
case GF_M2TS_AUDIO_AAC:
case GF_M2TS_AUDIO_LATM_AAC:
case GF_M2TS_AUDIO_AC3:
case GF_M2TS_AUDIO_DTS:
case GF_M2TS_MHAS_MAIN:
case GF_M2TS_MHAS_AUX:
case GF_M2TS_SUBTITLE_DVB:
case GF_M2TS_METADATA_PES:
GF_SAFEALLOC(pes, GF_M2TS_PES);
if (!pes) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
pes->cc = -1;
pes->flags = GF_M2TS_ES_IS_PES;
if (inherit_pcr)
pes->flags |= GF_M2TS_INHERIT_PCR;
es = (GF_M2TS_ES *)pes;
break;
case GF_M2TS_PRIVATE_DATA:
GF_SAFEALLOC(pes, GF_M2TS_PES);
if (!pes) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
pes->cc = -1;
pes->flags = GF_M2TS_ES_IS_PES;
es = (GF_M2TS_ES *)pes;
break;
/* Sections */
case GF_M2TS_SYSTEMS_MPEG4_SECTIONS:
GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES);
if (!ses) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
es = (GF_M2TS_ES *)ses;
es->flags |= GF_M2TS_ES_IS_SECTION;
/* carriage of ISO_IEC_14496 data in sections */
if (stream_type == GF_M2TS_SYSTEMS_MPEG4_SECTIONS) {
/*MPEG-4 sections need to be fully checked: if one section is lost, this means we lost
one SL packet in the AU so we must wait for the complete section again*/
ses->sec = gf_m2ts_section_filter_new(gf_m2ts_process_mpeg4section, 0);
/*create OD container*/
if (!pmt->program->additional_ods) {
pmt->program->additional_ods = gf_list_new();
ts->has_4on2 = 1;
}
}
break;
case GF_M2TS_13818_6_ANNEX_A:
case GF_M2TS_13818_6_ANNEX_B:
case GF_M2TS_13818_6_ANNEX_C:
case GF_M2TS_13818_6_ANNEX_D:
case GF_M2TS_PRIVATE_SECTION:
case GF_M2TS_QUALITY_SEC:
case GF_M2TS_MORE_SEC:
GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES);
if (!ses) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
es = (GF_M2TS_ES *)ses;
es->flags |= GF_M2TS_ES_IS_SECTION;
es->pid = pid;
es->service_id = pmt->program->number;
if (stream_type == GF_M2TS_PRIVATE_SECTION) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("AIT sections on pid %d\n", pid));
} else if (stream_type == GF_M2TS_QUALITY_SEC) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("Quality metadata sections on pid %d\n", pid));
} else if (stream_type == GF_M2TS_MORE_SEC) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("MORE sections on pid %d\n", pid));
} else {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("stream type DSM CC user private sections on pid %d \n", pid));
}
/* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */
ses->sec = gf_m2ts_section_filter_new(NULL, 1);
//ses->sec->service_id = pmt->program->number;
break;
case GF_M2TS_MPE_SECTIONS:
if (! ts->prefix_present) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("stream type MPE found : pid = %d \n", pid));
#ifdef GPAC_ENABLE_MPE
es = gf_dvb_mpe_section_new();
if (es->flags & GF_M2TS_ES_IS_SECTION) {
/* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */
((GF_M2TS_SECTION_ES*)es)->sec = gf_m2ts_section_filter_new(NULL, 1);
}
#endif
break;
}
default:
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
//GF_LOG(/*GF_LOG_WARNING*/GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
break;
}
if (es) {
es->stream_type = (stream_type==GF_M2TS_PRIVATE_DATA) ? 0 : stream_type;
es->program = pmt->program;
es->pid = pid;
es->component_tag = -1;
}
pos += 5;
data += 5;
while (desc_len) {
u8 tag = data[0];
u32 len = data[1];
if (es) {
switch (tag) {
case GF_M2TS_ISO_639_LANGUAGE_DESCRIPTOR:
if (pes)
pes->lang = GF_4CC(' ', data[2], data[3], data[4]);
break;
case GF_M2TS_MPEG4_SL_DESCRIPTOR:
es->mpeg4_es_id = ( (u32) data[2] & 0x1f) << 8 | data[3];
es->flags |= GF_M2TS_ES_IS_SL;
break;
case GF_M2TS_REGISTRATION_DESCRIPTOR:
reg_desc_format = GF_4CC(data[2], data[3], data[4], data[5]);
/*cf http://www.smpte-ra.org/mpegreg/mpegreg.html*/
switch (reg_desc_format) {
case GF_M2TS_RA_STREAM_AC3:
es->stream_type = GF_M2TS_AUDIO_AC3;
break;
case GF_M2TS_RA_STREAM_VC1:
es->stream_type = GF_M2TS_VIDEO_VC1;
break;
case GF_M2TS_RA_STREAM_GPAC:
if (len==8) {
es->stream_type = GF_4CC(data[6], data[7], data[8], data[9]);
es->flags |= GF_M2TS_GPAC_CODEC_ID;
break;
}
default:
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("Unknown registration descriptor %s\n", gf_4cc_to_str(reg_desc_format) ));
break;
}
break;
case GF_M2TS_DVB_EAC3_DESCRIPTOR:
es->stream_type = GF_M2TS_AUDIO_EC3;
break;
case GF_M2TS_DVB_DATA_BROADCAST_ID_DESCRIPTOR:
{
u32 id = data[2]<<8 | data[3];
if ((id == 0xB) && ses && !ses->sec) {
ses->sec = gf_m2ts_section_filter_new(NULL, 1);
}
}
break;
case GF_M2TS_DVB_SUBTITLING_DESCRIPTOR:
if (pes) {
pes->sub.language[0] = data[2];
pes->sub.language[1] = data[3];
pes->sub.language[2] = data[4];
pes->sub.type = data[5];
pes->sub.composition_page_id = (data[6]<<8) | data[7];
pes->sub.ancillary_page_id = (data[8]<<8) | data[9];
}
es->stream_type = GF_M2TS_DVB_SUBTITLE;
break;
case GF_M2TS_DVB_STREAM_IDENTIFIER_DESCRIPTOR:
{
es->component_tag = data[2];
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("Component Tag: %d on Program %d\n", es->component_tag, es->program->number));
}
break;
case GF_M2TS_DVB_TELETEXT_DESCRIPTOR:
es->stream_type = GF_M2TS_DVB_TELETEXT;
break;
case GF_M2TS_DVB_VBI_DATA_DESCRIPTOR:
es->stream_type = GF_M2TS_DVB_VBI;
break;
case GF_M2TS_HIERARCHY_DESCRIPTOR:
if (pes) {
u8 hierarchy_embedded_layer_index;
GF_BitStream *hbs = gf_bs_new((const char *)data, data_size, GF_BITSTREAM_READ);
/*u32 skip = */gf_bs_read_int(hbs, 16);
/*u8 res1 = */gf_bs_read_int(hbs, 1);
/*u8 temp_scal = */gf_bs_read_int(hbs, 1);
/*u8 spatial_scal = */gf_bs_read_int(hbs, 1);
/*u8 quality_scal = */gf_bs_read_int(hbs, 1);
/*u8 hierarchy_type = */gf_bs_read_int(hbs, 4);
/*u8 res2 = */gf_bs_read_int(hbs, 2);
/*u8 hierarchy_layer_index = */gf_bs_read_int(hbs, 6);
/*u8 tref_not_present = */gf_bs_read_int(hbs, 1);
/*u8 res3 = */gf_bs_read_int(hbs, 1);
hierarchy_embedded_layer_index = gf_bs_read_int(hbs, 6);
/*u8 res4 = */gf_bs_read_int(hbs, 2);
/*u8 hierarchy_channel = */gf_bs_read_int(hbs, 6);
gf_bs_del(hbs);
pes->depends_on_pid = 1+hierarchy_embedded_layer_index;
}
break;
case GF_M2TS_METADATA_DESCRIPTOR:
{
GF_BitStream *metadatad_bs;
GF_M2TS_MetadataDescriptor *metad;
metadatad_bs = gf_bs_new((char *)data+2, len, GF_BITSTREAM_READ);
metad = gf_m2ts_read_metadata_descriptor(metadatad_bs, len);
gf_bs_del(metadatad_bs);
if (metad->application_format_identifier == GF_M2TS_META_ID3 &&
metad->format_identifier == GF_M2TS_META_ID3) {
/*HLS ID3 Metadata */
if (pes) {
pes->metadata_descriptor = metad;
pes->stream_type = GF_M2TS_METADATA_ID3_HLS;
}
} else {
/* don't know what to do with it for now, delete */
gf_m2ts_metadata_descriptor_del(metad);
}
}
break;
default:
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] skipping descriptor (0x%x) not supported\n", tag));
break;
}
}
data += len+2;
pos += len+2;
if (desc_len < len+2) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Invalid PMT es descriptor size for PID %d\n", pid ) );
break;
}
desc_len-=len+2;
}
if (es && !es->stream_type) {
gf_free(es);
es = NULL;
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Private Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
}
if (!es) continue;
if (ts->ess[pid]) {
//this is component reuse across programs, overwrite the previously declared stream ...
if (status & GF_M2TS_TABLE_FOUND) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d reused across programs %d and %d, not completely supported\n", pid, ts->ess[pid]->program->number, es->program->number ) );
//add stream to program but don't reassign the pid table until the stream is playing (>GF_M2TS_PES_FRAMING_SKIP)
gf_list_add(pmt->program->streams, es);
if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP);
nb_es++;
//skip assignment below
es = NULL;
}
/*watchout for pmt update - FIXME this likely won't work in most cases*/
else {
GF_M2TS_ES *o_es = ts->ess[es->pid];
if ((o_es->stream_type == es->stream_type)
&& ((o_es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK) == (es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK))
&& (o_es->mpeg4_es_id == es->mpeg4_es_id)
&& ((o_es->flags & GF_M2TS_ES_IS_SECTION) || ((GF_M2TS_PES *)o_es)->lang == ((GF_M2TS_PES *)es)->lang)
) {
gf_free(es);
es = NULL;
} else {
gf_m2ts_es_del(o_es, ts);
ts->ess[es->pid] = NULL;
}
}
}
if (es) {
ts->ess[es->pid] = es;
gf_list_add(pmt->program->streams, es);
if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP);
nb_es++;
if (es->stream_type == GF_M2TS_VIDEO_HEVC) nb_hevc++;
else if (es->stream_type == GF_M2TS_VIDEO_HEVC_TEMPORAL) nb_hevc_temp++;
else if (es->stream_type == GF_M2TS_VIDEO_SHVC) nb_shvc++;
else if (es->stream_type == GF_M2TS_VIDEO_SHVC_TEMPORAL) nb_shvc_temp++;
else if (es->stream_type == GF_M2TS_VIDEO_MHVC) nb_mhvc++;
else if (es->stream_type == GF_M2TS_VIDEO_MHVC_TEMPORAL) nb_mhvc_temp++;
}
}
//Table 2-139, implied hierarchy indexes
if (nb_hevc_temp + nb_shvc + nb_shvc_temp + nb_mhvc+ nb_mhvc_temp) {
for (i=0; i<gf_list_count(pmt->program->streams); i++) {
GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i);
if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue;
if (es->depends_on_pid) continue;
switch (es->stream_type) {
case GF_M2TS_VIDEO_HEVC_TEMPORAL:
es->depends_on_pid = 1;
break;
case GF_M2TS_VIDEO_SHVC:
if (!nb_hevc_temp) es->depends_on_pid = 1;
else es->depends_on_pid = 2;
break;
case GF_M2TS_VIDEO_SHVC_TEMPORAL:
es->depends_on_pid = 3;
break;
case GF_M2TS_VIDEO_MHVC:
if (!nb_hevc_temp) es->depends_on_pid = 1;
else es->depends_on_pid = 2;
break;
case GF_M2TS_VIDEO_MHVC_TEMPORAL:
if (!nb_hevc_temp) es->depends_on_pid = 2;
else es->depends_on_pid = 3;
break;
}
}
}
if (nb_es) {
u32 i;
//translate hierarchy descriptors indexes into PIDs - check whether the PMT-index rules are the same for HEVC
for (i=0; i<gf_list_count(pmt->program->streams); i++) {
GF_M2TS_PES *an_es = NULL;
GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i);
if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue;
if (!es->depends_on_pid) continue;
//fixeme we are not always assured that hierarchy_layer_index matches the stream index...
//+1 is because our first stream is the PMT
an_es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, es->depends_on_pid);
if (an_es) {
es->depends_on_pid = an_es->pid;
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[M2TS] Wrong dependency index in hierarchy descriptor, assuming non-scalable stream\n"));
es->depends_on_pid = 0;
}
}
evt_type = (status&GF_M2TS_TABLE_FOUND) ? GF_M2TS_EVT_PMT_FOUND : GF_M2TS_EVT_PMT_UPDATE;
if (ts->on_event) ts->on_event(ts, evt_type, pmt->program);
} else {
/* if we found no new ES it's simply a repeat of the PMT */
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program);
}
}
static void gf_m2ts_process_pat(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *ses, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
GF_M2TS_Program *prog;
GF_M2TS_SECTION_ES *pmt;
u32 i, nb_progs, evt_type;
u32 nb_sections;
u32 data_size;
unsigned char *data;
GF_M2TS_Section *section;
/*wait for the last section */
if (!(status&GF_M2TS_TABLE_END)) return;
/*skip if already received*/
if (status&GF_M2TS_TABLE_REPEAT) {
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PAT_REPEAT, NULL);
return;
}
nb_sections = gf_list_count(sections);
if (nb_sections > 1) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("PAT on multiple sections not supported\n"));
}
section = (GF_M2TS_Section *)gf_list_get(sections, 0);
data = section->data;
data_size = section->data_size;
if (!(status&GF_M2TS_TABLE_UPDATE) && gf_list_count(ts->programs)) {
if (ts->pat->demux_restarted) {
ts->pat->demux_restarted = 0;
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Multiple different PAT on single TS found, ignoring new PAT declaration (table id %d - extended table id %d)\n", table_id, ex_table_id));
}
return;
}
nb_progs = data_size / 4;
for (i=0; i<nb_progs; i++) {
u16 number, pid;
number = (data[0]<<8) | data[1];
pid = (data[2]&0x1f)<<8 | data[3];
data += 4;
if (number==0) {
if (!ts->nit) {
ts->nit = gf_m2ts_section_filter_new(gf_m2ts_process_nit, 0);
}
} else {
GF_SAFEALLOC(prog, GF_M2TS_Program);
if (!prog) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Fail to allocate program for pid %d\n", pid));
return;
}
prog->streams = gf_list_new();
prog->pmt_pid = pid;
prog->number = number;
prog->ts = ts;
gf_list_add(ts->programs, prog);
GF_SAFEALLOC(pmt, GF_M2TS_SECTION_ES);
if (!pmt) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Fail to allocate pmt filter for pid %d\n", pid));
return;
}
pmt->flags = GF_M2TS_ES_IS_SECTION;
gf_list_add(prog->streams, pmt);
pmt->pid = prog->pmt_pid;
pmt->program = prog;
ts->ess[pmt->pid] = (GF_M2TS_ES *)pmt;
pmt->sec = gf_m2ts_section_filter_new(gf_m2ts_process_pmt, 0);
}
}
evt_type = (status&GF_M2TS_TABLE_UPDATE) ? GF_M2TS_EVT_PAT_UPDATE : GF_M2TS_EVT_PAT_FOUND;
if (ts->on_event) ts->on_event(ts, evt_type, NULL);
}
static void gf_m2ts_process_cat(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *ses, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
u32 evt_type;
/*
GF_M2TS_Program *prog;
GF_M2TS_SECTION_ES *pmt;
u32 i, nb_progs;
u32 nb_sections;
u32 data_size;
unsigned char *data;
GF_M2TS_Section *section;
*/
/*wait for the last section */
if (!(status&GF_M2TS_TABLE_END)) return;
/*skip if already received*/
if (status&GF_M2TS_TABLE_REPEAT) {
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_CAT_REPEAT, NULL);
return;
}
/*
nb_sections = gf_list_count(sections);
if (nb_sections > 1) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("CAT on multiple sections not supported\n"));
}
section = (GF_M2TS_Section *)gf_list_get(sections, 0);
data = section->data;
data_size = section->data_size;
nb_progs = data_size / 4;
for (i=0; i<nb_progs; i++) {
u16 number, pid;
number = (data[0]<<8) | data[1];
pid = (data[2]&0x1f)<<8 | data[3];
data += 4;
if (number==0) {
if (!ts->nit) {
ts->nit = gf_m2ts_section_filter_new(gf_m2ts_process_nit, 0);
}
} else {
GF_SAFEALLOC(prog, GF_M2TS_Program);
prog->streams = gf_list_new();
prog->pmt_pid = pid;
prog->number = number;
gf_list_add(ts->programs, prog);
GF_SAFEALLOC(pmt, GF_M2TS_SECTION_ES);
pmt->flags = GF_M2TS_ES_IS_SECTION;
gf_list_add(prog->streams, pmt);
pmt->pid = prog->pmt_pid;
pmt->program = prog;
ts->ess[pmt->pid] = (GF_M2TS_ES *)pmt;
pmt->sec = gf_m2ts_section_filter_new(gf_m2ts_process_pmt, 0);
}
}
*/
evt_type = (status&GF_M2TS_TABLE_UPDATE) ? GF_M2TS_EVT_CAT_UPDATE : GF_M2TS_EVT_CAT_FOUND;
if (ts->on_event) ts->on_event(ts, evt_type, NULL);
}
u64 gf_m2ts_get_pts(unsigned char *data)
{
u64 pts;
u32 val;
pts = (u64)((data[0] >> 1) & 0x07) << 30;
val = (data[1] << 8) | data[2];
pts |= (u64)(val >> 1) << 15;
val = (data[3] << 8) | data[4];
pts |= (u64)(val >> 1);
return pts;
}
void gf_m2ts_pes_header(GF_M2TS_PES *pes, unsigned char *data, u32 data_size, GF_M2TS_PESHeader *pesh)
{
u32 has_pts, has_dts;
u32 len_check;
memset(pesh, 0, sizeof(GF_M2TS_PESHeader));
len_check = 0;
pesh->id = data[0];
pesh->pck_len = (data[1]<<8) | data[2];
/*
2bits
scrambling_control = gf_bs_read_int(bs,2);
priority = gf_bs_read_int(bs,1);
*/
pesh->data_alignment = (data[3] & 0x4) ? 1 : 0;
/*
copyright = gf_bs_read_int(bs,1);
original = gf_bs_read_int(bs,1);
*/
has_pts = (data[4]&0x80);
has_dts = has_pts ? (data[4]&0x40) : 0;
/*
ESCR_flag = gf_bs_read_int(bs,1);
ES_rate_flag = gf_bs_read_int(bs,1);
DSM_flag = gf_bs_read_int(bs,1);
additional_copy_flag = gf_bs_read_int(bs,1);
prev_crc_flag = gf_bs_read_int(bs,1);
extension_flag = gf_bs_read_int(bs,1);
*/
pesh->hdr_data_len = data[5];
data += 6;
if (has_pts) {
pesh->PTS = gf_m2ts_get_pts(data);
data+=5;
len_check += 5;
}
if (has_dts) {
pesh->DTS = gf_m2ts_get_pts(data);
//data+=5;
len_check += 5;
} else {
pesh->DTS = pesh->PTS;
}
if (len_check < pesh->hdr_data_len) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d Skipping %d bytes in pes header\n", pes->pid, pesh->hdr_data_len - len_check));
} else if (len_check > pesh->hdr_data_len) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d Wrong pes_header_data_length field %d bytes - read %d\n", pes->pid, pesh->hdr_data_len, len_check));
}
if ((pesh->PTS<90000) && ((s32)pesh->DTS<0)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d Wrong DTS %d negative for PTS %d - forcing to 0\n", pes->pid, pesh->DTS, pesh->PTS));
pesh->DTS=0;
}
}
static void gf_m2ts_store_temi(GF_M2TS_Demuxer *ts, GF_M2TS_PES *pes)
{
GF_BitStream *bs = gf_bs_new(pes->temi_tc_desc, pes->temi_tc_desc_len, GF_BITSTREAM_READ);
u32 has_timestamp = gf_bs_read_int(bs, 2);
Bool has_ntp = (Bool) gf_bs_read_int(bs, 1);
/*u32 has_ptp = */gf_bs_read_int(bs, 1);
/*u32 has_timecode = */gf_bs_read_int(bs, 2);
memset(&pes->temi_tc, 0, sizeof(GF_M2TS_TemiTimecodeDescriptor));
pes->temi_tc.force_reload = gf_bs_read_int(bs, 1);
pes->temi_tc.is_paused = gf_bs_read_int(bs, 1);
pes->temi_tc.is_discontinuity = gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 7);
pes->temi_tc.timeline_id = gf_bs_read_int(bs, 8);
if (has_timestamp) {
pes->temi_tc.media_timescale = gf_bs_read_u32(bs);
if (has_timestamp==2)
pes->temi_tc.media_timestamp = gf_bs_read_u64(bs);
else
pes->temi_tc.media_timestamp = gf_bs_read_u32(bs);
}
if (has_ntp) {
pes->temi_tc.ntp = gf_bs_read_u64(bs);
}
gf_bs_del(bs);
pes->temi_tc_desc_len = 0;
pes->temi_pending = 1;
}
void gf_m2ts_flush_pes(GF_M2TS_Demuxer *ts, GF_M2TS_PES *pes)
{
GF_M2TS_PESHeader pesh;
if (!ts) return;
/*we need at least a full, valid start code and PES header !!*/
if ((pes->pck_data_len >= 4) && !pes->pck_data[0] && !pes->pck_data[1] && (pes->pck_data[2] == 0x1)) {
u32 len;
Bool has_pes_header = GF_TRUE;
u32 stream_id = pes->pck_data[3];
Bool same_pts = GF_FALSE;
switch (stream_id) {
case GF_M2_STREAMID_PROGRAM_STREAM_MAP:
case GF_M2_STREAMID_PADDING:
case GF_M2_STREAMID_PRIVATE_2:
case GF_M2_STREAMID_ECM:
case GF_M2_STREAMID_EMM:
case GF_M2_STREAMID_PROGRAM_STREAM_DIRECTORY:
case GF_M2_STREAMID_DSMCC:
case GF_M2_STREAMID_H222_TYPE_E:
has_pes_header = GF_FALSE;
break;
}
if (has_pes_header) {
/*OK read header*/
gf_m2ts_pes_header(pes, pes->pck_data + 3, pes->pck_data_len - 3, &pesh);
/*send PES timing*/
if (ts->notify_pes_timing) {
GF_M2TS_PES_PCK pck;
memset(&pck, 0, sizeof(GF_M2TS_PES_PCK));
pck.PTS = pesh.PTS;
pck.DTS = pesh.DTS;
pck.stream = pes;
if (pes->rap) pck.flags |= GF_M2TS_PES_PCK_RAP;
pes->pes_end_packet_number = ts->pck_number;
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PES_TIMING, &pck);
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d Got PES header DTS %d PTS %d\n", pes->pid, pesh.DTS, pesh.PTS));
if (pesh.PTS) {
if (pesh.PTS == pes->PTS) {
same_pts = GF_TRUE;
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d - same PTS "LLU" for two consecutive PES packets \n", pes->pid, pes->PTS));
}
#ifndef GPAC_DISABLE_LOG
/*FIXME - this test should only be done for non bi-directionnally coded media
else if (pesh.PTS < pes->PTS) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d - PTS "LLU" less than previous packet PTS "LLU"\n", pes->pid, pesh.PTS, pes->PTS) );
}
*/
#endif
pes->PTS = pesh.PTS;
#ifndef GPAC_DISABLE_LOG
{
if (pes->DTS && (pesh.DTS == pes->DTS)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d - same DTS "LLU" for two consecutive PES packets \n", pes->pid, pes->DTS));
}
if (pesh.DTS < pes->DTS) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d - DTS "LLU" less than previous DTS "LLU"\n", pes->pid, pesh.DTS, pes->DTS));
}
}
#endif
pes->DTS = pesh.DTS;
}
/*no PTSs were coded, same time*/
else if (!pesh.hdr_data_len) {
same_pts = GF_TRUE;
}
/*3-byte start-code + 6 bytes header + hdr extensions*/
len = 9 + pesh.hdr_data_len;
} else {
/*3-byte start-code + 1 byte streamid*/
len = 4;
memset(&pesh, 0, sizeof(pesh));
}
if ((u8) pes->pck_data[3]==0xfa) {
GF_M2TS_SL_PCK sl_pck;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] SL Packet in PES for %d - ES ID %d\n", pes->pid, pes->mpeg4_es_id));
if (pes->pck_data_len > len) {
sl_pck.data = (char *)pes->pck_data + len;
sl_pck.data_len = pes->pck_data_len - len;
sl_pck.stream = (GF_M2TS_ES *)pes;
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_SL_PCK, &sl_pck);
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Bad SL Packet size: (%d indicated < %d header)\n", pes->pid, pes->pck_data_len, len));
}
} else if (pes->reframe) {
u32 remain = 0;
u32 offset = len;
if (pesh.pck_len && (pesh.pck_len-3-pesh.hdr_data_len != pes->pck_data_len-len)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PES payload size %d but received %d bytes\n", pes->pid, (u32) ( pesh.pck_len-3-pesh.hdr_data_len), pes->pck_data_len-len));
}
//copy over the remaining of previous PES payload before start of this PES payload
if (pes->prev_data_len) {
if (pes->prev_data_len < len) {
offset = len - pes->prev_data_len;
memcpy(pes->pck_data + offset, pes->prev_data, pes->prev_data_len);
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PES reassembly buffer overflow (%d bytes not processed from previous PES) - discarding prev data\n", pes->pid, pes->prev_data_len ));
}
}
if (!pes->temi_pending && pes->temi_tc_desc_len) {
gf_m2ts_store_temi(ts, pes);
}
if (pes->temi_pending) {
pes->temi_pending = 0;
pes->temi_tc.pes_pts = pes->PTS;
if (ts->on_event)
ts->on_event(ts, GF_M2TS_EVT_TEMI_TIMECODE, &pes->temi_tc);
}
if (! ts->seek_mode)
remain = pes->reframe(ts, pes, same_pts, pes->pck_data+offset, pes->pck_data_len-offset, &pesh);
//CLEANUP alloc stuff
if (pes->prev_data) gf_free(pes->prev_data);
pes->prev_data = NULL;
pes->prev_data_len = 0;
if (remain) {
pes->prev_data = gf_malloc(sizeof(char)*remain);
assert(pes->pck_data_len >= remain);
memcpy(pes->prev_data, pes->pck_data + pes->pck_data_len - remain, remain);
pes->prev_data_len = remain;
}
}
} else if (pes->pck_data_len) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PES %d: Bad PES Header, discarding packet (maybe stream is encrypted ?)\n", pes->pid));
}
pes->pck_data_len = 0;
pes->pes_len = 0;
pes->rap = 0;
}
static void gf_m2ts_process_pes(GF_M2TS_Demuxer *ts, GF_M2TS_PES *pes, GF_M2TS_Header *hdr, unsigned char *data, u32 data_size, GF_M2TS_AdaptationField *paf)
{
u8 expect_cc;
Bool disc=0;
Bool flush_pes = 0;
/*duplicated packet, NOT A DISCONTINUITY, we should discard the packet - however we may encounter this configuration in DASH at segment boundaries.
If payload start is set, ignore duplication*/
if (hdr->continuity_counter==pes->cc) {
if (!hdr->payload_start || (hdr->adaptation_field!=3) ) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[MPEG-2 TS] PES %d: Duplicated Packet found (CC %d) - skipping\n", pes->pid, pes->cc));
return;
}
} else {
expect_cc = (pes->cc<0) ? hdr->continuity_counter : (pes->cc + 1) & 0xf;
if (expect_cc != hdr->continuity_counter)
disc = 1;
}
pes->cc = hdr->continuity_counter;
if (disc) {
if (pes->flags & GF_M2TS_ES_IGNORE_NEXT_DISCONTINUITY) {
pes->flags &= ~GF_M2TS_ES_IGNORE_NEXT_DISCONTINUITY;
disc = 0;
}
if (disc) {
if (hdr->payload_start) {
if (pes->pck_data_len) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PES %d: Packet discontinuity (%d expected - got %d) - may have lost end of previous PES\n", pes->pid, expect_cc, hdr->continuity_counter));
}
} else {
if (pes->pck_data_len) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] PES %d: Packet discontinuity (%d expected - got %d) - trashing PES packet\n", pes->pid, expect_cc, hdr->continuity_counter));
}
pes->pck_data_len = 0;
pes->pes_len = 0;
pes->cc = -1;
return;
}
}
}
if (!pes->reframe) return;
if (hdr->payload_start) {
flush_pes = 1;
pes->pes_start_packet_number = ts->pck_number;
pes->before_last_pcr_value = pes->program->before_last_pcr_value;
pes->before_last_pcr_value_pck_number = pes->program->before_last_pcr_value_pck_number;
pes->last_pcr_value = pes->program->last_pcr_value;
pes->last_pcr_value_pck_number = pes->program->last_pcr_value_pck_number;
} else if (pes->pes_len && (pes->pck_data_len + data_size == pes->pes_len + 6)) {
/* 6 = startcode+stream_id+length*/
/*reassemble pes*/
if (pes->pck_data_len + data_size > pes->pck_alloc_len) {
pes->pck_alloc_len = pes->pck_data_len + data_size;
pes->pck_data = (u8*)gf_realloc(pes->pck_data, pes->pck_alloc_len);
}
memcpy(pes->pck_data+pes->pck_data_len, data, data_size);
pes->pck_data_len += data_size;
/*force discard*/
data_size = 0;
flush_pes = 1;
}
/*PES first fragment: flush previous packet*/
if (flush_pes && pes->pck_data_len) {
gf_m2ts_flush_pes(ts, pes);
if (!data_size) return;
}
/*we need to wait for first packet of PES*/
if (!pes->pck_data_len && !hdr->payload_start) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Waiting for PES header, trashing data\n", hdr->pid));
return;
}
/*reassemble*/
if (pes->pck_data_len + data_size > pes->pck_alloc_len ) {
pes->pck_alloc_len = pes->pck_data_len + data_size;
pes->pck_data = (u8*)gf_realloc(pes->pck_data, pes->pck_alloc_len);
}
memcpy(pes->pck_data + pes->pck_data_len, data, data_size);
pes->pck_data_len += data_size;
if (paf && paf->random_access_indicator) pes->rap = 1;
if (hdr->payload_start && !pes->pes_len && (pes->pck_data_len>=6)) {
pes->pes_len = (pes->pck_data[4]<<8) | pes->pck_data[5];
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Got PES packet len %d\n", pes->pid, pes->pes_len));
if (pes->pes_len + 6 == pes->pck_data_len) {
gf_m2ts_flush_pes(ts, pes);
}
}
}
static void gf_m2ts_get_adaptation_field(GF_M2TS_Demuxer *ts, GF_M2TS_AdaptationField *paf, unsigned char *data, u32 size, u32 pid)
{
unsigned char *af_extension;
paf->discontinuity_indicator = (data[0] & 0x80) ? 1 : 0;
paf->random_access_indicator = (data[0] & 0x40) ? 1 : 0;
paf->priority_indicator = (data[0] & 0x20) ? 1 : 0;
paf->PCR_flag = (data[0] & 0x10) ? 1 : 0;
paf->OPCR_flag = (data[0] & 0x8) ? 1 : 0;
paf->splicing_point_flag = (data[0] & 0x4) ? 1 : 0;
paf->transport_private_data_flag = (data[0] & 0x2) ? 1 : 0;
paf->adaptation_field_extension_flag = (data[0] & 0x1) ? 1 : 0;
af_extension = data + 1;
if (paf->PCR_flag == 1) {
u32 base = ((u32)data[1] << 24) | ((u32)data[2] << 16) | ((u32)data[3] << 8) | (u32)data[4];
u64 PCR = (u64) base;
paf->PCR_base = (PCR << 1) | (data[5] >> 7);
paf->PCR_ext = ((data[5] & 1) << 8) | data[6];
af_extension += 6;
}
if (paf->adaptation_field_extension_flag) {
u32 afext_bytes;
Bool ltw_flag, pwr_flag, seamless_flag, af_desc_not_present;
if (paf->OPCR_flag) {
af_extension += 6;
}
if (paf->splicing_point_flag) {
af_extension += 1;
}
if (paf->transport_private_data_flag) {
u32 priv_bytes = af_extension[0];
af_extension += 1 + priv_bytes;
}
afext_bytes = af_extension[0];
ltw_flag = af_extension[1] & 0x80 ? 1 : 0;
pwr_flag = af_extension[1] & 0x40 ? 1 : 0;
seamless_flag = af_extension[1] & 0x20 ? 1 : 0;
af_desc_not_present = af_extension[1] & 0x10 ? 1 : 0;
af_extension += 2;
if (!afext_bytes) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Bad Adaptation Extension found\n", pid));
return;
}
afext_bytes-=1;
if (ltw_flag) {
af_extension += 2;
if (afext_bytes<2) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Bad Adaptation Extension found\n", pid));
return;
}
afext_bytes-=2;
}
if (pwr_flag) {
af_extension += 3;
if (afext_bytes<3) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Bad Adaptation Extension found\n", pid));
return;
}
afext_bytes-=3;
}
if (seamless_flag) {
af_extension += 3;
if (afext_bytes<3) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Bad Adaptation Extension found\n", pid));
return;
}
afext_bytes-=3;
}
if (! af_desc_not_present) {
while (afext_bytes) {
GF_BitStream *bs;
char *desc;
u8 desc_tag = af_extension[0];
u8 desc_len = af_extension[1];
if (!desc_len || (u32) desc_len+2 > afext_bytes) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Bad Adaptation Descriptor found (tag %d) size is %d but only %d bytes available\n", pid, desc_tag, desc_len, afext_bytes));
break;
}
desc = (char *) af_extension+2;
bs = gf_bs_new(desc, desc_len, GF_BITSTREAM_READ);
switch (desc_tag) {
case GF_M2TS_AFDESC_LOCATION_DESCRIPTOR:
{
Bool use_base_temi_url;
char URL[255];
GF_M2TS_TemiLocationDescriptor temi_loc;
memset(&temi_loc, 0, sizeof(GF_M2TS_TemiLocationDescriptor) );
temi_loc.reload_external = gf_bs_read_int(bs, 1);
temi_loc.is_announce = gf_bs_read_int(bs, 1);
temi_loc.is_splicing = gf_bs_read_int(bs, 1);
use_base_temi_url = gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 5); //reserved
temi_loc.timeline_id = gf_bs_read_int(bs, 7);
if (!use_base_temi_url) {
char *_url = URL;
u8 scheme = gf_bs_read_int(bs, 8);
u8 url_len = gf_bs_read_int(bs, 8);
switch (scheme) {
case 1:
strcpy(URL, "http://");
_url = URL+7;
break;
case 2:
strcpy(URL, "https://");
_url = URL+8;
break;
}
gf_bs_read_data(bs, _url, url_len);
_url[url_len] = 0;
}
temi_loc.external_URL = URL;
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d AF Location descriptor found - URL %s\n", pid, URL));
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_TEMI_LOCATION, &temi_loc);
}
break;
case GF_M2TS_AFDESC_TIMELINE_DESCRIPTOR:
if (ts->ess[pid] && (ts->ess[pid]->flags & GF_M2TS_ES_IS_PES)) {
GF_M2TS_PES *pes = (GF_M2TS_PES *) ts->ess[pid];
if (pes->temi_tc_desc_len)
gf_m2ts_store_temi(ts, pes);
if (pes->temi_tc_desc_alloc_size < desc_len) {
pes->temi_tc_desc = gf_realloc(pes->temi_tc_desc, desc_len);
pes->temi_tc_desc_alloc_size = desc_len;
}
memcpy(pes->temi_tc_desc, desc, desc_len);
pes->temi_tc_desc_len = desc_len;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d AF Timeline descriptor found\n", pid));
}
break;
}
gf_bs_del(bs);
af_extension += 2+desc_len;
afext_bytes -= 2+desc_len;
}
}
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Adaptation Field found: Discontinuity %d - RAP %d - PCR: "LLD"\n", pid, paf->discontinuity_indicator, paf->random_access_indicator, paf->PCR_flag ? paf->PCR_base * 300 + paf->PCR_ext : 0));
}
static GF_Err gf_m2ts_process_packet(GF_M2TS_Demuxer *ts, unsigned char *data)
{
GF_M2TS_ES *es;
GF_M2TS_Header hdr;
GF_M2TS_AdaptationField af, *paf;
u32 payload_size, af_size;
u32 pos = 0;
ts->pck_number++;
/* read TS packet header*/
hdr.sync = data[0];
if (hdr.sync != 0x47) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] TS Packet %d does not start with sync marker\n", ts->pck_number));
return GF_CORRUPTED_DATA;
}
hdr.error = (data[1] & 0x80) ? 1 : 0;
hdr.payload_start = (data[1] & 0x40) ? 1 : 0;
hdr.priority = (data[1] & 0x20) ? 1 : 0;
hdr.pid = ( (data[1]&0x1f) << 8) | data[2];
hdr.scrambling_ctrl = (data[3] >> 6) & 0x3;
hdr.adaptation_field = (data[3] >> 4) & 0x3;
hdr.continuity_counter = data[3] & 0xf;
if (hdr.error) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] TS Packet %d has error (PID could be %d)\n", ts->pck_number, hdr.pid));
return GF_CORRUPTED_DATA;
}
//#if DEBUG_TS_PACKET
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] TS Packet %d PID %d CC %d Encrypted %d\n", ts->pck_number, hdr.pid, hdr.continuity_counter, hdr.scrambling_ctrl));
//#endif
if (hdr.scrambling_ctrl) {
//TODO add decyphering
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] TS Packet %d is scrambled - not supported\n", ts->pck_number, hdr.pid));
return GF_NOT_SUPPORTED;
}
paf = NULL;
payload_size = 184;
pos = 4;
switch (hdr.adaptation_field) {
/*adaptation+data*/
case 3:
af_size = data[4];
if (af_size>183) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] TS Packet %d AF field larger than 183 !\n", ts->pck_number));
//error
return GF_CORRUPTED_DATA;
}
paf = ⁡
memset(paf, 0, sizeof(GF_M2TS_AdaptationField));
//this will stop you when processing invalid (yet existing) mpeg2ts streams in debug
assert( af_size<=183);
if (af_size>183)
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] TS Packet %d Detected wrong adaption field size %u when control value is 3\n", ts->pck_number, af_size));
if (af_size) gf_m2ts_get_adaptation_field(ts, paf, data+5, af_size, hdr.pid);
pos += 1+af_size;
payload_size = 183 - af_size;
break;
/*adaptation only - still process in case of PCR*/
case 2:
af_size = data[4];
if (af_size != 183) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] TS Packet %d AF size is %d when it must be 183 for AF type 2\n", ts->pck_number, af_size));
return GF_CORRUPTED_DATA;
}
paf = ⁡
memset(paf, 0, sizeof(GF_M2TS_AdaptationField));
gf_m2ts_get_adaptation_field(ts, paf, data+5, af_size, hdr.pid);
payload_size = 0;
/*no payload and no PCR, return*/
if (!paf->PCR_flag)
return GF_OK;
break;
/*reserved*/
case 0:
return GF_OK;
default:
break;
}
data += pos;
/*PAT*/
if (hdr.pid == GF_M2TS_PID_PAT) {
gf_m2ts_gather_section(ts, ts->pat, NULL, &hdr, data, payload_size);
return GF_OK;
} else if (hdr.pid == GF_M2TS_PID_CAT) {
gf_m2ts_gather_section(ts, ts->cat, NULL, &hdr, data, payload_size);
return GF_OK;
}
es = ts->ess[hdr.pid];
if (paf && paf->PCR_flag) {
if (!es) {
u32 i, j;
for(i=0; i<gf_list_count(ts->programs); i++) {
GF_M2TS_PES *first_pes = NULL;
GF_M2TS_Program *program = (GF_M2TS_Program *)gf_list_get(ts->programs,i);
if(program->pcr_pid != hdr.pid) continue;
for (j=0; j<gf_list_count(program->streams); j++) {
GF_M2TS_PES *pes = (GF_M2TS_PES *) gf_list_get(program->streams, j);
if (pes->flags & GF_M2TS_INHERIT_PCR) {
ts->ess[hdr.pid] = (GF_M2TS_ES *) pes;
pes->flags |= GF_M2TS_FAKE_PCR;
break;
}
if (pes->flags & GF_M2TS_ES_IS_PES) {
first_pes = pes;
}
}
//non found, use the first media stream as a PCR destination - Q: is it legal to have PCR only streams not declared in PMT ?
if (!es && first_pes) {
es = (GF_M2TS_ES *) first_pes;
first_pes->flags |= GF_M2TS_FAKE_PCR;
}
break;
}
if (!es)
es = ts->ess[hdr.pid];
}
if (es) {
GF_M2TS_PES_PCK pck;
s64 prev_diff_in_us;
Bool discontinuity;
s32 cc = -1;
if (es->flags & GF_M2TS_FAKE_PCR) {
cc = es->program->pcr_cc;
es->program->pcr_cc = hdr.continuity_counter;
}
else if (es->flags & GF_M2TS_ES_IS_PES) cc = ((GF_M2TS_PES*)es)->cc;
else if (((GF_M2TS_SECTION_ES*)es)->sec) cc = ((GF_M2TS_SECTION_ES*)es)->sec->cc;
discontinuity = paf->discontinuity_indicator;
if ((cc>=0) && es->program->before_last_pcr_value) {
//no increment of CC if AF only packet
if (hdr.adaptation_field == 2) {
if (hdr.continuity_counter != cc) {
discontinuity = GF_TRUE;
}
} else if (hdr.continuity_counter != ((cc + 1) & 0xF)) {
discontinuity = GF_TRUE;
}
}
memset(&pck, 0, sizeof(GF_M2TS_PES_PCK));
prev_diff_in_us = (s64) (es->program->last_pcr_value /27- es->program->before_last_pcr_value/27);
es->program->before_last_pcr_value = es->program->last_pcr_value;
es->program->before_last_pcr_value_pck_number = es->program->last_pcr_value_pck_number;
es->program->last_pcr_value_pck_number = ts->pck_number;
es->program->last_pcr_value = paf->PCR_base * 300 + paf->PCR_ext;
if (!es->program->last_pcr_value) es->program->last_pcr_value = 1;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PCR found "LLU" ("LLU" at 90kHz) - PCR diff is %d us\n", hdr.pid, es->program->last_pcr_value, es->program->last_pcr_value/300, (s32) (es->program->last_pcr_value - es->program->before_last_pcr_value)/27 ));
pck.PTS = es->program->last_pcr_value;
pck.stream = (GF_M2TS_PES *)es;
//try to ignore all discontinuities that are less than 200 ms (seen in some HLS setup ...)
if (discontinuity) {
s64 diff_in_us = (s64) (es->program->last_pcr_value - es->program->before_last_pcr_value) / 27;
u64 diff = ABS(diff_in_us - prev_diff_in_us);
if ((diff_in_us<0) && (diff_in_us >= -200000)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d new PCR, with discontinuity signaled, is less than previously received PCR (diff %d us) but not too large, trying to ignore discontinuity\n", hdr.pid, diff_in_us));
}
//ignore PCR discontinuity indicator if PCR found is larger than previously received PCR and diffence between PCR before and after discontinuity indicator is smaller than 50ms
else if ((diff_in_us > 0) && (diff < 200000)) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PCR discontinuity signaled but diff is small (diff %d us - PCR diff %d vs prev PCR diff %d) - ignore it\n", hdr.pid, diff, diff_in_us, prev_diff_in_us));
} else if (paf->discontinuity_indicator) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PCR discontinuity signaled (diff %d us - PCR diff %d vs prev PCR diff %d)\n", hdr.pid, diff, diff_in_us, prev_diff_in_us));
pck.flags = GF_M2TS_PES_PCK_DISCONTINUITY;
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PCR discontinuity not signaled (diff %d us - PCR diff %d vs prev PCR diff %d)\n", hdr.pid, diff, diff_in_us, prev_diff_in_us));
pck.flags = GF_M2TS_PES_PCK_DISCONTINUITY;
}
}
else if ( (es->program->last_pcr_value < es->program->before_last_pcr_value) ) {
s64 diff_in_us = (s64) (es->program->last_pcr_value - es->program->before_last_pcr_value) / 27;
//if less than 200 ms before PCR loop at the last PCR, this is a PCR loop
if (GF_M2TS_MAX_PCR - es->program->before_last_pcr_value < 5400000 /*2*2700000*/) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PCR loop found from "LLU" to "LLU" \n", hdr.pid, es->program->before_last_pcr_value, es->program->last_pcr_value));
} else if ((diff_in_us<0) && (diff_in_us >= -200000)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d new PCR, without discontinuity signaled, is less than previously received PCR (diff %d us) but not too large, trying to ignore discontinuity\n", hdr.pid, diff_in_us));
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PCR found "LLU" is less than previously received PCR "LLU" (PCR diff %g sec) but no discontinuity signaled\n", hdr.pid, es->program->last_pcr_value, es->program->before_last_pcr_value, (GF_M2TS_MAX_PCR - es->program->before_last_pcr_value + es->program->last_pcr_value) / 27000000.0));
pck.flags = GF_M2TS_PES_PCK_DISCONTINUITY;
}
}
if (pck.flags & GF_M2TS_PES_PCK_DISCONTINUITY) {
gf_m2ts_reset_parsers_for_program(ts, es->program);
}
if (ts->on_event) {
ts->on_event(ts, GF_M2TS_EVT_PES_PCR, &pck);
}
}
}
/*check for DVB reserved PIDs*/
if (!es) {
if (hdr.pid == GF_M2TS_PID_SDT_BAT_ST) {
gf_m2ts_gather_section(ts, ts->sdt, NULL, &hdr, data, payload_size);
return GF_OK;
} else if (hdr.pid == GF_M2TS_PID_NIT_ST) {
/*ignore them, unused at application level*/
gf_m2ts_gather_section(ts, ts->nit, NULL, &hdr, data, payload_size);
return GF_OK;
} else if (hdr.pid == GF_M2TS_PID_EIT_ST_CIT) {
/* ignore EIT messages for the moment */
gf_m2ts_gather_section(ts, ts->eit, NULL, &hdr, data, payload_size);
return GF_OK;
} else if (hdr.pid == GF_M2TS_PID_TDT_TOT_ST) {
gf_m2ts_gather_section(ts, ts->tdt_tot, NULL, &hdr, data, payload_size);
} else {
/* ignore packet */
}
} else if (es->flags & GF_M2TS_ES_IS_SECTION) { /* The stream uses sections to carry its payload */
GF_M2TS_SECTION_ES *ses = (GF_M2TS_SECTION_ES *)es;
if (ses->sec) gf_m2ts_gather_section(ts, ses->sec, ses, &hdr, data, payload_size);
} else {
GF_M2TS_PES *pes = (GF_M2TS_PES *)es;
/* regular stream using PES packets */
if (pes->reframe && payload_size) gf_m2ts_process_pes(ts, pes, &hdr, data, payload_size, paf);
}
return GF_OK;
}
GF_EXPORT
GF_Err gf_m2ts_process_data(GF_M2TS_Demuxer *ts, u8 *data, u32 data_size)
{
GF_Err e=GF_OK;
u32 pos, pck_size;
Bool is_align = 1;
if (ts->buffer_size) {
//we are sync, copy remaining bytes
if ( (ts->buffer[0]==0x47) && (ts->buffer_size<200)) {
u32 pck_size = ts->prefix_present ? 192 : 188;
if (ts->alloc_size < 200) {
ts->alloc_size = 200;
ts->buffer = (char*)gf_realloc(ts->buffer, sizeof(char)*ts->alloc_size);
}
memcpy(ts->buffer + ts->buffer_size, data, pck_size - ts->buffer_size);
e |= gf_m2ts_process_packet(ts, (unsigned char *)ts->buffer);
data += (pck_size - ts->buffer_size);
data_size = data_size - (pck_size - ts->buffer_size);
}
//not sync, copy over the complete buffer
else {
if (ts->alloc_size < ts->buffer_size+data_size) {
ts->alloc_size = ts->buffer_size+data_size;
ts->buffer = (char*)gf_realloc(ts->buffer, sizeof(char)*ts->alloc_size);
}
memcpy(ts->buffer + ts->buffer_size, data, sizeof(char)*data_size);
ts->buffer_size += data_size;
is_align = 0;
data = ts->buffer;
data_size = ts->buffer_size;
}
}
/*sync input data*/
pos = gf_m2ts_sync(ts, data, data_size, is_align);
if (pos==data_size) {
if (is_align) {
if (ts->alloc_size<data_size) {
ts->buffer = (char*)gf_realloc(ts->buffer, sizeof(char)*data_size);
ts->alloc_size = data_size;
}
memcpy(ts->buffer, data, sizeof(char)*data_size);
ts->buffer_size = data_size;
}
return GF_OK;
}
pck_size = ts->prefix_present ? 192 : 188;
for (;;) {
/*wait for a complete packet*/
if (data_size < pos + pck_size) {
ts->buffer_size = data_size - pos;
data += pos;
if (!ts->buffer_size) {
return e;
}
assert(ts->buffer_size<pck_size);
if (is_align) {
u32 s = ts->buffer_size;
if (s<200) s = 200;
if (ts->alloc_size < s) {
ts->alloc_size = s;
ts->buffer = (char*)gf_realloc(ts->buffer, sizeof(char)*ts->alloc_size);
}
memcpy(ts->buffer, data, sizeof(char)*ts->buffer_size);
} else {
memmove(ts->buffer, data, sizeof(char)*ts->buffer_size);
}
return e;
}
/*process*/
e |= gf_m2ts_process_packet(ts, (unsigned char *)data + pos);
pos += pck_size;
}
return e;
}
//unused
#if 0
GF_ESD *gf_m2ts_get_esd(GF_M2TS_ES *es)
{
GF_ESD *esd;
u32 k, esd_count;
esd = NULL;
if (es->program->pmt_iod && es->program->pmt_iod->ESDescriptors) {
esd_count = gf_list_count(es->program->pmt_iod->ESDescriptors);
for (k = 0; k < esd_count; k++) {
GF_ESD *esd_tmp = (GF_ESD *)gf_list_get(es->program->pmt_iod->ESDescriptors, k);
if (esd_tmp->ESID != es->mpeg4_es_id) continue;
esd = esd_tmp;
break;
}
}
if (!esd && es->program->additional_ods) {
u32 od_count, od_index;
od_count = gf_list_count(es->program->additional_ods);
for (od_index = 0; od_index < od_count; od_index++) {
GF_ObjectDescriptor *od = (GF_ObjectDescriptor *)gf_list_get(es->program->additional_ods, od_index);
esd_count = gf_list_count(od->ESDescriptors);
for (k = 0; k < esd_count; k++) {
GF_ESD *esd_tmp = (GF_ESD *)gf_list_get(od->ESDescriptors, k);
if (esd_tmp->ESID != es->mpeg4_es_id) continue;
esd = esd_tmp;
break;
}
}
}
return esd;
}
void gf_m2ts_set_segment_switch(GF_M2TS_Demuxer *ts)
{
u32 i;
for (i=0; i<GF_M2TS_MAX_STREAMS; i++) {
GF_M2TS_ES *es = (GF_M2TS_ES *) ts->ess[i];
if (!es) continue;
es->flags |= GF_M2TS_ES_IGNORE_NEXT_DISCONTINUITY;
}
}
#endif
GF_EXPORT
void gf_m2ts_reset_parsers_for_program(GF_M2TS_Demuxer *ts, GF_M2TS_Program *prog)
{
u32 i;
for (i=0; i<GF_M2TS_MAX_STREAMS; i++) {
GF_M2TS_ES *es = (GF_M2TS_ES *) ts->ess[i];
if (!es) continue;
if (prog && (es->program != prog) ) continue;
if (es->flags & GF_M2TS_ES_IS_SECTION) {
GF_M2TS_SECTION_ES *ses = (GF_M2TS_SECTION_ES *)es;
gf_m2ts_section_filter_reset(ses->sec);
} else {
GF_M2TS_PES *pes = (GF_M2TS_PES *)es;
if (!pes || (pes->pid==pes->program->pmt_pid)) continue;
pes->cc = -1;
pes->frame_state = 0;
pes->pck_data_len = 0;
if (pes->prev_data) gf_free(pes->prev_data);
pes->prev_data = NULL;
pes->prev_data_len = 0;
pes->PTS = pes->DTS = 0;
// pes->prev_PTS = 0;
// pes->first_dts = 0;
pes->pes_len = pes->pes_end_packet_number = pes->pes_start_packet_number = 0;
if (pes->buf) gf_free(pes->buf);
pes->buf = NULL;
if (pes->temi_tc_desc) gf_free(pes->temi_tc_desc);
pes->temi_tc_desc = NULL;
pes->temi_tc_desc_len = pes->temi_tc_desc_alloc_size = 0;
pes->before_last_pcr_value = pes->before_last_pcr_value_pck_number = 0;
pes->last_pcr_value = pes->last_pcr_value_pck_number = 0;
if (pes->program->pcr_pid==pes->pid) {
pes->program->last_pcr_value = pes->program->last_pcr_value_pck_number = 0;
pes->program->before_last_pcr_value = pes->program->before_last_pcr_value_pck_number = 0;
}
}
}
}
GF_EXPORT
void gf_m2ts_reset_parsers(GF_M2TS_Demuxer *ts)
{
gf_m2ts_reset_parsers_for_program(ts, NULL);
ts->pck_number = 0;
gf_m2ts_section_filter_reset(ts->cat);
gf_m2ts_section_filter_reset(ts->pat);
gf_m2ts_section_filter_reset(ts->sdt);
gf_m2ts_section_filter_reset(ts->nit);
gf_m2ts_section_filter_reset(ts->eit);
gf_m2ts_section_filter_reset(ts->tdt_tot);
}
#if 0 //unused
u32 gf_m2ts_pes_get_framing_mode(GF_M2TS_PES *pes)
{
if (pes->flags & GF_M2TS_ES_IS_SECTION) {
if (pes->flags & GF_M2TS_ES_IS_SL) {
if ( ((GF_M2TS_SECTION_ES *)pes)->sec->process_section == NULL)
return GF_M2TS_PES_FRAMING_DEFAULT;
}
return GF_M2TS_PES_FRAMING_SKIP_NO_RESET;
}
if (!pes->reframe ) return GF_M2TS_PES_FRAMING_SKIP_NO_RESET;
if (pes->reframe == gf_m2ts_reframe_default) return GF_M2TS_PES_FRAMING_RAW;
if (pes->reframe == gf_m2ts_reframe_reset) return GF_M2TS_PES_FRAMING_SKIP;
return GF_M2TS_PES_FRAMING_DEFAULT;
}
#endif
GF_EXPORT
GF_Err gf_m2ts_set_pes_framing(GF_M2TS_PES *pes, u32 mode)
{
if (!pes) return GF_BAD_PARAM;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Setting pes framing mode of PID %d to %d\n", pes->pid, mode) );
/*ignore request for section PIDs*/
if (pes->flags & GF_M2TS_ES_IS_SECTION) {
if (pes->flags & GF_M2TS_ES_IS_SL) {
if (mode==GF_M2TS_PES_FRAMING_DEFAULT) {
((GF_M2TS_SECTION_ES *)pes)->sec->process_section = gf_m2ts_process_mpeg4section;
} else {
((GF_M2TS_SECTION_ES *)pes)->sec->process_section = NULL;
}
}
return GF_OK;
}
if (pes->pid==pes->program->pmt_pid) return GF_BAD_PARAM;
//if component reuse, disable previous pes
if ((mode > GF_M2TS_PES_FRAMING_SKIP) && (pes->program->ts->ess[pes->pid] != (GF_M2TS_ES *) pes)) {
GF_M2TS_PES *o_pes = (GF_M2TS_PES *) pes->program->ts->ess[pes->pid];
if (o_pes->flags & GF_M2TS_ES_IS_PES)
gf_m2ts_set_pes_framing(o_pes, GF_M2TS_PES_FRAMING_SKIP);
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[MPEG-2 TS] Reassinging PID %d from program %d to program %d\n", pes->pid, o_pes->program->number, pes->program->number) );
pes->program->ts->ess[pes->pid] = (GF_M2TS_ES *) pes;
}
switch (mode) {
case GF_M2TS_PES_FRAMING_RAW:
pes->reframe = gf_m2ts_reframe_default;
break;
case GF_M2TS_PES_FRAMING_SKIP:
pes->reframe = gf_m2ts_reframe_reset;
break;
case GF_M2TS_PES_FRAMING_SKIP_NO_RESET:
pes->reframe = NULL;
break;
case GF_M2TS_PES_FRAMING_DEFAULT:
default:
switch (pes->stream_type) {
case GF_M2TS_VIDEO_MPEG1:
case GF_M2TS_VIDEO_MPEG2:
case GF_M2TS_VIDEO_H264:
case GF_M2TS_VIDEO_SVC:
case GF_M2TS_VIDEO_HEVC:
case GF_M2TS_VIDEO_HEVC_TEMPORAL:
case GF_M2TS_VIDEO_HEVC_MCTS:
case GF_M2TS_VIDEO_SHVC:
case GF_M2TS_VIDEO_SHVC_TEMPORAL:
case GF_M2TS_VIDEO_MHVC:
case GF_M2TS_VIDEO_MHVC_TEMPORAL:
case GF_M2TS_AUDIO_MPEG1:
case GF_M2TS_AUDIO_MPEG2:
case GF_M2TS_AUDIO_AAC:
case GF_M2TS_AUDIO_LATM_AAC:
case GF_M2TS_AUDIO_AC3:
case GF_M2TS_AUDIO_EC3:
//for all our supported codec types, use a reframer filter
pes->reframe = gf_m2ts_reframe_default;
break;
case GF_M2TS_PRIVATE_DATA:
/* TODO: handle DVB subtitle streams */
break;
case GF_M2TS_METADATA_ID3_HLS:
//TODO
pes->reframe = gf_m2ts_reframe_id3_pes;
break;
default:
pes->reframe = gf_m2ts_reframe_default;
break;
}
break;
}
return GF_OK;
}
GF_EXPORT
GF_M2TS_Demuxer *gf_m2ts_demux_new()
{
GF_M2TS_Demuxer *ts;
GF_SAFEALLOC(ts, GF_M2TS_Demuxer);
if (!ts) return NULL;
ts->programs = gf_list_new();
ts->SDTs = gf_list_new();
ts->pat = gf_m2ts_section_filter_new(gf_m2ts_process_pat, 0);
ts->cat = gf_m2ts_section_filter_new(gf_m2ts_process_cat, 0);
ts->sdt = gf_m2ts_section_filter_new(gf_m2ts_process_sdt, 1);
ts->nit = gf_m2ts_section_filter_new(gf_m2ts_process_nit, 0);
ts->eit = gf_m2ts_section_filter_new(NULL/*gf_m2ts_process_eit*/, 1);
ts->tdt_tot = gf_m2ts_section_filter_new(gf_m2ts_process_tdt_tot, 1);
#ifdef GPAC_ENABLE_MPE
gf_dvb_mpe_init(ts);
#endif
ts->nb_prog_pmt_received = 0;
ts->ChannelAppList = gf_list_new();
return ts;
}
GF_EXPORT
void gf_m2ts_demux_dmscc_init(GF_M2TS_Demuxer *ts) {
char temp_dir[GF_MAX_PATH];
u32 length;
GF_Err e;
ts->dsmcc_controler = gf_list_new();
ts->process_dmscc = 1;
strcpy(temp_dir, gf_get_default_cache_directory() );
length = (u32) strlen(temp_dir);
if(temp_dir[length-1] == GF_PATH_SEPARATOR) {
temp_dir[length-1] = 0;
}
ts->dsmcc_root_dir = (char*)gf_calloc(strlen(temp_dir)+strlen("CarouselData")+2,sizeof(char));
sprintf(ts->dsmcc_root_dir,"%s%cCarouselData",temp_dir,GF_PATH_SEPARATOR);
e = gf_mkdir(ts->dsmcc_root_dir);
if(e) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[Process DSMCC] Error during the creation of the directory %s \n",ts->dsmcc_root_dir));
}
}
GF_EXPORT
void gf_m2ts_demux_del(GF_M2TS_Demuxer *ts)
{
u32 i;
if (ts->pat) gf_m2ts_section_filter_del(ts->pat);
if (ts->cat) gf_m2ts_section_filter_del(ts->cat);
if (ts->sdt) gf_m2ts_section_filter_del(ts->sdt);
if (ts->nit) gf_m2ts_section_filter_del(ts->nit);
if (ts->eit) gf_m2ts_section_filter_del(ts->eit);
if (ts->tdt_tot) gf_m2ts_section_filter_del(ts->tdt_tot);
for (i=0; i<GF_M2TS_MAX_STREAMS; i++) {
//bacause of pure PCR streams, en ES might be reassigned on 2 PIDs, one for the ES and one for the PCR
if (ts->ess[i] && (ts->ess[i]->pid==i)) gf_m2ts_es_del(ts->ess[i], ts);
}
if (ts->buffer) gf_free(ts->buffer);
while (gf_list_count(ts->programs)) {
GF_M2TS_Program *p = (GF_M2TS_Program *)gf_list_last(ts->programs);
gf_list_rem_last(ts->programs);
gf_list_del(p->streams);
/*reset OD list*/
if (p->additional_ods) {
gf_odf_desc_list_del(p->additional_ods);
gf_list_del(p->additional_ods);
}
if (p->pmt_iod) gf_odf_desc_del((GF_Descriptor *)p->pmt_iod);
if (p->metadata_pointer_descriptor) gf_m2ts_metadata_pointer_descriptor_del(p->metadata_pointer_descriptor);
gf_free(p);
}
gf_list_del(ts->programs);
if (ts->TDT_time) gf_free(ts->TDT_time);
gf_m2ts_reset_sdt(ts);
if (ts->tdt_tot)
gf_list_del(ts->SDTs);
#ifdef GPAC_ENABLE_MPE
gf_dvb_mpe_shutdown(ts);
#endif
if (ts->dsmcc_controler) {
if (gf_list_count(ts->dsmcc_controler)) {
#ifdef GPAC_ENABLE_DSMCC
GF_M2TS_DSMCC_OVERLORD* dsmcc_overlord = (GF_M2TS_DSMCC_OVERLORD*)gf_list_get(ts->dsmcc_controler,0);
gf_cleanup_dir(dsmcc_overlord->root_dir);
gf_rmdir(dsmcc_overlord->root_dir);
gf_m2ts_delete_dsmcc_overlord(dsmcc_overlord);
if(ts->dsmcc_root_dir) {
gf_free(ts->dsmcc_root_dir);
}
#endif
}
gf_list_del(ts->dsmcc_controler);
}
while(gf_list_count(ts->ChannelAppList)) {
#ifdef GPAC_ENABLE_DSMCC
GF_M2TS_CHANNEL_APPLICATION_INFO* ChanAppInfo = (GF_M2TS_CHANNEL_APPLICATION_INFO*)gf_list_get(ts->ChannelAppList,0);
gf_m2ts_delete_channel_application_info(ChanAppInfo);
gf_list_rem(ts->ChannelAppList,0);
#endif
}
gf_list_del(ts->ChannelAppList);
if (ts->dsmcc_root_dir) gf_free(ts->dsmcc_root_dir);
gf_free(ts);
}
#if 0//unused
void gf_m2ts_print_info(GF_M2TS_Demuxer *ts)
{
#ifdef GPAC_ENABLE_MPE
gf_m2ts_print_mpe_info(ts);
#endif
}
#endif
#define M2TS_PROBE_SIZE 188000
static Bool gf_m2ts_probe_buffer(char *buf, u32 size)
{
GF_Err e;
GF_M2TS_Demuxer *ts;
u32 lt;
lt = gf_log_get_tool_level(GF_LOG_CONTAINER);
gf_log_set_tool_level(GF_LOG_CONTAINER, GF_LOG_QUIET);
ts = gf_m2ts_demux_new();
e = gf_m2ts_process_data(ts, buf, size);
if (!ts->pck_number) e = GF_BAD_PARAM;
gf_m2ts_demux_del(ts);
gf_log_set_tool_level(GF_LOG_CONTAINER, lt);
if (e) return GF_FALSE;
return GF_TRUE;
}
GF_EXPORT
Bool gf_m2ts_probe_file(const char *fileName)
{
char buf[M2TS_PROBE_SIZE];
u32 size;
FILE *t;
if (!strncmp(fileName, "gmem://", 7)) {
u8 *mem_address;
if (gf_blob_get_data(fileName, &mem_address, &size) != GF_OK) {
return GF_FALSE;
}
if (size>M2TS_PROBE_SIZE) size = M2TS_PROBE_SIZE;
memcpy(buf, mem_address, size);
} else {
t = gf_fopen(fileName, "rb");
if (!t) return 0;
size = (u32) fread(buf, 1, M2TS_PROBE_SIZE, t);
gf_fclose(t);
if ((s32) size <= 0) return 0;
}
return gf_m2ts_probe_buffer(buf, size);
}
GF_EXPORT
Bool gf_m2ts_probe_data(const u8 *data, u32 size)
{
size /= 188;
size *= 188;
return gf_m2ts_probe_buffer((char *) data, size);
}
static void rewrite_pts_dts(unsigned char *ptr, u64 TS)
{
ptr[0] &= 0xf1;
ptr[0] |= (unsigned char)((TS&0x1c0000000ULL)>>29);
ptr[1] = (unsigned char)((TS&0x03fc00000ULL)>>22);
ptr[2] &= 0x1;
ptr[2] |= (unsigned char)((TS&0x0003f8000ULL)>>14);
ptr[3] = (unsigned char)((TS&0x000007f80ULL)>>7);
ptr[4] &= 0x1;
ptr[4] |= (unsigned char)((TS&0x00000007fULL)<<1);
assert(((u64)(ptr[0]&0xe)<<29) + ((u64)ptr[1]<<22) + ((u64)(ptr[2]&0xfe)<<14) + ((u64)ptr[3]<<7) + ((ptr[4]&0xfe)>>1) == TS);
}
#define ADJUST_TIMESTAMP(_TS) \
if (_TS < (u64) -ts_shift) _TS = pcr_mod + _TS + ts_shift; \
else _TS = _TS + ts_shift; \
while (_TS > pcr_mod) _TS -= pcr_mod; \
GF_EXPORT
GF_Err gf_m2ts_restamp(u8 *buffer, u32 size, s64 ts_shift, u8 *is_pes)
{
u32 done = 0;
u64 pcr_mod;
// if (!ts_shift) return GF_OK;
pcr_mod = 0x80000000;
pcr_mod*=4;
while (done + 188 <= size) {
u8 *pesh;
u8 *pck;
u64 pcr_base=0, pcr_ext=0;
u16 pid;
u8 adaptation_field, adaptation_field_length;
pck = (u8*) buffer+done;
if (pck[0]!=0x47) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[M2TS Restamp] Invalid sync byte %X\n", pck[0]));
return GF_NON_COMPLIANT_BITSTREAM;
}
pid = ((pck[1] & 0x1f) <<8 ) + pck[2];
adaptation_field_length = 0;
adaptation_field = (pck[3] >> 4) & 0x3;
if ((adaptation_field==2) || (adaptation_field==3)) {
adaptation_field_length = pck[4];
if ( pck[5]&0x10 /*PCR_flag*/) {
pcr_base = (((u64)pck[6])<<25) + (pck[7]<<17) + (pck[8]<<9) + (pck[9]<<1) + (pck[10]>>7);
pcr_ext = ((pck[10]&1)<<8) + pck[11];
ADJUST_TIMESTAMP(pcr_base);
pck[6] = (unsigned char)(0xff&(pcr_base>>25));
pck[7] = (unsigned char)(0xff&(pcr_base>>17));
pck[8] = (unsigned char)(0xff&(pcr_base>>9));
pck[9] = (unsigned char)(0xff&(pcr_base>>1));
pck[10] = (unsigned char)(((0x1&pcr_base)<<7) | 0x7e | ((0x100&pcr_ext)>>8));
if (pcr_ext != ((pck[10]&1)<<8) + pck[11]) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[M2TS Restamp] Sanity check failed for PCR restamping\n"));
return GF_IO_ERR;
}
pck[11] = (unsigned char)(0xff&pcr_ext);
}
/*add adaptation_field_length field*/
adaptation_field_length++;
}
if (!is_pes[pid] || !(pck[1]&0x40)) {
done+=188;
continue;
}
pesh = &pck[4+adaptation_field_length];
if ((pesh[0]==0x00) && (pesh[1]==0x00) && (pesh[2]==0x01)) {
Bool has_pts, has_dts;
if ((pesh[6]&0xc0)!=0x80) {
done+=188;
continue;
}
has_pts = (pesh[7]&0x80);
has_dts = has_pts ? (pesh[7]&0x40) : 0;
if (has_pts) {
u64 PTS;
if (((pesh[9]&0xe0)>>4)!=0x2) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[M2TS Restamp] PID %4d: Wrong PES header, PTS decoding: '0010' expected\n", pid));
done+=188;
continue;
}
PTS = gf_m2ts_get_pts(pesh + 9);
ADJUST_TIMESTAMP(PTS);
rewrite_pts_dts(pesh+9, PTS);
}
if (has_dts) {
u64 DTS = gf_m2ts_get_pts(pesh + 14);
ADJUST_TIMESTAMP(DTS);
rewrite_pts_dts(pesh+14, DTS);
}
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[M2TS Restamp] PID %4d: Wrong PES not beginning with start code\n", pid));
}
done+=188;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_MPEG2TS*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1374_0 |
crossvul-cpp_data_good_4827_0 | //---------------------------------------------------------------------------------
//
// Little Color Management System
// Copyright (c) 1998-2016 Marti Maria Saguer
//
// 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.
//
//---------------------------------------------------------------------------------
//
#include "lcms2_internal.h"
// Tag Serialization -----------------------------------------------------------------------------
// This file implements every single tag and tag type as described in the ICC spec. Some types
// have been deprecated, like ncl and Data. There is no implementation for those types as there
// are no profiles holding them. The programmer can also extend this list by defining his own types
// by using the appropriate plug-in. There are three types of plug ins regarding that. First type
// allows to define new tags using any existing type. Next plug-in type allows to define new types
// and the third one is very specific: allows to extend the number of elements in the multiprocessing
// elements special type.
//--------------------------------------------------------------------------------------------------
// Some broken types
#define cmsCorbisBrokenXYZtype ((cmsTagTypeSignature) 0x17A505B8)
#define cmsMonacoBrokenCurveType ((cmsTagTypeSignature) 0x9478ee00)
// This is the linked list that keeps track of the defined types
typedef struct _cmsTagTypeLinkedList_st {
cmsTagTypeHandler Handler;
struct _cmsTagTypeLinkedList_st* Next;
} _cmsTagTypeLinkedList;
// Some macros to define callbacks.
#define READ_FN(x) Type_##x##_Read
#define WRITE_FN(x) Type_##x##_Write
#define FREE_FN(x) Type_##x##_Free
#define DUP_FN(x) Type_##x##_Dup
// Helper macro to define a handler. Callbacks do have a fixed naming convention.
#define TYPE_HANDLER(t, x) { (t), READ_FN(x), WRITE_FN(x), DUP_FN(x), FREE_FN(x), NULL, 0 }
// Helper macro to define a MPE handler. Callbacks do have a fixed naming convention
#define TYPE_MPE_HANDLER(t, x) { (t), READ_FN(x), WRITE_FN(x), GenericMPEdup, GenericMPEfree, NULL, 0 }
// Register a new type handler. This routine is shared between normal types and MPE. LinkedList points to the optional list head
static
cmsBool RegisterTypesPlugin(cmsContext id, cmsPluginBase* Data, _cmsMemoryClient pos)
{
cmsPluginTagType* Plugin = (cmsPluginTagType*) Data;
_cmsTagTypePluginChunkType* ctx = ( _cmsTagTypePluginChunkType*) _cmsContextGetClientChunk(id, pos);
_cmsTagTypeLinkedList *pt;
// Calling the function with NULL as plug-in would unregister the plug in.
if (Data == NULL) {
// There is no need to set free the memory, as pool is destroyed as a whole.
ctx ->TagTypes = NULL;
return TRUE;
}
// Registering happens in plug-in memory pool.
pt = (_cmsTagTypeLinkedList*) _cmsPluginMalloc(id, sizeof(_cmsTagTypeLinkedList));
if (pt == NULL) return FALSE;
pt ->Handler = Plugin ->Handler;
pt ->Next = ctx ->TagTypes;
ctx ->TagTypes = pt;
return TRUE;
}
// Return handler for a given type or NULL if not found. Shared between normal types and MPE. It first tries the additons
// made by plug-ins and then the built-in defaults.
static
cmsTagTypeHandler* GetHandler(cmsTagTypeSignature sig, _cmsTagTypeLinkedList* PluginLinkedList, _cmsTagTypeLinkedList* DefaultLinkedList)
{
_cmsTagTypeLinkedList* pt;
for (pt = PluginLinkedList;
pt != NULL;
pt = pt ->Next) {
if (sig == pt -> Handler.Signature) return &pt ->Handler;
}
for (pt = DefaultLinkedList;
pt != NULL;
pt = pt ->Next) {
if (sig == pt -> Handler.Signature) return &pt ->Handler;
}
return NULL;
}
// Auxiliary to convert UTF-32 to UTF-16 in some cases
static
cmsBool _cmsWriteWCharArray(cmsIOHANDLER* io, cmsUInt32Number n, const wchar_t* Array)
{
cmsUInt32Number i;
_cmsAssert(io != NULL);
_cmsAssert(!(Array == NULL && n > 0));
for (i=0; i < n; i++) {
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) Array[i])) return FALSE;
}
return TRUE;
}
// Auxiliary to read an array of wchar_t
static
cmsBool _cmsReadWCharArray(cmsIOHANDLER* io, cmsUInt32Number n, wchar_t* Array)
{
cmsUInt32Number i;
cmsUInt16Number tmp;
_cmsAssert(io != NULL);
for (i=0; i < n; i++) {
if (Array != NULL) {
if (!_cmsReadUInt16Number(io, &tmp)) return FALSE;
Array[i] = (wchar_t) tmp;
}
else {
if (!_cmsReadUInt16Number(io, NULL)) return FALSE;
}
}
return TRUE;
}
// To deal with position tables
typedef cmsBool (* PositionTableEntryFn)(struct _cms_typehandler_struct* self,
cmsIOHANDLER* io,
void* Cargo,
cmsUInt32Number n,
cmsUInt32Number SizeOfTag);
// Helper function to deal with position tables as described in ICC spec 4.3
// A table of n elements is readed, where first comes n records containing offsets and sizes and
// then a block containing the data itself. This allows to reuse same data in more than one entry
static
cmsBool ReadPositionTable(struct _cms_typehandler_struct* self,
cmsIOHANDLER* io,
cmsUInt32Number Count,
cmsUInt32Number BaseOffset,
void *Cargo,
PositionTableEntryFn ElementFn)
{
cmsUInt32Number i;
cmsUInt32Number *ElementOffsets = NULL, *ElementSizes = NULL;
// Let's take the offsets to each element
ElementOffsets = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number));
if (ElementOffsets == NULL) goto Error;
ElementSizes = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number));
if (ElementSizes == NULL) goto Error;
for (i=0; i < Count; i++) {
if (!_cmsReadUInt32Number(io, &ElementOffsets[i])) goto Error;
if (!_cmsReadUInt32Number(io, &ElementSizes[i])) goto Error;
ElementOffsets[i] += BaseOffset;
}
// Seek to each element and read it
for (i=0; i < Count; i++) {
if (!io -> Seek(io, ElementOffsets[i])) goto Error;
// This is the reader callback
if (!ElementFn(self, io, Cargo, i, ElementSizes[i])) goto Error;
}
// Success
if (ElementOffsets != NULL) _cmsFree(io ->ContextID, ElementOffsets);
if (ElementSizes != NULL) _cmsFree(io ->ContextID, ElementSizes);
return TRUE;
Error:
if (ElementOffsets != NULL) _cmsFree(io ->ContextID, ElementOffsets);
if (ElementSizes != NULL) _cmsFree(io ->ContextID, ElementSizes);
return FALSE;
}
// Same as anterior, but for write position tables
static
cmsBool WritePositionTable(struct _cms_typehandler_struct* self,
cmsIOHANDLER* io,
cmsUInt32Number SizeOfTag,
cmsUInt32Number Count,
cmsUInt32Number BaseOffset,
void *Cargo,
PositionTableEntryFn ElementFn)
{
cmsUInt32Number i;
cmsUInt32Number DirectoryPos, CurrentPos, Before;
cmsUInt32Number *ElementOffsets = NULL, *ElementSizes = NULL;
// Create table
ElementOffsets = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number));
if (ElementOffsets == NULL) goto Error;
ElementSizes = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number));
if (ElementSizes == NULL) goto Error;
// Keep starting position of curve offsets
DirectoryPos = io ->Tell(io);
// Write a fake directory to be filled latter on
for (i=0; i < Count; i++) {
if (!_cmsWriteUInt32Number(io, 0)) goto Error; // Offset
if (!_cmsWriteUInt32Number(io, 0)) goto Error; // size
}
// Write each element. Keep track of the size as well.
for (i=0; i < Count; i++) {
Before = io ->Tell(io);
ElementOffsets[i] = Before - BaseOffset;
// Callback to write...
if (!ElementFn(self, io, Cargo, i, SizeOfTag)) goto Error;
// Now the size
ElementSizes[i] = io ->Tell(io) - Before;
}
// Write the directory
CurrentPos = io ->Tell(io);
if (!io ->Seek(io, DirectoryPos)) goto Error;
for (i=0; i < Count; i++) {
if (!_cmsWriteUInt32Number(io, ElementOffsets[i])) goto Error;
if (!_cmsWriteUInt32Number(io, ElementSizes[i])) goto Error;
}
if (!io ->Seek(io, CurrentPos)) goto Error;
if (ElementOffsets != NULL) _cmsFree(io ->ContextID, ElementOffsets);
if (ElementSizes != NULL) _cmsFree(io ->ContextID, ElementSizes);
return TRUE;
Error:
if (ElementOffsets != NULL) _cmsFree(io ->ContextID, ElementOffsets);
if (ElementSizes != NULL) _cmsFree(io ->ContextID, ElementSizes);
return FALSE;
}
// ********************************************************************************
// Type XYZ. Only one value is allowed
// ********************************************************************************
//The XYZType contains an array of three encoded values for the XYZ tristimulus
//values. Tristimulus values must be non-negative. The signed encoding allows for
//implementation optimizations by minimizing the number of fixed formats.
static
void *Type_XYZ_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsCIEXYZ* xyz;
*nItems = 0;
xyz = (cmsCIEXYZ*) _cmsMallocZero(self ->ContextID, sizeof(cmsCIEXYZ));
if (xyz == NULL) return NULL;
if (!_cmsReadXYZNumber(io, xyz)) {
_cmsFree(self ->ContextID, xyz);
return NULL;
}
*nItems = 1;
return (void*) xyz;
cmsUNUSED_PARAMETER(SizeOfTag);
}
static
cmsBool Type_XYZ_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
return _cmsWriteXYZNumber(io, (cmsCIEXYZ*) Ptr);
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
static
void* Type_XYZ_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsCIEXYZ));
cmsUNUSED_PARAMETER(n);
}
static
void Type_XYZ_Free(struct _cms_typehandler_struct* self, void *Ptr)
{
_cmsFree(self ->ContextID, Ptr);
}
static
cmsTagTypeSignature DecideXYZtype(cmsFloat64Number ICCVersion, const void *Data)
{
return cmsSigXYZType;
cmsUNUSED_PARAMETER(ICCVersion);
cmsUNUSED_PARAMETER(Data);
}
// ********************************************************************************
// Type chromaticity. Only one value is allowed
// ********************************************************************************
// The chromaticity tag type provides basic chromaticity data and type of
// phosphors or colorants of a monitor to applications and utilities.
static
void *Type_Chromaticity_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsCIExyYTRIPLE* chrm;
cmsUInt16Number nChans, Table;
*nItems = 0;
chrm = (cmsCIExyYTRIPLE*) _cmsMallocZero(self ->ContextID, sizeof(cmsCIExyYTRIPLE));
if (chrm == NULL) return NULL;
if (!_cmsReadUInt16Number(io, &nChans)) goto Error;
// Let's recover from a bug introduced in early versions of lcms1
if (nChans == 0 && SizeOfTag == 32) {
if (!_cmsReadUInt16Number(io, NULL)) goto Error;
if (!_cmsReadUInt16Number(io, &nChans)) goto Error;
}
if (nChans != 3) goto Error;
if (!_cmsReadUInt16Number(io, &Table)) goto Error;
if (!_cmsRead15Fixed16Number(io, &chrm ->Red.x)) goto Error;
if (!_cmsRead15Fixed16Number(io, &chrm ->Red.y)) goto Error;
chrm ->Red.Y = 1.0;
if (!_cmsRead15Fixed16Number(io, &chrm ->Green.x)) goto Error;
if (!_cmsRead15Fixed16Number(io, &chrm ->Green.y)) goto Error;
chrm ->Green.Y = 1.0;
if (!_cmsRead15Fixed16Number(io, &chrm ->Blue.x)) goto Error;
if (!_cmsRead15Fixed16Number(io, &chrm ->Blue.y)) goto Error;
chrm ->Blue.Y = 1.0;
*nItems = 1;
return (void*) chrm;
Error:
_cmsFree(self ->ContextID, (void*) chrm);
return NULL;
cmsUNUSED_PARAMETER(SizeOfTag);
}
static
cmsBool SaveOneChromaticity(cmsFloat64Number x, cmsFloat64Number y, cmsIOHANDLER* io)
{
if (!_cmsWriteUInt32Number(io, _cmsDoubleTo15Fixed16(x))) return FALSE;
if (!_cmsWriteUInt32Number(io, _cmsDoubleTo15Fixed16(y))) return FALSE;
return TRUE;
}
static
cmsBool Type_Chromaticity_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsCIExyYTRIPLE* chrm = (cmsCIExyYTRIPLE*) Ptr;
if (!_cmsWriteUInt16Number(io, 3)) return FALSE; // nChannels
if (!_cmsWriteUInt16Number(io, 0)) return FALSE; // Table
if (!SaveOneChromaticity(chrm -> Red.x, chrm -> Red.y, io)) return FALSE;
if (!SaveOneChromaticity(chrm -> Green.x, chrm -> Green.y, io)) return FALSE;
if (!SaveOneChromaticity(chrm -> Blue.x, chrm -> Blue.y, io)) return FALSE;
return TRUE;
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
static
void* Type_Chromaticity_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsCIExyYTRIPLE));
cmsUNUSED_PARAMETER(n);
}
static
void Type_Chromaticity_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
_cmsFree(self ->ContextID, Ptr);
}
// ********************************************************************************
// Type cmsSigColorantOrderType
// ********************************************************************************
// This is an optional tag which specifies the laydown order in which colorants will
// be printed on an n-colorant device. The laydown order may be the same as the
// channel generation order listed in the colorantTableTag or the channel order of a
// colour space such as CMYK, in which case this tag is not needed. When this is not
// the case (for example, ink-towers sometimes use the order KCMY), this tag may be
// used to specify the laydown order of the colorants.
static
void *Type_ColorantOrderType_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsUInt8Number* ColorantOrder;
cmsUInt32Number Count;
*nItems = 0;
if (!_cmsReadUInt32Number(io, &Count)) return NULL;
if (Count > cmsMAXCHANNELS) return NULL;
ColorantOrder = (cmsUInt8Number*) _cmsCalloc(self ->ContextID, cmsMAXCHANNELS, sizeof(cmsUInt8Number));
if (ColorantOrder == NULL) return NULL;
// We use FF as end marker
memset(ColorantOrder, 0xFF, cmsMAXCHANNELS * sizeof(cmsUInt8Number));
if (io ->Read(io, ColorantOrder, sizeof(cmsUInt8Number), Count) != Count) {
_cmsFree(self ->ContextID, (void*) ColorantOrder);
return NULL;
}
*nItems = 1;
return (void*) ColorantOrder;
cmsUNUSED_PARAMETER(SizeOfTag);
}
static
cmsBool Type_ColorantOrderType_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsUInt8Number* ColorantOrder = (cmsUInt8Number*) Ptr;
cmsUInt32Number i, sz, Count;
// Get the length
for (Count=i=0; i < cmsMAXCHANNELS; i++) {
if (ColorantOrder[i] != 0xFF) Count++;
}
if (!_cmsWriteUInt32Number(io, Count)) return FALSE;
sz = Count * sizeof(cmsUInt8Number);
if (!io -> Write(io, sz, ColorantOrder)) return FALSE;
return TRUE;
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
static
void* Type_ColorantOrderType_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return _cmsDupMem(self ->ContextID, Ptr, cmsMAXCHANNELS * sizeof(cmsUInt8Number));
cmsUNUSED_PARAMETER(n);
}
static
void Type_ColorantOrderType_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
_cmsFree(self ->ContextID, Ptr);
}
// ********************************************************************************
// Type cmsSigS15Fixed16ArrayType
// ********************************************************************************
// This type represents an array of generic 4-byte/32-bit fixed point quantity.
// The number of values is determined from the size of the tag.
static
void *Type_S15Fixed16_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsFloat64Number* array_double;
cmsUInt32Number i, n;
*nItems = 0;
n = SizeOfTag / sizeof(cmsUInt32Number);
array_double = (cmsFloat64Number*) _cmsCalloc(self ->ContextID, n, sizeof(cmsFloat64Number));
if (array_double == NULL) return NULL;
for (i=0; i < n; i++) {
if (!_cmsRead15Fixed16Number(io, &array_double[i])) {
_cmsFree(self ->ContextID, array_double);
return NULL;
}
}
*nItems = n;
return (void*) array_double;
}
static
cmsBool Type_S15Fixed16_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsFloat64Number* Value = (cmsFloat64Number*) Ptr;
cmsUInt32Number i;
for (i=0; i < nItems; i++) {
if (!_cmsWrite15Fixed16Number(io, Value[i])) return FALSE;
}
return TRUE;
cmsUNUSED_PARAMETER(self);
}
static
void* Type_S15Fixed16_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return _cmsDupMem(self ->ContextID, Ptr, n * sizeof(cmsFloat64Number));
}
static
void Type_S15Fixed16_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
_cmsFree(self ->ContextID, Ptr);
}
// ********************************************************************************
// Type cmsSigU16Fixed16ArrayType
// ********************************************************************************
// This type represents an array of generic 4-byte/32-bit quantity.
// The number of values is determined from the size of the tag.
static
void *Type_U16Fixed16_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsFloat64Number* array_double;
cmsUInt32Number v;
cmsUInt32Number i, n;
*nItems = 0;
n = SizeOfTag / sizeof(cmsUInt32Number);
array_double = (cmsFloat64Number*) _cmsCalloc(self ->ContextID, n, sizeof(cmsFloat64Number));
if (array_double == NULL) return NULL;
for (i=0; i < n; i++) {
if (!_cmsReadUInt32Number(io, &v)) {
_cmsFree(self ->ContextID, (void*) array_double);
return NULL;
}
// Convert to cmsFloat64Number
array_double[i] = (cmsFloat64Number) (v / 65536.0);
}
*nItems = n;
return (void*) array_double;
}
static
cmsBool Type_U16Fixed16_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsFloat64Number* Value = (cmsFloat64Number*) Ptr;
cmsUInt32Number i;
for (i=0; i < nItems; i++) {
cmsUInt32Number v = (cmsUInt32Number) floor(Value[i]*65536.0 + 0.5);
if (!_cmsWriteUInt32Number(io, v)) return FALSE;
}
return TRUE;
cmsUNUSED_PARAMETER(self);
}
static
void* Type_U16Fixed16_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return _cmsDupMem(self ->ContextID, Ptr, n * sizeof(cmsFloat64Number));
}
static
void Type_U16Fixed16_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
_cmsFree(self ->ContextID, Ptr);
}
// ********************************************************************************
// Type cmsSigSignatureType
// ********************************************************************************
//
// The signatureType contains a four-byte sequence, Sequences of less than four
// characters are padded at the end with spaces, 20h.
// Typically this type is used for registered tags that can be displayed on many
// development systems as a sequence of four characters.
static
void *Type_Signature_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsSignature* SigPtr = (cmsSignature*) _cmsMalloc(self ->ContextID, sizeof(cmsSignature));
if (SigPtr == NULL) return NULL;
if (!_cmsReadUInt32Number(io, SigPtr)) return NULL;
*nItems = 1;
return SigPtr;
cmsUNUSED_PARAMETER(SizeOfTag);
}
static
cmsBool Type_Signature_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsSignature* SigPtr = (cmsSignature*) Ptr;
return _cmsWriteUInt32Number(io, *SigPtr);
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
static
void* Type_Signature_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return _cmsDupMem(self ->ContextID, Ptr, n * sizeof(cmsSignature));
}
static
void Type_Signature_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
_cmsFree(self ->ContextID, Ptr);
}
// ********************************************************************************
// Type cmsSigTextType
// ********************************************************************************
//
// The textType is a simple text structure that contains a 7-bit ASCII text string.
// The length of the string is obtained by subtracting 8 from the element size portion
// of the tag itself. This string must be terminated with a 00h byte.
static
void *Type_Text_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
char* Text = NULL;
cmsMLU* mlu = NULL;
// Create a container
mlu = cmsMLUalloc(self ->ContextID, 1);
if (mlu == NULL) return NULL;
*nItems = 0;
// We need to store the "\0" at the end, so +1
if (SizeOfTag == UINT_MAX) goto Error;
Text = (char*) _cmsMalloc(self ->ContextID, SizeOfTag + 1);
if (Text == NULL) goto Error;
if (io -> Read(io, Text, sizeof(char), SizeOfTag) != SizeOfTag) goto Error;
// Make sure text is properly ended
Text[SizeOfTag] = 0;
*nItems = 1;
// Keep the result
if (!cmsMLUsetASCII(mlu, cmsNoLanguage, cmsNoCountry, Text)) goto Error;
_cmsFree(self ->ContextID, Text);
return (void*) mlu;
Error:
if (mlu != NULL)
cmsMLUfree(mlu);
if (Text != NULL)
_cmsFree(self ->ContextID, Text);
return NULL;
}
// The conversion implies to choose a language. So, we choose the actual language.
static
cmsBool Type_Text_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsMLU* mlu = (cmsMLU*) Ptr;
cmsUInt32Number size;
cmsBool rc;
char* Text;
// Get the size of the string. Note there is an extra "\0" at the end
size = cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry, NULL, 0);
if (size == 0) return FALSE; // Cannot be zero!
// Create memory
Text = (char*) _cmsMalloc(self ->ContextID, size);
if (Text == NULL) return FALSE;
cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry, Text, size);
// Write it, including separator
rc = io ->Write(io, size, Text);
_cmsFree(self ->ContextID, Text);
return rc;
cmsUNUSED_PARAMETER(nItems);
}
static
void* Type_Text_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return (void*) cmsMLUdup((cmsMLU*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_Text_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsMLU* mlu = (cmsMLU*) Ptr;
cmsMLUfree(mlu);
return;
cmsUNUSED_PARAMETER(self);
}
static
cmsTagTypeSignature DecideTextType(cmsFloat64Number ICCVersion, const void *Data)
{
if (ICCVersion >= 4.0)
return cmsSigMultiLocalizedUnicodeType;
return cmsSigTextType;
cmsUNUSED_PARAMETER(Data);
}
// ********************************************************************************
// Type cmsSigDataType
// ********************************************************************************
// General purpose data type
static
void *Type_Data_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsICCData* BinData;
cmsUInt32Number LenOfData;
*nItems = 0;
if (SizeOfTag < sizeof(cmsUInt32Number)) return NULL;
LenOfData = SizeOfTag - sizeof(cmsUInt32Number);
if (LenOfData > INT_MAX) return NULL;
BinData = (cmsICCData*) _cmsMalloc(self ->ContextID, sizeof(cmsICCData) + LenOfData - 1);
if (BinData == NULL) return NULL;
BinData ->len = LenOfData;
if (!_cmsReadUInt32Number(io, &BinData->flag)) {
_cmsFree(self ->ContextID, BinData);
return NULL;
}
if (io -> Read(io, BinData ->data, sizeof(cmsUInt8Number), LenOfData) != LenOfData) {
_cmsFree(self ->ContextID, BinData);
return NULL;
}
*nItems = 1;
return (void*) BinData;
}
static
cmsBool Type_Data_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsICCData* BinData = (cmsICCData*) Ptr;
if (!_cmsWriteUInt32Number(io, BinData ->flag)) return FALSE;
return io ->Write(io, BinData ->len, BinData ->data);
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
static
void* Type_Data_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
cmsICCData* BinData = (cmsICCData*) Ptr;
return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsICCData) + BinData ->len - 1);
cmsUNUSED_PARAMETER(n);
}
static
void Type_Data_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
_cmsFree(self ->ContextID, Ptr);
}
// ********************************************************************************
// Type cmsSigTextDescriptionType
// ********************************************************************************
static
void *Type_Text_Description_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
char* Text = NULL;
cmsMLU* mlu = NULL;
cmsUInt32Number AsciiCount;
cmsUInt32Number i, UnicodeCode, UnicodeCount;
cmsUInt16Number ScriptCodeCode, Dummy;
cmsUInt8Number ScriptCodeCount;
*nItems = 0;
// One dword should be there
if (SizeOfTag < sizeof(cmsUInt32Number)) return NULL;
// Read len of ASCII
if (!_cmsReadUInt32Number(io, &AsciiCount)) return NULL;
SizeOfTag -= sizeof(cmsUInt32Number);
// Check for size
if (SizeOfTag < AsciiCount) return NULL;
// All seems Ok, allocate the container
mlu = cmsMLUalloc(self ->ContextID, 1);
if (mlu == NULL) return NULL;
// As many memory as size of tag
Text = (char*) _cmsMalloc(self ->ContextID, AsciiCount + 1);
if (Text == NULL) goto Error;
// Read it
if (io ->Read(io, Text, sizeof(char), AsciiCount) != AsciiCount) goto Error;
SizeOfTag -= AsciiCount;
// Make sure there is a terminator
Text[AsciiCount] = 0;
// Set the MLU entry. From here we can be tolerant to wrong types
if (!cmsMLUsetASCII(mlu, cmsNoLanguage, cmsNoCountry, Text)) goto Error;
_cmsFree(self ->ContextID, (void*) Text);
Text = NULL;
// Skip Unicode code
if (SizeOfTag < 2* sizeof(cmsUInt32Number)) goto Done;
if (!_cmsReadUInt32Number(io, &UnicodeCode)) goto Done;
if (!_cmsReadUInt32Number(io, &UnicodeCount)) goto Done;
SizeOfTag -= 2* sizeof(cmsUInt32Number);
if (SizeOfTag < UnicodeCount*sizeof(cmsUInt16Number)) goto Done;
for (i=0; i < UnicodeCount; i++) {
if (!io ->Read(io, &Dummy, sizeof(cmsUInt16Number), 1)) goto Done;
}
SizeOfTag -= UnicodeCount*sizeof(cmsUInt16Number);
// Skip ScriptCode code if present. Some buggy profiles does have less
// data that stricttly required. We need to skip it as this type may come
// embedded in other types.
if (SizeOfTag >= sizeof(cmsUInt16Number) + sizeof(cmsUInt8Number) + 67) {
if (!_cmsReadUInt16Number(io, &ScriptCodeCode)) goto Done;
if (!_cmsReadUInt8Number(io, &ScriptCodeCount)) goto Done;
// Skip rest of tag
for (i=0; i < 67; i++) {
if (!io ->Read(io, &Dummy, sizeof(cmsUInt8Number), 1)) goto Error;
}
}
Done:
*nItems = 1;
return mlu;
Error:
if (Text) _cmsFree(self ->ContextID, (void*) Text);
if (mlu) cmsMLUfree(mlu);
return NULL;
}
// This tag can come IN UNALIGNED SIZE. In order to prevent issues, we force zeros on description to align it
static
cmsBool Type_Text_Description_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsMLU* mlu = (cmsMLU*) Ptr;
char *Text = NULL;
wchar_t *Wide = NULL;
cmsUInt32Number len, len_text, len_tag_requirement, len_aligned;
cmsBool rc = FALSE;
char Filler[68];
// Used below for writting zeroes
memset(Filler, 0, sizeof(Filler));
// Get the len of string
len = cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry, NULL, 0);
// Specification ICC.1:2001-04 (v2.4.0): It has been found that textDescriptionType can contain misaligned data
//(see clause 4.1 for the definition of �aligned�). Because the Unicode language
// code and Unicode count immediately follow the ASCII description, their
// alignment is not correct if the ASCII count is not a multiple of four. The
// ScriptCode code is misaligned when the ASCII count is odd. Profile reading and
// writing software must be written carefully in order to handle these alignment
// problems.
//
// The above last sentence suggest to handle alignment issues in the
// parser. The provided example (Table 69 on Page 60) makes this clear.
// The padding only in the ASCII count is not sufficient for a aligned tag
// size, with the same text size in ASCII and Unicode.
// Null strings
if (len <= 0) {
Text = (char*) _cmsDupMem(self ->ContextID, "", sizeof(char));
Wide = (wchar_t*) _cmsDupMem(self ->ContextID, L"", sizeof(wchar_t));
}
else {
// Create independent buffers
Text = (char*) _cmsCalloc(self ->ContextID, len, sizeof(char));
if (Text == NULL) goto Error;
Wide = (wchar_t*) _cmsCalloc(self ->ContextID, len, sizeof(wchar_t));
if (Wide == NULL) goto Error;
// Get both representations.
cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry, Text, len * sizeof(char));
cmsMLUgetWide(mlu, cmsNoLanguage, cmsNoCountry, Wide, len * sizeof(wchar_t));
}
// Tell the real text len including the null terminator and padding
len_text = (cmsUInt32Number) strlen(Text) + 1;
// Compute an total tag size requirement
len_tag_requirement = (8+4+len_text+4+4+2*len_text+2+1+67);
len_aligned = _cmsALIGNLONG(len_tag_requirement);
// * cmsUInt32Number count; * Description length
// * cmsInt8Number desc[count] * NULL terminated ascii string
// * cmsUInt32Number ucLangCode; * UniCode language code
// * cmsUInt32Number ucCount; * UniCode description length
// * cmsInt16Number ucDesc[ucCount];* The UniCode description
// * cmsUInt16Number scCode; * ScriptCode code
// * cmsUInt8Number scCount; * ScriptCode count
// * cmsInt8Number scDesc[67]; * ScriptCode Description
if (!_cmsWriteUInt32Number(io, len_text)) goto Error;
if (!io ->Write(io, len_text, Text)) goto Error;
if (!_cmsWriteUInt32Number(io, 0)) goto Error; // ucLanguageCode
if (!_cmsWriteUInt32Number(io, len_text)) goto Error;
// Note that in some compilers sizeof(cmsUInt16Number) != sizeof(wchar_t)
if (!_cmsWriteWCharArray(io, len_text, Wide)) goto Error;
// ScriptCode Code & count (unused)
if (!_cmsWriteUInt16Number(io, 0)) goto Error;
if (!_cmsWriteUInt8Number(io, 0)) goto Error;
if (!io ->Write(io, 67, Filler)) goto Error;
// possibly add pad at the end of tag
if(len_aligned - len_tag_requirement > 0)
if (!io ->Write(io, len_aligned - len_tag_requirement, Filler)) goto Error;
rc = TRUE;
Error:
if (Text) _cmsFree(self ->ContextID, Text);
if (Wide) _cmsFree(self ->ContextID, Wide);
return rc;
cmsUNUSED_PARAMETER(nItems);
}
static
void* Type_Text_Description_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return (void*) cmsMLUdup((cmsMLU*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_Text_Description_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsMLU* mlu = (cmsMLU*) Ptr;
cmsMLUfree(mlu);
return;
cmsUNUSED_PARAMETER(self);
}
static
cmsTagTypeSignature DecideTextDescType(cmsFloat64Number ICCVersion, const void *Data)
{
if (ICCVersion >= 4.0)
return cmsSigMultiLocalizedUnicodeType;
return cmsSigTextDescriptionType;
cmsUNUSED_PARAMETER(Data);
}
// ********************************************************************************
// Type cmsSigCurveType
// ********************************************************************************
static
void *Type_Curve_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsUInt32Number Count;
cmsToneCurve* NewGamma;
*nItems = 0;
if (!_cmsReadUInt32Number(io, &Count)) return NULL;
switch (Count) {
case 0: // Linear.
{
cmsFloat64Number SingleGamma = 1.0;
NewGamma = cmsBuildParametricToneCurve(self ->ContextID, 1, &SingleGamma);
if (!NewGamma) return NULL;
*nItems = 1;
return NewGamma;
}
case 1: // Specified as the exponent of gamma function
{
cmsUInt16Number SingleGammaFixed;
cmsFloat64Number SingleGamma;
if (!_cmsReadUInt16Number(io, &SingleGammaFixed)) return NULL;
SingleGamma = _cms8Fixed8toDouble(SingleGammaFixed);
*nItems = 1;
return cmsBuildParametricToneCurve(self ->ContextID, 1, &SingleGamma);
}
default: // Curve
if (Count > 0x7FFF)
return NULL; // This is to prevent bad guys for doing bad things
NewGamma = cmsBuildTabulatedToneCurve16(self ->ContextID, Count, NULL);
if (!NewGamma) return NULL;
if (!_cmsReadUInt16Array(io, Count, NewGamma -> Table16)) return NULL;
*nItems = 1;
return NewGamma;
}
cmsUNUSED_PARAMETER(SizeOfTag);
}
static
cmsBool Type_Curve_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsToneCurve* Curve = (cmsToneCurve*) Ptr;
if (Curve ->nSegments == 1 && Curve ->Segments[0].Type == 1) {
// Single gamma, preserve number
cmsUInt16Number SingleGammaFixed = _cmsDoubleTo8Fixed8(Curve ->Segments[0].Params[0]);
if (!_cmsWriteUInt32Number(io, 1)) return FALSE;
if (!_cmsWriteUInt16Number(io, SingleGammaFixed)) return FALSE;
return TRUE;
}
if (!_cmsWriteUInt32Number(io, Curve ->nEntries)) return FALSE;
return _cmsWriteUInt16Array(io, Curve ->nEntries, Curve ->Table16);
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
static
void* Type_Curve_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return (void*) cmsDupToneCurve((cmsToneCurve*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_Curve_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsToneCurve* gamma = (cmsToneCurve*) Ptr;
cmsFreeToneCurve(gamma);
return;
cmsUNUSED_PARAMETER(self);
}
// ********************************************************************************
// Type cmsSigParametricCurveType
// ********************************************************************************
// Decide which curve type to use on writting
static
cmsTagTypeSignature DecideCurveType(cmsFloat64Number ICCVersion, const void *Data)
{
cmsToneCurve* Curve = (cmsToneCurve*) Data;
if (ICCVersion < 4.0) return cmsSigCurveType;
if (Curve ->nSegments != 1) return cmsSigCurveType; // Only 1-segment curves can be saved as parametric
if (Curve ->Segments[0].Type < 0) return cmsSigCurveType; // Only non-inverted curves
if (Curve ->Segments[0].Type > 5) return cmsSigCurveType; // Only ICC parametric curves
return cmsSigParametricCurveType;
}
static
void *Type_ParametricCurve_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
static const int ParamsByType[] = { 1, 3, 4, 5, 7 };
cmsFloat64Number Params[10];
cmsUInt16Number Type;
int i, n;
cmsToneCurve* NewGamma;
if (!_cmsReadUInt16Number(io, &Type)) return NULL;
if (!_cmsReadUInt16Number(io, NULL)) return NULL; // Reserved
if (Type > 4) {
cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown parametric curve type '%d'", Type);
return NULL;
}
memset(Params, 0, sizeof(Params));
n = ParamsByType[Type];
for (i=0; i < n; i++) {
if (!_cmsRead15Fixed16Number(io, &Params[i])) return NULL;
}
NewGamma = cmsBuildParametricToneCurve(self ->ContextID, Type+1, Params);
*nItems = 1;
return NewGamma;
cmsUNUSED_PARAMETER(SizeOfTag);
}
static
cmsBool Type_ParametricCurve_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsToneCurve* Curve = (cmsToneCurve*) Ptr;
int i, nParams, typen;
static const int ParamsByType[] = { 0, 1, 3, 4, 5, 7 };
typen = Curve -> Segments[0].Type;
if (Curve ->nSegments > 1 || typen < 1) {
cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Multisegment or Inverted parametric curves cannot be written");
return FALSE;
}
if (typen > 5) {
cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported parametric curve");
return FALSE;
}
nParams = ParamsByType[typen];
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) (Curve ->Segments[0].Type - 1))) return FALSE;
if (!_cmsWriteUInt16Number(io, 0)) return FALSE; // Reserved
for (i=0; i < nParams; i++) {
if (!_cmsWrite15Fixed16Number(io, Curve -> Segments[0].Params[i])) return FALSE;
}
return TRUE;
cmsUNUSED_PARAMETER(nItems);
}
static
void* Type_ParametricCurve_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return (void*) cmsDupToneCurve((cmsToneCurve*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_ParametricCurve_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsToneCurve* gamma = (cmsToneCurve*) Ptr;
cmsFreeToneCurve(gamma);
return;
cmsUNUSED_PARAMETER(self);
}
// ********************************************************************************
// Type cmsSigDateTimeType
// ********************************************************************************
// A 12-byte value representation of the time and date, where the byte usage is assigned
// as specified in table 1. The actual values are encoded as 16-bit unsigned integers
// (uInt16Number - see 5.1.6).
//
// All the dateTimeNumber values in a profile shall be in Coordinated Universal Time
// (UTC, also known as GMT or ZULU Time). Profile writers are required to convert local
// time to UTC when setting these values. Programmes that display these values may show
// the dateTimeNumber as UTC, show the equivalent local time (at current locale), or
// display both UTC and local versions of the dateTimeNumber.
static
void *Type_DateTime_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsDateTimeNumber timestamp;
struct tm * NewDateTime;
*nItems = 0;
NewDateTime = (struct tm*) _cmsMalloc(self ->ContextID, sizeof(struct tm));
if (NewDateTime == NULL) return NULL;
if (io->Read(io, ×tamp, sizeof(cmsDateTimeNumber), 1) != 1) return NULL;
_cmsDecodeDateTimeNumber(×tamp, NewDateTime);
*nItems = 1;
return NewDateTime;
cmsUNUSED_PARAMETER(SizeOfTag);
}
static
cmsBool Type_DateTime_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
struct tm * DateTime = (struct tm*) Ptr;
cmsDateTimeNumber timestamp;
_cmsEncodeDateTimeNumber(×tamp, DateTime);
if (!io ->Write(io, sizeof(cmsDateTimeNumber), ×tamp)) return FALSE;
return TRUE;
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
static
void* Type_DateTime_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return _cmsDupMem(self ->ContextID, Ptr, sizeof(struct tm));
cmsUNUSED_PARAMETER(n);
}
static
void Type_DateTime_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
_cmsFree(self ->ContextID, Ptr);
}
// ********************************************************************************
// Type icMeasurementType
// ********************************************************************************
/*
The measurementType information refers only to the internal profile data and is
meant to provide profile makers an alternative to the default measurement
specifications.
*/
static
void *Type_Measurement_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsICCMeasurementConditions mc;
memset(&mc, 0, sizeof(mc));
if (!_cmsReadUInt32Number(io, &mc.Observer)) return NULL;
if (!_cmsReadXYZNumber(io, &mc.Backing)) return NULL;
if (!_cmsReadUInt32Number(io, &mc.Geometry)) return NULL;
if (!_cmsRead15Fixed16Number(io, &mc.Flare)) return NULL;
if (!_cmsReadUInt32Number(io, &mc.IlluminantType)) return NULL;
*nItems = 1;
return _cmsDupMem(self ->ContextID, &mc, sizeof(cmsICCMeasurementConditions));
cmsUNUSED_PARAMETER(SizeOfTag);
}
static
cmsBool Type_Measurement_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsICCMeasurementConditions* mc =(cmsICCMeasurementConditions*) Ptr;
if (!_cmsWriteUInt32Number(io, mc->Observer)) return FALSE;
if (!_cmsWriteXYZNumber(io, &mc->Backing)) return FALSE;
if (!_cmsWriteUInt32Number(io, mc->Geometry)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, mc->Flare)) return FALSE;
if (!_cmsWriteUInt32Number(io, mc->IlluminantType)) return FALSE;
return TRUE;
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
static
void* Type_Measurement_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsICCMeasurementConditions));
cmsUNUSED_PARAMETER(n);
}
static
void Type_Measurement_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
_cmsFree(self ->ContextID, Ptr);
}
// ********************************************************************************
// Type cmsSigMultiLocalizedUnicodeType
// ********************************************************************************
//
// Do NOT trust SizeOfTag as there is an issue on the definition of profileSequenceDescTag. See the TechNote from
// Max Derhak and Rohit Patil about this: basically the size of the string table should be guessed and cannot be
// taken from the size of tag if this tag is embedded as part of bigger structures (profileSequenceDescTag, for instance)
//
static
void *Type_MLU_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsMLU* mlu;
cmsUInt32Number Count, RecLen, NumOfWchar;
cmsUInt32Number SizeOfHeader;
cmsUInt32Number Len, Offset;
cmsUInt32Number i;
wchar_t* Block;
cmsUInt32Number BeginOfThisString, EndOfThisString, LargestPosition;
*nItems = 0;
if (!_cmsReadUInt32Number(io, &Count)) return NULL;
if (!_cmsReadUInt32Number(io, &RecLen)) return NULL;
if (RecLen != 12) {
cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "multiLocalizedUnicodeType of len != 12 is not supported.");
return NULL;
}
mlu = cmsMLUalloc(self ->ContextID, Count);
if (mlu == NULL) return NULL;
mlu ->UsedEntries = Count;
SizeOfHeader = 12 * Count + sizeof(_cmsTagBase);
LargestPosition = 0;
for (i=0; i < Count; i++) {
if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Language)) goto Error;
if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Country)) goto Error;
// Now deal with Len and offset.
if (!_cmsReadUInt32Number(io, &Len)) goto Error;
if (!_cmsReadUInt32Number(io, &Offset)) goto Error;
// Check for overflow
if (Offset < (SizeOfHeader + 8)) goto Error;
if ((Offset + Len) > SizeOfTag + 8) goto Error;
// True begin of the string
BeginOfThisString = Offset - SizeOfHeader - 8;
// Ajust to wchar_t elements
mlu ->Entries[i].Len = (Len * sizeof(wchar_t)) / sizeof(cmsUInt16Number);
mlu ->Entries[i].StrW = (BeginOfThisString * sizeof(wchar_t)) / sizeof(cmsUInt16Number);
// To guess maximum size, add offset + len
EndOfThisString = BeginOfThisString + Len;
if (EndOfThisString > LargestPosition)
LargestPosition = EndOfThisString;
}
// Now read the remaining of tag and fill all strings. Subtract the directory
SizeOfTag = (LargestPosition * sizeof(wchar_t)) / sizeof(cmsUInt16Number);
if (SizeOfTag == 0)
{
Block = NULL;
NumOfWchar = 0;
}
else
{
Block = (wchar_t*) _cmsMalloc(self ->ContextID, SizeOfTag);
if (Block == NULL) goto Error;
NumOfWchar = SizeOfTag / sizeof(wchar_t);
if (!_cmsReadWCharArray(io, NumOfWchar, Block)) goto Error;
}
mlu ->MemPool = Block;
mlu ->PoolSize = SizeOfTag;
mlu ->PoolUsed = SizeOfTag;
*nItems = 1;
return (void*) mlu;
Error:
if (mlu) cmsMLUfree(mlu);
return NULL;
}
static
cmsBool Type_MLU_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsMLU* mlu =(cmsMLU*) Ptr;
cmsUInt32Number HeaderSize;
cmsUInt32Number Len, Offset;
cmsUInt32Number i;
if (Ptr == NULL) {
// Empty placeholder
if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
if (!_cmsWriteUInt32Number(io, 12)) return FALSE;
return TRUE;
}
if (!_cmsWriteUInt32Number(io, mlu ->UsedEntries)) return FALSE;
if (!_cmsWriteUInt32Number(io, 12)) return FALSE;
HeaderSize = 12 * mlu ->UsedEntries + sizeof(_cmsTagBase);
for (i=0; i < mlu ->UsedEntries; i++) {
Len = mlu ->Entries[i].Len;
Offset = mlu ->Entries[i].StrW;
Len = (Len * sizeof(cmsUInt16Number)) / sizeof(wchar_t);
Offset = (Offset * sizeof(cmsUInt16Number)) / sizeof(wchar_t) + HeaderSize + 8;
if (!_cmsWriteUInt16Number(io, mlu ->Entries[i].Language)) return FALSE;
if (!_cmsWriteUInt16Number(io, mlu ->Entries[i].Country)) return FALSE;
if (!_cmsWriteUInt32Number(io, Len)) return FALSE;
if (!_cmsWriteUInt32Number(io, Offset)) return FALSE;
}
if (!_cmsWriteWCharArray(io, mlu ->PoolUsed / sizeof(wchar_t), (wchar_t*) mlu ->MemPool)) return FALSE;
return TRUE;
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
static
void* Type_MLU_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return (void*) cmsMLUdup((cmsMLU*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_MLU_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsMLUfree((cmsMLU*) Ptr);
return;
cmsUNUSED_PARAMETER(self);
}
// ********************************************************************************
// Type cmsSigLut8Type
// ********************************************************************************
// Decide which LUT type to use on writting
static
cmsTagTypeSignature DecideLUTtypeA2B(cmsFloat64Number ICCVersion, const void *Data)
{
cmsPipeline* Lut = (cmsPipeline*) Data;
if (ICCVersion < 4.0) {
if (Lut ->SaveAs8Bits) return cmsSigLut8Type;
return cmsSigLut16Type;
}
else {
return cmsSigLutAtoBType;
}
}
static
cmsTagTypeSignature DecideLUTtypeB2A(cmsFloat64Number ICCVersion, const void *Data)
{
cmsPipeline* Lut = (cmsPipeline*) Data;
if (ICCVersion < 4.0) {
if (Lut ->SaveAs8Bits) return cmsSigLut8Type;
return cmsSigLut16Type;
}
else {
return cmsSigLutBtoAType;
}
}
/*
This structure represents a colour transform using tables of 8-bit precision.
This type contains four processing elements: a 3 by 3 matrix (which shall be
the identity matrix unless the input colour space is XYZ), a set of one dimensional
input tables, a multidimensional lookup table, and a set of one dimensional output
tables. Data is processed using these elements via the following sequence:
(matrix) -> (1d input tables) -> (multidimensional lookup table - CLUT) -> (1d output tables)
Byte Position Field Length (bytes) Content Encoded as...
8 1 Number of Input Channels (i) uInt8Number
9 1 Number of Output Channels (o) uInt8Number
10 1 Number of CLUT grid points (identical for each side) (g) uInt8Number
11 1 Reserved for padding (fill with 00h)
12..15 4 Encoded e00 parameter s15Fixed16Number
*/
// Read 8 bit tables as gamma functions
static
cmsBool Read8bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsPipeline* lut, int nChannels)
{
cmsUInt8Number* Temp = NULL;
int i, j;
cmsToneCurve* Tables[cmsMAXCHANNELS];
if (nChannels > cmsMAXCHANNELS) return FALSE;
if (nChannels <= 0) return FALSE;
memset(Tables, 0, sizeof(Tables));
Temp = (cmsUInt8Number*) _cmsMalloc(ContextID, 256);
if (Temp == NULL) return FALSE;
for (i=0; i < nChannels; i++) {
Tables[i] = cmsBuildTabulatedToneCurve16(ContextID, 256, NULL);
if (Tables[i] == NULL) goto Error;
}
for (i=0; i < nChannels; i++) {
if (io ->Read(io, Temp, 256, 1) != 1) goto Error;
for (j=0; j < 256; j++)
Tables[i]->Table16[j] = (cmsUInt16Number) FROM_8_TO_16(Temp[j]);
}
_cmsFree(ContextID, Temp);
Temp = NULL;
if (!cmsPipelineInsertStage(lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, nChannels, Tables)))
goto Error;
for (i=0; i < nChannels; i++)
cmsFreeToneCurve(Tables[i]);
return TRUE;
Error:
for (i=0; i < nChannels; i++) {
if (Tables[i]) cmsFreeToneCurve(Tables[i]);
}
if (Temp) _cmsFree(ContextID, Temp);
return FALSE;
}
static
cmsBool Write8bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsUInt32Number n, _cmsStageToneCurvesData* Tables)
{
int j;
cmsUInt32Number i;
cmsUInt8Number val;
for (i=0; i < n; i++) {
if (Tables) {
// Usual case of identity curves
if ((Tables ->TheCurves[i]->nEntries == 2) &&
(Tables->TheCurves[i]->Table16[0] == 0) &&
(Tables->TheCurves[i]->Table16[1] == 65535)) {
for (j=0; j < 256; j++) {
if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) j)) return FALSE;
}
}
else
if (Tables ->TheCurves[i]->nEntries != 256) {
cmsSignalError(ContextID, cmsERROR_RANGE, "LUT8 needs 256 entries on prelinearization");
return FALSE;
}
else
for (j=0; j < 256; j++) {
val = (cmsUInt8Number) FROM_16_TO_8(Tables->TheCurves[i]->Table16[j]);
if (!_cmsWriteUInt8Number(io, val)) return FALSE;
}
}
}
return TRUE;
}
// Check overflow
static
cmsUInt32Number uipow(cmsUInt32Number n, cmsUInt32Number a, cmsUInt32Number b)
{
cmsUInt32Number rv = 1, rc;
if (a == 0) return 0;
if (n == 0) return 0;
for (; b > 0; b--) {
rv *= a;
// Check for overflow
if (rv > UINT_MAX / a) return (cmsUInt32Number) -1;
}
rc = rv * n;
if (rv != rc / n) return (cmsUInt32Number) -1;
return rc;
}
// That will create a MPE LUT with Matrix, pre tables, CLUT and post tables.
// 8 bit lut may be scaled easely to v4 PCS, but we need also to properly adjust
// PCS on BToAxx tags and AtoB if abstract. We need to fix input direction.
static
void *Type_LUT8_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsUInt8Number InputChannels, OutputChannels, CLUTpoints;
cmsUInt8Number* Temp = NULL;
cmsPipeline* NewLUT = NULL;
cmsUInt32Number nTabSize, i;
cmsFloat64Number Matrix[3*3];
*nItems = 0;
if (!_cmsReadUInt8Number(io, &InputChannels)) goto Error;
if (!_cmsReadUInt8Number(io, &OutputChannels)) goto Error;
if (!_cmsReadUInt8Number(io, &CLUTpoints)) goto Error;
if (CLUTpoints == 1) goto Error; // Impossible value, 0 for no CLUT and then 2 at least
// Padding
if (!_cmsReadUInt8Number(io, NULL)) goto Error;
// Do some checking
if (InputChannels > cmsMAXCHANNELS) goto Error;
if (OutputChannels > cmsMAXCHANNELS) goto Error;
// Allocates an empty Pipeline
NewLUT = cmsPipelineAlloc(self ->ContextID, InputChannels, OutputChannels);
if (NewLUT == NULL) goto Error;
// Read the Matrix
if (!_cmsRead15Fixed16Number(io, &Matrix[0])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[1])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[2])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[3])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[4])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[5])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[6])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[7])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[8])) goto Error;
// Only operates if not identity...
if ((InputChannels == 3) && !_cmsMAT3isIdentity((cmsMAT3*) Matrix)) {
if (!cmsPipelineInsertStage(NewLUT, cmsAT_BEGIN, cmsStageAllocMatrix(self ->ContextID, 3, 3, Matrix, NULL)))
goto Error;
}
// Get input tables
if (!Read8bitTables(self ->ContextID, io, NewLUT, InputChannels)) goto Error;
// Get 3D CLUT. Check the overflow....
nTabSize = uipow(OutputChannels, CLUTpoints, InputChannels);
if (nTabSize == (cmsUInt32Number) -1) goto Error;
if (nTabSize > 0) {
cmsUInt16Number *PtrW, *T;
PtrW = T = (cmsUInt16Number*) _cmsCalloc(self ->ContextID, nTabSize, sizeof(cmsUInt16Number));
if (T == NULL) goto Error;
Temp = (cmsUInt8Number*) _cmsMalloc(self ->ContextID, nTabSize);
if (Temp == NULL) {
_cmsFree(self ->ContextID, T);
goto Error;
}
if (io ->Read(io, Temp, nTabSize, 1) != 1) {
_cmsFree(self ->ContextID, T);
_cmsFree(self ->ContextID, Temp);
goto Error;
}
for (i = 0; i < nTabSize; i++) {
*PtrW++ = FROM_8_TO_16(Temp[i]);
}
_cmsFree(self ->ContextID, Temp);
Temp = NULL;
if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, cmsStageAllocCLut16bit(self ->ContextID, CLUTpoints, InputChannels, OutputChannels, T)))
goto Error;
_cmsFree(self ->ContextID, T);
}
// Get output tables
if (!Read8bitTables(self ->ContextID, io, NewLUT, OutputChannels)) goto Error;
*nItems = 1;
return NewLUT;
Error:
if (NewLUT != NULL) cmsPipelineFree(NewLUT);
return NULL;
cmsUNUSED_PARAMETER(SizeOfTag);
}
// We only allow a specific MPE structure: Matrix plus prelin, plus clut, plus post-lin.
static
cmsBool Type_LUT8_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsUInt32Number j, nTabSize;
cmsUInt8Number val;
cmsPipeline* NewLUT = (cmsPipeline*) Ptr;
cmsStage* mpe;
_cmsStageToneCurvesData* PreMPE = NULL, *PostMPE = NULL;
_cmsStageMatrixData* MatMPE = NULL;
_cmsStageCLutData* clut = NULL;
int clutPoints;
// Disassemble the LUT into components.
mpe = NewLUT -> Elements;
if (mpe ->Type == cmsSigMatrixElemType) {
MatMPE = (_cmsStageMatrixData*) mpe ->Data;
mpe = mpe -> Next;
}
if (mpe != NULL && mpe ->Type == cmsSigCurveSetElemType) {
PreMPE = (_cmsStageToneCurvesData*) mpe ->Data;
mpe = mpe -> Next;
}
if (mpe != NULL && mpe ->Type == cmsSigCLutElemType) {
clut = (_cmsStageCLutData*) mpe -> Data;
mpe = mpe ->Next;
}
if (mpe != NULL && mpe ->Type == cmsSigCurveSetElemType) {
PostMPE = (_cmsStageToneCurvesData*) mpe ->Data;
mpe = mpe -> Next;
}
// That should be all
if (mpe != NULL) {
cmsSignalError(mpe->ContextID, cmsERROR_UNKNOWN_EXTENSION, "LUT is not suitable to be saved as LUT8");
return FALSE;
}
if (clut == NULL)
clutPoints = 0;
else
clutPoints = clut->Params->nSamples[0];
if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) NewLUT ->InputChannels)) return FALSE;
if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) NewLUT ->OutputChannels)) return FALSE;
if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) clutPoints)) return FALSE;
if (!_cmsWriteUInt8Number(io, 0)) return FALSE; // Padding
if (MatMPE != NULL) {
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[0])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[1])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[2])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[3])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[4])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[5])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[6])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[7])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[8])) return FALSE;
}
else {
if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE;
}
// The prelinearization table
if (!Write8bitTables(self ->ContextID, io, NewLUT ->InputChannels, PreMPE)) return FALSE;
nTabSize = uipow(NewLUT->OutputChannels, clutPoints, NewLUT ->InputChannels);
if (nTabSize == (cmsUInt32Number) -1) return FALSE;
if (nTabSize > 0) {
// The 3D CLUT.
if (clut != NULL) {
for (j=0; j < nTabSize; j++) {
val = (cmsUInt8Number) FROM_16_TO_8(clut ->Tab.T[j]);
if (!_cmsWriteUInt8Number(io, val)) return FALSE;
}
}
}
// The postlinearization table
if (!Write8bitTables(self ->ContextID, io, NewLUT ->OutputChannels, PostMPE)) return FALSE;
return TRUE;
cmsUNUSED_PARAMETER(nItems);
}
static
void* Type_LUT8_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return (void*) cmsPipelineDup((cmsPipeline*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_LUT8_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsPipelineFree((cmsPipeline*) Ptr);
return;
cmsUNUSED_PARAMETER(self);
}
// ********************************************************************************
// Type cmsSigLut16Type
// ********************************************************************************
// Read 16 bit tables as gamma functions
static
cmsBool Read16bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsPipeline* lut, int nChannels, int nEntries)
{
int i;
cmsToneCurve* Tables[cmsMAXCHANNELS];
// Maybe an empty table? (this is a lcms extension)
if (nEntries <= 0) return TRUE;
// Check for malicious profiles
if (nEntries < 2) return FALSE;
if (nChannels > cmsMAXCHANNELS) return FALSE;
// Init table to zero
memset(Tables, 0, sizeof(Tables));
for (i=0; i < nChannels; i++) {
Tables[i] = cmsBuildTabulatedToneCurve16(ContextID, nEntries, NULL);
if (Tables[i] == NULL) goto Error;
if (!_cmsReadUInt16Array(io, nEntries, Tables[i]->Table16)) goto Error;
}
// Add the table (which may certainly be an identity, but this is up to the optimizer, not the reading code)
if (!cmsPipelineInsertStage(lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, nChannels, Tables)))
goto Error;
for (i=0; i < nChannels; i++)
cmsFreeToneCurve(Tables[i]);
return TRUE;
Error:
for (i=0; i < nChannels; i++) {
if (Tables[i]) cmsFreeToneCurve(Tables[i]);
}
return FALSE;
}
static
cmsBool Write16bitTables(cmsContext ContextID, cmsIOHANDLER* io, _cmsStageToneCurvesData* Tables)
{
int j;
cmsUInt32Number i;
cmsUInt16Number val;
int nEntries;
_cmsAssert(Tables != NULL);
nEntries = Tables->TheCurves[0]->nEntries;
for (i=0; i < Tables ->nCurves; i++) {
for (j=0; j < nEntries; j++) {
val = Tables->TheCurves[i]->Table16[j];
if (!_cmsWriteUInt16Number(io, val)) return FALSE;
}
}
return TRUE;
cmsUNUSED_PARAMETER(ContextID);
}
static
void *Type_LUT16_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsUInt8Number InputChannels, OutputChannels, CLUTpoints;
cmsPipeline* NewLUT = NULL;
cmsUInt32Number nTabSize;
cmsFloat64Number Matrix[3*3];
cmsUInt16Number InputEntries, OutputEntries;
*nItems = 0;
if (!_cmsReadUInt8Number(io, &InputChannels)) return NULL;
if (!_cmsReadUInt8Number(io, &OutputChannels)) return NULL;
if (!_cmsReadUInt8Number(io, &CLUTpoints)) return NULL; // 255 maximum
// Padding
if (!_cmsReadUInt8Number(io, NULL)) return NULL;
// Do some checking
if (InputChannels > cmsMAXCHANNELS) goto Error;
if (OutputChannels > cmsMAXCHANNELS) goto Error;
// Allocates an empty LUT
NewLUT = cmsPipelineAlloc(self ->ContextID, InputChannels, OutputChannels);
if (NewLUT == NULL) goto Error;
// Read the Matrix
if (!_cmsRead15Fixed16Number(io, &Matrix[0])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[1])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[2])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[3])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[4])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[5])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[6])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[7])) goto Error;
if (!_cmsRead15Fixed16Number(io, &Matrix[8])) goto Error;
// Only operates on 3 channels
if ((InputChannels == 3) && !_cmsMAT3isIdentity((cmsMAT3*) Matrix)) {
if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, cmsStageAllocMatrix(self ->ContextID, 3, 3, Matrix, NULL)))
goto Error;
}
if (!_cmsReadUInt16Number(io, &InputEntries)) goto Error;
if (!_cmsReadUInt16Number(io, &OutputEntries)) goto Error;
if (InputEntries > 0x7FFF || OutputEntries > 0x7FFF) goto Error;
if (CLUTpoints == 1) goto Error; // Impossible value, 0 for no CLUT and then 2 at least
// Get input tables
if (!Read16bitTables(self ->ContextID, io, NewLUT, InputChannels, InputEntries)) goto Error;
// Get 3D CLUT
nTabSize = uipow(OutputChannels, CLUTpoints, InputChannels);
if (nTabSize == (cmsUInt32Number) -1) goto Error;
if (nTabSize > 0) {
cmsUInt16Number *T;
T = (cmsUInt16Number*) _cmsCalloc(self ->ContextID, nTabSize, sizeof(cmsUInt16Number));
if (T == NULL) goto Error;
if (!_cmsReadUInt16Array(io, nTabSize, T)) {
_cmsFree(self ->ContextID, T);
goto Error;
}
if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, cmsStageAllocCLut16bit(self ->ContextID, CLUTpoints, InputChannels, OutputChannels, T))) {
_cmsFree(self ->ContextID, T);
goto Error;
}
_cmsFree(self ->ContextID, T);
}
// Get output tables
if (!Read16bitTables(self ->ContextID, io, NewLUT, OutputChannels, OutputEntries)) goto Error;
*nItems = 1;
return NewLUT;
Error:
if (NewLUT != NULL) cmsPipelineFree(NewLUT);
return NULL;
cmsUNUSED_PARAMETER(SizeOfTag);
}
// We only allow some specific MPE structures: Matrix plus prelin, plus clut, plus post-lin.
// Some empty defaults are created for missing parts
static
cmsBool Type_LUT16_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsUInt32Number nTabSize;
cmsPipeline* NewLUT = (cmsPipeline*) Ptr;
cmsStage* mpe;
_cmsStageToneCurvesData* PreMPE = NULL, *PostMPE = NULL;
_cmsStageMatrixData* MatMPE = NULL;
_cmsStageCLutData* clut = NULL;
int i, InputChannels, OutputChannels, clutPoints;
// Disassemble the LUT into components.
mpe = NewLUT -> Elements;
if (mpe != NULL && mpe ->Type == cmsSigMatrixElemType) {
MatMPE = (_cmsStageMatrixData*) mpe ->Data;
mpe = mpe -> Next;
}
if (mpe != NULL && mpe ->Type == cmsSigCurveSetElemType) {
PreMPE = (_cmsStageToneCurvesData*) mpe ->Data;
mpe = mpe -> Next;
}
if (mpe != NULL && mpe ->Type == cmsSigCLutElemType) {
clut = (_cmsStageCLutData*) mpe -> Data;
mpe = mpe ->Next;
}
if (mpe != NULL && mpe ->Type == cmsSigCurveSetElemType) {
PostMPE = (_cmsStageToneCurvesData*) mpe ->Data;
mpe = mpe -> Next;
}
// That should be all
if (mpe != NULL) {
cmsSignalError(mpe->ContextID, cmsERROR_UNKNOWN_EXTENSION, "LUT is not suitable to be saved as LUT16");
return FALSE;
}
InputChannels = cmsPipelineInputChannels(NewLUT);
OutputChannels = cmsPipelineOutputChannels(NewLUT);
if (clut == NULL)
clutPoints = 0;
else
clutPoints = clut->Params->nSamples[0];
if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) InputChannels)) return FALSE;
if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) OutputChannels)) return FALSE;
if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) clutPoints)) return FALSE;
if (!_cmsWriteUInt8Number(io, 0)) return FALSE; // Padding
if (MatMPE != NULL) {
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[0])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[1])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[2])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[3])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[4])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[5])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[6])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[7])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[8])) return FALSE;
}
else {
if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE;
}
if (PreMPE != NULL) {
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) PreMPE ->TheCurves[0]->nEntries)) return FALSE;
} else {
if (!_cmsWriteUInt16Number(io, 2)) return FALSE;
}
if (PostMPE != NULL) {
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) PostMPE ->TheCurves[0]->nEntries)) return FALSE;
} else {
if (!_cmsWriteUInt16Number(io, 2)) return FALSE;
}
// The prelinearization table
if (PreMPE != NULL) {
if (!Write16bitTables(self ->ContextID, io, PreMPE)) return FALSE;
}
else {
for (i=0; i < InputChannels; i++) {
if (!_cmsWriteUInt16Number(io, 0)) return FALSE;
if (!_cmsWriteUInt16Number(io, 0xffff)) return FALSE;
}
}
nTabSize = uipow(OutputChannels, clutPoints, InputChannels);
if (nTabSize == (cmsUInt32Number) -1) return FALSE;
if (nTabSize > 0) {
// The 3D CLUT.
if (clut != NULL) {
if (!_cmsWriteUInt16Array(io, nTabSize, clut->Tab.T)) return FALSE;
}
}
// The postlinearization table
if (PostMPE != NULL) {
if (!Write16bitTables(self ->ContextID, io, PostMPE)) return FALSE;
}
else {
for (i=0; i < OutputChannels; i++) {
if (!_cmsWriteUInt16Number(io, 0)) return FALSE;
if (!_cmsWriteUInt16Number(io, 0xffff)) return FALSE;
}
}
return TRUE;
cmsUNUSED_PARAMETER(nItems);
}
static
void* Type_LUT16_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return (void*) cmsPipelineDup((cmsPipeline*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_LUT16_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsPipelineFree((cmsPipeline*) Ptr);
return;
cmsUNUSED_PARAMETER(self);
}
// ********************************************************************************
// Type cmsSigLutAToBType
// ********************************************************************************
// V4 stuff. Read matrix for LutAtoB and LutBtoA
static
cmsStage* ReadMatrix(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number Offset)
{
cmsFloat64Number dMat[3*3];
cmsFloat64Number dOff[3];
cmsStage* Mat;
// Go to address
if (!io -> Seek(io, Offset)) return NULL;
// Read the Matrix
if (!_cmsRead15Fixed16Number(io, &dMat[0])) return NULL;
if (!_cmsRead15Fixed16Number(io, &dMat[1])) return NULL;
if (!_cmsRead15Fixed16Number(io, &dMat[2])) return NULL;
if (!_cmsRead15Fixed16Number(io, &dMat[3])) return NULL;
if (!_cmsRead15Fixed16Number(io, &dMat[4])) return NULL;
if (!_cmsRead15Fixed16Number(io, &dMat[5])) return NULL;
if (!_cmsRead15Fixed16Number(io, &dMat[6])) return NULL;
if (!_cmsRead15Fixed16Number(io, &dMat[7])) return NULL;
if (!_cmsRead15Fixed16Number(io, &dMat[8])) return NULL;
if (!_cmsRead15Fixed16Number(io, &dOff[0])) return NULL;
if (!_cmsRead15Fixed16Number(io, &dOff[1])) return NULL;
if (!_cmsRead15Fixed16Number(io, &dOff[2])) return NULL;
Mat = cmsStageAllocMatrix(self ->ContextID, 3, 3, dMat, dOff);
return Mat;
}
// V4 stuff. Read CLUT part for LutAtoB and LutBtoA
static
cmsStage* ReadCLUT(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number Offset, int InputChannels, int OutputChannels)
{
cmsUInt8Number gridPoints8[cmsMAXCHANNELS]; // Number of grid points in each dimension.
cmsUInt32Number GridPoints[cmsMAXCHANNELS], i;
cmsUInt8Number Precision;
cmsStage* CLUT;
_cmsStageCLutData* Data;
if (!io -> Seek(io, Offset)) return NULL;
if (io -> Read(io, gridPoints8, cmsMAXCHANNELS, 1) != 1) return NULL;
for (i=0; i < cmsMAXCHANNELS; i++) {
if (gridPoints8[i] == 1) return NULL; // Impossible value, 0 for no CLUT and then 2 at least
GridPoints[i] = gridPoints8[i];
}
if (!_cmsReadUInt8Number(io, &Precision)) return NULL;
if (!_cmsReadUInt8Number(io, NULL)) return NULL;
if (!_cmsReadUInt8Number(io, NULL)) return NULL;
if (!_cmsReadUInt8Number(io, NULL)) return NULL;
CLUT = cmsStageAllocCLut16bitGranular(self ->ContextID, GridPoints, InputChannels, OutputChannels, NULL);
if (CLUT == NULL) return NULL;
Data = (_cmsStageCLutData*) CLUT ->Data;
// Precision can be 1 or 2 bytes
if (Precision == 1) {
cmsUInt8Number v;
for (i=0; i < Data ->nEntries; i++) {
if (io ->Read(io, &v, sizeof(cmsUInt8Number), 1) != 1) return NULL;
Data ->Tab.T[i] = FROM_8_TO_16(v);
}
}
else
if (Precision == 2) {
if (!_cmsReadUInt16Array(io, Data->nEntries, Data ->Tab.T)) {
cmsStageFree(CLUT);
return NULL;
}
}
else {
cmsStageFree(CLUT);
cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown precision of '%d'", Precision);
return NULL;
}
return CLUT;
}
static
cmsToneCurve* ReadEmbeddedCurve(struct _cms_typehandler_struct* self, cmsIOHANDLER* io)
{
cmsTagTypeSignature BaseType;
cmsUInt32Number nItems;
BaseType = _cmsReadTypeBase(io);
switch (BaseType) {
case cmsSigCurveType:
return (cmsToneCurve*) Type_Curve_Read(self, io, &nItems, 0);
case cmsSigParametricCurveType:
return (cmsToneCurve*) Type_ParametricCurve_Read(self, io, &nItems, 0);
default:
{
char String[5];
_cmsTagSignature2String(String, (cmsTagSignature) BaseType);
cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown curve type '%s'", String);
}
return NULL;
}
}
// Read a set of curves from specific offset
static
cmsStage* ReadSetOfCurves(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number Offset, cmsUInt32Number nCurves)
{
cmsToneCurve* Curves[cmsMAXCHANNELS];
cmsUInt32Number i;
cmsStage* Lin = NULL;
if (nCurves > cmsMAXCHANNELS) return FALSE;
if (!io -> Seek(io, Offset)) return FALSE;
for (i=0; i < nCurves; i++)
Curves[i] = NULL;
for (i=0; i < nCurves; i++) {
Curves[i] = ReadEmbeddedCurve(self, io);
if (Curves[i] == NULL) goto Error;
if (!_cmsReadAlignment(io)) goto Error;
}
Lin = cmsStageAllocToneCurves(self ->ContextID, nCurves, Curves);
Error:
for (i=0; i < nCurves; i++)
cmsFreeToneCurve(Curves[i]);
return Lin;
}
// LutAtoB type
// This structure represents a colour transform. The type contains up to five processing
// elements which are stored in the AtoBTag tag in the following order: a set of one
// dimensional curves, a 3 by 3 matrix with offset terms, a set of one dimensional curves,
// a multidimensional lookup table, and a set of one dimensional output curves.
// Data are processed using these elements via the following sequence:
//
//("A" curves) -> (multidimensional lookup table - CLUT) -> ("M" curves) -> (matrix) -> ("B" curves).
//
/*
It is possible to use any or all of these processing elements. At least one processing element
must be included.Only the following combinations are allowed:
B
M - Matrix - B
A - CLUT - B
A - CLUT - M - Matrix - B
*/
static
void* Type_LUTA2B_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsUInt32Number BaseOffset;
cmsUInt8Number inputChan; // Number of input channels
cmsUInt8Number outputChan; // Number of output channels
cmsUInt32Number offsetB; // Offset to first "B" curve
cmsUInt32Number offsetMat; // Offset to matrix
cmsUInt32Number offsetM; // Offset to first "M" curve
cmsUInt32Number offsetC; // Offset to CLUT
cmsUInt32Number offsetA; // Offset to first "A" curve
cmsPipeline* NewLUT = NULL;
BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
if (!_cmsReadUInt8Number(io, &inputChan)) return NULL;
if (!_cmsReadUInt8Number(io, &outputChan)) return NULL;
if (!_cmsReadUInt16Number(io, NULL)) return NULL;
if (!_cmsReadUInt32Number(io, &offsetB)) return NULL;
if (!_cmsReadUInt32Number(io, &offsetMat)) return NULL;
if (!_cmsReadUInt32Number(io, &offsetM)) return NULL;
if (!_cmsReadUInt32Number(io, &offsetC)) return NULL;
if (!_cmsReadUInt32Number(io, &offsetA)) return NULL;
// Allocates an empty LUT
NewLUT = cmsPipelineAlloc(self ->ContextID, inputChan, outputChan);
if (NewLUT == NULL) return NULL;
if (offsetA!= 0) {
if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetA, inputChan)))
goto Error;
}
if (offsetC != 0) {
if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadCLUT(self, io, BaseOffset + offsetC, inputChan, outputChan)))
goto Error;
}
if (offsetM != 0) {
if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetM, outputChan)))
goto Error;
}
if (offsetMat != 0) {
if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadMatrix(self, io, BaseOffset + offsetMat)))
goto Error;
}
if (offsetB != 0) {
if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetB, outputChan)))
goto Error;
}
*nItems = 1;
return NewLUT;
Error:
cmsPipelineFree(NewLUT);
return NULL;
cmsUNUSED_PARAMETER(SizeOfTag);
}
// Write a set of curves
static
cmsBool WriteMatrix(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsStage* mpe)
{
_cmsStageMatrixData* m = (_cmsStageMatrixData*) mpe -> Data;
// Write the Matrix
if (!_cmsWrite15Fixed16Number(io, m -> Double[0])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, m -> Double[1])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, m -> Double[2])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, m -> Double[3])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, m -> Double[4])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, m -> Double[5])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, m -> Double[6])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, m -> Double[7])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, m -> Double[8])) return FALSE;
if (m ->Offset != NULL) {
if (!_cmsWrite15Fixed16Number(io, m -> Offset[0])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, m -> Offset[1])) return FALSE;
if (!_cmsWrite15Fixed16Number(io, m -> Offset[2])) return FALSE;
}
else {
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
}
return TRUE;
cmsUNUSED_PARAMETER(self);
}
// Write a set of curves
static
cmsBool WriteSetOfCurves(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsTagTypeSignature Type, cmsStage* mpe)
{
cmsUInt32Number i, n;
cmsTagTypeSignature CurrentType;
cmsToneCurve** Curves;
n = cmsStageOutputChannels(mpe);
Curves = _cmsStageGetPtrToCurveSet(mpe);
for (i=0; i < n; i++) {
// If this is a table-based curve, use curve type even on V4
CurrentType = Type;
if ((Curves[i] ->nSegments == 0)||
((Curves[i]->nSegments == 2) && (Curves[i] ->Segments[1].Type == 0)) )
CurrentType = cmsSigCurveType;
else
if (Curves[i] ->Segments[0].Type < 0)
CurrentType = cmsSigCurveType;
if (!_cmsWriteTypeBase(io, CurrentType)) return FALSE;
switch (CurrentType) {
case cmsSigCurveType:
if (!Type_Curve_Write(self, io, Curves[i], 1)) return FALSE;
break;
case cmsSigParametricCurveType:
if (!Type_ParametricCurve_Write(self, io, Curves[i], 1)) return FALSE;
break;
default:
{
char String[5];
_cmsTagSignature2String(String, (cmsTagSignature) Type);
cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown curve type '%s'", String);
}
return FALSE;
}
if (!_cmsWriteAlignment(io)) return FALSE;
}
return TRUE;
}
static
cmsBool WriteCLUT(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt8Number Precision, cmsStage* mpe)
{
cmsUInt8Number gridPoints[cmsMAXCHANNELS]; // Number of grid points in each dimension.
cmsUInt32Number i;
_cmsStageCLutData* CLUT = ( _cmsStageCLutData*) mpe -> Data;
if (CLUT ->HasFloatValues) {
cmsSignalError(self ->ContextID, cmsERROR_NOT_SUITABLE, "Cannot save floating point data, CLUT are 8 or 16 bit only");
return FALSE;
}
memset(gridPoints, 0, sizeof(gridPoints));
for (i=0; i < (cmsUInt32Number) CLUT ->Params ->nInputs; i++)
gridPoints[i] = (cmsUInt8Number) CLUT ->Params ->nSamples[i];
if (!io -> Write(io, cmsMAXCHANNELS*sizeof(cmsUInt8Number), gridPoints)) return FALSE;
if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) Precision)) return FALSE;
if (!_cmsWriteUInt8Number(io, 0)) return FALSE;
if (!_cmsWriteUInt8Number(io, 0)) return FALSE;
if (!_cmsWriteUInt8Number(io, 0)) return FALSE;
// Precision can be 1 or 2 bytes
if (Precision == 1) {
for (i=0; i < CLUT->nEntries; i++) {
if (!_cmsWriteUInt8Number(io, FROM_16_TO_8(CLUT->Tab.T[i]))) return FALSE;
}
}
else
if (Precision == 2) {
if (!_cmsWriteUInt16Array(io, CLUT->nEntries, CLUT ->Tab.T)) return FALSE;
}
else {
cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown precision of '%d'", Precision);
return FALSE;
}
if (!_cmsWriteAlignment(io)) return FALSE;
return TRUE;
}
static
cmsBool Type_LUTA2B_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsPipeline* Lut = (cmsPipeline*) Ptr;
int inputChan, outputChan;
cmsStage *A = NULL, *B = NULL, *M = NULL;
cmsStage * Matrix = NULL;
cmsStage * CLUT = NULL;
cmsUInt32Number offsetB = 0, offsetMat = 0, offsetM = 0, offsetC = 0, offsetA = 0;
cmsUInt32Number BaseOffset, DirectoryPos, CurrentPos;
// Get the base for all offsets
BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
if (Lut ->Elements != NULL)
if (!cmsPipelineCheckAndRetreiveStages(Lut, 1, cmsSigCurveSetElemType, &B))
if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType, &M, &Matrix, &B))
if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &A, &CLUT, &B))
if (!cmsPipelineCheckAndRetreiveStages(Lut, 5, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType,
cmsSigMatrixElemType, cmsSigCurveSetElemType, &A, &CLUT, &M, &Matrix, &B)) {
cmsSignalError(self->ContextID, cmsERROR_NOT_SUITABLE, "LUT is not suitable to be saved as LutAToB");
return FALSE;
}
// Get input, output channels
inputChan = cmsPipelineInputChannels(Lut);
outputChan = cmsPipelineOutputChannels(Lut);
// Write channel count
if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) inputChan)) return FALSE;
if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) outputChan)) return FALSE;
if (!_cmsWriteUInt16Number(io, 0)) return FALSE;
// Keep directory to be filled latter
DirectoryPos = io ->Tell(io);
// Write the directory
if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
if (A != NULL) {
offsetA = io ->Tell(io) - BaseOffset;
if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, A)) return FALSE;
}
if (CLUT != NULL) {
offsetC = io ->Tell(io) - BaseOffset;
if (!WriteCLUT(self, io, Lut ->SaveAs8Bits ? 1 : 2, CLUT)) return FALSE;
}
if (M != NULL) {
offsetM = io ->Tell(io) - BaseOffset;
if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, M)) return FALSE;
}
if (Matrix != NULL) {
offsetMat = io ->Tell(io) - BaseOffset;
if (!WriteMatrix(self, io, Matrix)) return FALSE;
}
if (B != NULL) {
offsetB = io ->Tell(io) - BaseOffset;
if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, B)) return FALSE;
}
CurrentPos = io ->Tell(io);
if (!io ->Seek(io, DirectoryPos)) return FALSE;
if (!_cmsWriteUInt32Number(io, offsetB)) return FALSE;
if (!_cmsWriteUInt32Number(io, offsetMat)) return FALSE;
if (!_cmsWriteUInt32Number(io, offsetM)) return FALSE;
if (!_cmsWriteUInt32Number(io, offsetC)) return FALSE;
if (!_cmsWriteUInt32Number(io, offsetA)) return FALSE;
if (!io ->Seek(io, CurrentPos)) return FALSE;
return TRUE;
cmsUNUSED_PARAMETER(nItems);
}
static
void* Type_LUTA2B_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return (void*) cmsPipelineDup((cmsPipeline*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_LUTA2B_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsPipelineFree((cmsPipeline*) Ptr);
return;
cmsUNUSED_PARAMETER(self);
}
// LutBToA type
static
void* Type_LUTB2A_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsUInt8Number inputChan; // Number of input channels
cmsUInt8Number outputChan; // Number of output channels
cmsUInt32Number BaseOffset; // Actual position in file
cmsUInt32Number offsetB; // Offset to first "B" curve
cmsUInt32Number offsetMat; // Offset to matrix
cmsUInt32Number offsetM; // Offset to first "M" curve
cmsUInt32Number offsetC; // Offset to CLUT
cmsUInt32Number offsetA; // Offset to first "A" curve
cmsPipeline* NewLUT = NULL;
BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
if (!_cmsReadUInt8Number(io, &inputChan)) return NULL;
if (!_cmsReadUInt8Number(io, &outputChan)) return NULL;
// Padding
if (!_cmsReadUInt16Number(io, NULL)) return NULL;
if (!_cmsReadUInt32Number(io, &offsetB)) return NULL;
if (!_cmsReadUInt32Number(io, &offsetMat)) return NULL;
if (!_cmsReadUInt32Number(io, &offsetM)) return NULL;
if (!_cmsReadUInt32Number(io, &offsetC)) return NULL;
if (!_cmsReadUInt32Number(io, &offsetA)) return NULL;
// Allocates an empty LUT
NewLUT = cmsPipelineAlloc(self ->ContextID, inputChan, outputChan);
if (NewLUT == NULL) return NULL;
if (offsetB != 0) {
if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetB, inputChan)))
goto Error;
}
if (offsetMat != 0) {
if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadMatrix(self, io, BaseOffset + offsetMat)))
goto Error;
}
if (offsetM != 0) {
if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetM, inputChan)))
goto Error;
}
if (offsetC != 0) {
if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadCLUT(self, io, BaseOffset + offsetC, inputChan, outputChan)))
goto Error;
}
if (offsetA!= 0) {
if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetA, outputChan)))
goto Error;
}
*nItems = 1;
return NewLUT;
Error:
cmsPipelineFree(NewLUT);
return NULL;
cmsUNUSED_PARAMETER(SizeOfTag);
}
/*
B
B - Matrix - M
B - CLUT - A
B - Matrix - M - CLUT - A
*/
static
cmsBool Type_LUTB2A_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsPipeline* Lut = (cmsPipeline*) Ptr;
int inputChan, outputChan;
cmsStage *A = NULL, *B = NULL, *M = NULL;
cmsStage *Matrix = NULL;
cmsStage *CLUT = NULL;
cmsUInt32Number offsetB = 0, offsetMat = 0, offsetM = 0, offsetC = 0, offsetA = 0;
cmsUInt32Number BaseOffset, DirectoryPos, CurrentPos;
BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
if (!cmsPipelineCheckAndRetreiveStages(Lut, 1, cmsSigCurveSetElemType, &B))
if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType, &B, &Matrix, &M))
if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &B, &CLUT, &A))
if (!cmsPipelineCheckAndRetreiveStages(Lut, 5, cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType,
cmsSigCLutElemType, cmsSigCurveSetElemType, &B, &Matrix, &M, &CLUT, &A)) {
cmsSignalError(self->ContextID, cmsERROR_NOT_SUITABLE, "LUT is not suitable to be saved as LutBToA");
return FALSE;
}
inputChan = cmsPipelineInputChannels(Lut);
outputChan = cmsPipelineOutputChannels(Lut);
if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) inputChan)) return FALSE;
if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) outputChan)) return FALSE;
if (!_cmsWriteUInt16Number(io, 0)) return FALSE;
DirectoryPos = io ->Tell(io);
if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
if (A != NULL) {
offsetA = io ->Tell(io) - BaseOffset;
if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, A)) return FALSE;
}
if (CLUT != NULL) {
offsetC = io ->Tell(io) - BaseOffset;
if (!WriteCLUT(self, io, Lut ->SaveAs8Bits ? 1 : 2, CLUT)) return FALSE;
}
if (M != NULL) {
offsetM = io ->Tell(io) - BaseOffset;
if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, M)) return FALSE;
}
if (Matrix != NULL) {
offsetMat = io ->Tell(io) - BaseOffset;
if (!WriteMatrix(self, io, Matrix)) return FALSE;
}
if (B != NULL) {
offsetB = io ->Tell(io) - BaseOffset;
if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, B)) return FALSE;
}
CurrentPos = io ->Tell(io);
if (!io ->Seek(io, DirectoryPos)) return FALSE;
if (!_cmsWriteUInt32Number(io, offsetB)) return FALSE;
if (!_cmsWriteUInt32Number(io, offsetMat)) return FALSE;
if (!_cmsWriteUInt32Number(io, offsetM)) return FALSE;
if (!_cmsWriteUInt32Number(io, offsetC)) return FALSE;
if (!_cmsWriteUInt32Number(io, offsetA)) return FALSE;
if (!io ->Seek(io, CurrentPos)) return FALSE;
return TRUE;
cmsUNUSED_PARAMETER(nItems);
}
static
void* Type_LUTB2A_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return (void*) cmsPipelineDup((cmsPipeline*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_LUTB2A_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsPipelineFree((cmsPipeline*) Ptr);
return;
cmsUNUSED_PARAMETER(self);
}
// ********************************************************************************
// Type cmsSigColorantTableType
// ********************************************************************************
/*
The purpose of this tag is to identify the colorants used in the profile by a
unique name and set of XYZ or L*a*b* values to give the colorant an unambiguous
value. The first colorant listed is the colorant of the first device channel of
a lut tag. The second colorant listed is the colorant of the second device channel
of a lut tag, and so on.
*/
static
void *Type_ColorantTable_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsUInt32Number i, Count;
cmsNAMEDCOLORLIST* List;
char Name[34];
cmsUInt16Number PCS[3];
if (!_cmsReadUInt32Number(io, &Count)) return NULL;
if (Count > cmsMAXCHANNELS) {
cmsSignalError(self->ContextID, cmsERROR_RANGE, "Too many colorants '%d'", Count);
return NULL;
}
List = cmsAllocNamedColorList(self ->ContextID, Count, 0, "", "");
for (i=0; i < Count; i++) {
if (io ->Read(io, Name, 32, 1) != 1) goto Error;
Name[33] = 0;
if (!_cmsReadUInt16Array(io, 3, PCS)) goto Error;
if (!cmsAppendNamedColor(List, Name, PCS, NULL)) goto Error;
}
*nItems = 1;
return List;
Error:
*nItems = 0;
cmsFreeNamedColorList(List);
return NULL;
cmsUNUSED_PARAMETER(SizeOfTag);
}
// Saves a colorant table. It is using the named color structure for simplicity sake
static
cmsBool Type_ColorantTable_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsNAMEDCOLORLIST* NamedColorList = (cmsNAMEDCOLORLIST*) Ptr;
int i, nColors;
nColors = cmsNamedColorCount(NamedColorList);
if (!_cmsWriteUInt32Number(io, nColors)) return FALSE;
for (i=0; i < nColors; i++) {
char root[33];
cmsUInt16Number PCS[3];
if (!cmsNamedColorInfo(NamedColorList, i, root, NULL, NULL, PCS, NULL)) return 0;
root[32] = 0;
if (!io ->Write(io, 32, root)) return FALSE;
if (!_cmsWriteUInt16Array(io, 3, PCS)) return FALSE;
}
return TRUE;
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
static
void* Type_ColorantTable_Dup(struct _cms_typehandler_struct* self, const void* Ptr, cmsUInt32Number n)
{
cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) Ptr;
return (void*) cmsDupNamedColorList(nc);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_ColorantTable_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsFreeNamedColorList((cmsNAMEDCOLORLIST*) Ptr);
return;
cmsUNUSED_PARAMETER(self);
}
// ********************************************************************************
// Type cmsSigNamedColor2Type
// ********************************************************************************
//
//The namedColor2Type is a count value and array of structures that provide color
//coordinates for 7-bit ASCII color names. For each named color, a PCS and optional
//device representation of the color are given. Both representations are 16-bit values.
//The device representation corresponds to the header�s �color space of data� field.
//This representation should be consistent with the �number of device components�
//field in the namedColor2Type. If this field is 0, device coordinates are not provided.
//The PCS representation corresponds to the header�s PCS field. The PCS representation
//is always provided. Color names are fixed-length, 32-byte fields including null
//termination. In order to maintain maximum portability, it is strongly recommended
//that special characters of the 7-bit ASCII set not be used.
static
void *Type_NamedColor_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsUInt32Number vendorFlag; // Bottom 16 bits for ICC use
cmsUInt32Number count; // Count of named colors
cmsUInt32Number nDeviceCoords; // Num of device coordinates
char prefix[32]; // Prefix for each color name
char suffix[32]; // Suffix for each color name
cmsNAMEDCOLORLIST* v;
cmsUInt32Number i;
*nItems = 0;
if (!_cmsReadUInt32Number(io, &vendorFlag)) return NULL;
if (!_cmsReadUInt32Number(io, &count)) return NULL;
if (!_cmsReadUInt32Number(io, &nDeviceCoords)) return NULL;
if (io -> Read(io, prefix, 32, 1) != 1) return NULL;
if (io -> Read(io, suffix, 32, 1) != 1) return NULL;
prefix[31] = suffix[31] = 0;
v = cmsAllocNamedColorList(self ->ContextID, count, nDeviceCoords, prefix, suffix);
if (v == NULL) {
cmsSignalError(self->ContextID, cmsERROR_RANGE, "Too many named colors '%d'", count);
return NULL;
}
if (nDeviceCoords > cmsMAXCHANNELS) {
cmsSignalError(self->ContextID, cmsERROR_RANGE, "Too many device coordinates '%d'", nDeviceCoords);
return 0;
}
for (i=0; i < count; i++) {
cmsUInt16Number PCS[3];
cmsUInt16Number Colorant[cmsMAXCHANNELS];
char Root[33];
memset(Colorant, 0, sizeof(Colorant));
if (io -> Read(io, Root, 32, 1) != 1) return NULL;
Root[32] = 0; // To prevent exploits
if (!_cmsReadUInt16Array(io, 3, PCS)) goto Error;
if (!_cmsReadUInt16Array(io, nDeviceCoords, Colorant)) goto Error;
if (!cmsAppendNamedColor(v, Root, PCS, Colorant)) goto Error;
}
*nItems = 1;
return (void*) v ;
Error:
cmsFreeNamedColorList(v);
return NULL;
cmsUNUSED_PARAMETER(SizeOfTag);
}
// Saves a named color list into a named color profile
static
cmsBool Type_NamedColor_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsNAMEDCOLORLIST* NamedColorList = (cmsNAMEDCOLORLIST*) Ptr;
char prefix[33]; // Prefix for each color name
char suffix[33]; // Suffix for each color name
int i, nColors;
nColors = cmsNamedColorCount(NamedColorList);
if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
if (!_cmsWriteUInt32Number(io, nColors)) return FALSE;
if (!_cmsWriteUInt32Number(io, NamedColorList ->ColorantCount)) return FALSE;
strncpy(prefix, (const char*) NamedColorList->Prefix, 32);
strncpy(suffix, (const char*) NamedColorList->Suffix, 32);
suffix[32] = prefix[32] = 0;
if (!io ->Write(io, 32, prefix)) return FALSE;
if (!io ->Write(io, 32, suffix)) return FALSE;
for (i=0; i < nColors; i++) {
cmsUInt16Number PCS[3];
cmsUInt16Number Colorant[cmsMAXCHANNELS];
char Root[33];
if (!cmsNamedColorInfo(NamedColorList, i, Root, NULL, NULL, PCS, Colorant)) return 0;
Root[32] = 0;
if (!io ->Write(io, 32 , Root)) return FALSE;
if (!_cmsWriteUInt16Array(io, 3, PCS)) return FALSE;
if (!_cmsWriteUInt16Array(io, NamedColorList ->ColorantCount, Colorant)) return FALSE;
}
return TRUE;
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
static
void* Type_NamedColor_Dup(struct _cms_typehandler_struct* self, const void* Ptr, cmsUInt32Number n)
{
cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) Ptr;
return (void*) cmsDupNamedColorList(nc);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_NamedColor_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsFreeNamedColorList((cmsNAMEDCOLORLIST*) Ptr);
return;
cmsUNUSED_PARAMETER(self);
}
// ********************************************************************************
// Type cmsSigProfileSequenceDescType
// ********************************************************************************
// This type is an array of structures, each of which contains information from the
// header fields and tags from the original profiles which were combined to create
// the final profile. The order of the structures is the order in which the profiles
// were combined and includes a structure for the final profile. This provides a
// description of the profile sequence from source to destination,
// typically used with the DeviceLink profile.
static
cmsBool ReadEmbeddedText(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsMLU** mlu, cmsUInt32Number SizeOfTag)
{
cmsTagTypeSignature BaseType;
cmsUInt32Number nItems;
BaseType = _cmsReadTypeBase(io);
switch (BaseType) {
case cmsSigTextType:
if (*mlu) cmsMLUfree(*mlu);
*mlu = (cmsMLU*)Type_Text_Read(self, io, &nItems, SizeOfTag);
return (*mlu != NULL);
case cmsSigTextDescriptionType:
if (*mlu) cmsMLUfree(*mlu);
*mlu = (cmsMLU*) Type_Text_Description_Read(self, io, &nItems, SizeOfTag);
return (*mlu != NULL);
/*
TBD: Size is needed for MLU, and we have no idea on which is the available size
*/
case cmsSigMultiLocalizedUnicodeType:
if (*mlu) cmsMLUfree(*mlu);
*mlu = (cmsMLU*) Type_MLU_Read(self, io, &nItems, SizeOfTag);
return (*mlu != NULL);
default: return FALSE;
}
}
static
void *Type_ProfileSequenceDesc_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsSEQ* OutSeq;
cmsUInt32Number i, Count;
*nItems = 0;
if (!_cmsReadUInt32Number(io, &Count)) return NULL;
if (SizeOfTag < sizeof(cmsUInt32Number)) return NULL;
SizeOfTag -= sizeof(cmsUInt32Number);
OutSeq = cmsAllocProfileSequenceDescription(self ->ContextID, Count);
if (OutSeq == NULL) return NULL;
OutSeq ->n = Count;
// Get structures as well
for (i=0; i < Count; i++) {
cmsPSEQDESC* sec = &OutSeq -> seq[i];
if (!_cmsReadUInt32Number(io, &sec ->deviceMfg)) goto Error;
if (SizeOfTag < sizeof(cmsUInt32Number)) goto Error;
SizeOfTag -= sizeof(cmsUInt32Number);
if (!_cmsReadUInt32Number(io, &sec ->deviceModel)) goto Error;
if (SizeOfTag < sizeof(cmsUInt32Number)) goto Error;
SizeOfTag -= sizeof(cmsUInt32Number);
if (!_cmsReadUInt64Number(io, &sec ->attributes)) goto Error;
if (SizeOfTag < sizeof(cmsUInt64Number)) goto Error;
SizeOfTag -= sizeof(cmsUInt64Number);
if (!_cmsReadUInt32Number(io, (cmsUInt32Number *)&sec ->technology)) goto Error;
if (SizeOfTag < sizeof(cmsUInt32Number)) goto Error;
SizeOfTag -= sizeof(cmsUInt32Number);
if (!ReadEmbeddedText(self, io, &sec ->Manufacturer, SizeOfTag)) goto Error;
if (!ReadEmbeddedText(self, io, &sec ->Model, SizeOfTag)) goto Error;
}
*nItems = 1;
return OutSeq;
Error:
cmsFreeProfileSequenceDescription(OutSeq);
return NULL;
}
// Aux--Embed a text description type. It can be of type text description or multilocalized unicode
// and it depends of the version number passed on cmsTagDescriptor structure instead of stack
static
cmsBool SaveDescription(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsMLU* Text)
{
if (self ->ICCVersion < 0x4000000) {
if (!_cmsWriteTypeBase(io, cmsSigTextDescriptionType)) return FALSE;
return Type_Text_Description_Write(self, io, Text, 1);
}
else {
if (!_cmsWriteTypeBase(io, cmsSigMultiLocalizedUnicodeType)) return FALSE;
return Type_MLU_Write(self, io, Text, 1);
}
}
static
cmsBool Type_ProfileSequenceDesc_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsSEQ* Seq = (cmsSEQ*) Ptr;
cmsUInt32Number i;
if (!_cmsWriteUInt32Number(io, Seq->n)) return FALSE;
for (i=0; i < Seq ->n; i++) {
cmsPSEQDESC* sec = &Seq -> seq[i];
if (!_cmsWriteUInt32Number(io, sec ->deviceMfg)) return FALSE;
if (!_cmsWriteUInt32Number(io, sec ->deviceModel)) return FALSE;
if (!_cmsWriteUInt64Number(io, &sec ->attributes)) return FALSE;
if (!_cmsWriteUInt32Number(io, sec ->technology)) return FALSE;
if (!SaveDescription(self, io, sec ->Manufacturer)) return FALSE;
if (!SaveDescription(self, io, sec ->Model)) return FALSE;
}
return TRUE;
cmsUNUSED_PARAMETER(nItems);
}
static
void* Type_ProfileSequenceDesc_Dup(struct _cms_typehandler_struct* self, const void* Ptr, cmsUInt32Number n)
{
return (void*) cmsDupProfileSequenceDescription((cmsSEQ*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_ProfileSequenceDesc_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsFreeProfileSequenceDescription((cmsSEQ*) Ptr);
return;
cmsUNUSED_PARAMETER(self);
}
// ********************************************************************************
// Type cmsSigProfileSequenceIdType
// ********************************************************************************
/*
In certain workflows using ICC Device Link Profiles, it is necessary to identify the
original profiles that were combined to create the Device Link Profile.
This type is an array of structures, each of which contains information for
identification of a profile used in a sequence
*/
static
cmsBool ReadSeqID(struct _cms_typehandler_struct* self,
cmsIOHANDLER* io,
void* Cargo,
cmsUInt32Number n,
cmsUInt32Number SizeOfTag)
{
cmsSEQ* OutSeq = (cmsSEQ*) Cargo;
cmsPSEQDESC* seq = &OutSeq ->seq[n];
if (io -> Read(io, seq ->ProfileID.ID8, 16, 1) != 1) return FALSE;
if (!ReadEmbeddedText(self, io, &seq ->Description, SizeOfTag)) return FALSE;
return TRUE;
}
static
void *Type_ProfileSequenceId_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsSEQ* OutSeq;
cmsUInt32Number Count;
cmsUInt32Number BaseOffset;
*nItems = 0;
// Get actual position as a basis for element offsets
BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
// Get table count
if (!_cmsReadUInt32Number(io, &Count)) return NULL;
SizeOfTag -= sizeof(cmsUInt32Number);
// Allocate an empty structure
OutSeq = cmsAllocProfileSequenceDescription(self ->ContextID, Count);
if (OutSeq == NULL) return NULL;
// Read the position table
if (!ReadPositionTable(self, io, Count, BaseOffset, OutSeq, ReadSeqID)) {
cmsFreeProfileSequenceDescription(OutSeq);
return NULL;
}
// Success
*nItems = 1;
return OutSeq;
}
static
cmsBool WriteSeqID(struct _cms_typehandler_struct* self,
cmsIOHANDLER* io,
void* Cargo,
cmsUInt32Number n,
cmsUInt32Number SizeOfTag)
{
cmsSEQ* Seq = (cmsSEQ*) Cargo;
if (!io ->Write(io, 16, Seq ->seq[n].ProfileID.ID8)) return FALSE;
// Store here the MLU
if (!SaveDescription(self, io, Seq ->seq[n].Description)) return FALSE;
return TRUE;
cmsUNUSED_PARAMETER(SizeOfTag);
}
static
cmsBool Type_ProfileSequenceId_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsSEQ* Seq = (cmsSEQ*) Ptr;
cmsUInt32Number BaseOffset;
// Keep the base offset
BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
// This is the table count
if (!_cmsWriteUInt32Number(io, Seq ->n)) return FALSE;
// This is the position table and content
if (!WritePositionTable(self, io, 0, Seq ->n, BaseOffset, Seq, WriteSeqID)) return FALSE;
return TRUE;
cmsUNUSED_PARAMETER(nItems);
}
static
void* Type_ProfileSequenceId_Dup(struct _cms_typehandler_struct* self, const void* Ptr, cmsUInt32Number n)
{
return (void*) cmsDupProfileSequenceDescription((cmsSEQ*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_ProfileSequenceId_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsFreeProfileSequenceDescription((cmsSEQ*) Ptr);
return;
cmsUNUSED_PARAMETER(self);
}
// ********************************************************************************
// Type cmsSigUcrBgType
// ********************************************************************************
/*
This type contains curves representing the under color removal and black
generation and a text string which is a general description of the method used
for the ucr/bg.
*/
static
void *Type_UcrBg_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsUcrBg* n = (cmsUcrBg*) _cmsMallocZero(self ->ContextID, sizeof(cmsUcrBg));
cmsUInt32Number CountUcr, CountBg;
char* ASCIIString;
*nItems = 0;
if (n == NULL) return NULL;
// First curve is Under color removal
if (!_cmsReadUInt32Number(io, &CountUcr)) return NULL;
if (SizeOfTag < sizeof(cmsUInt32Number)) return NULL;
SizeOfTag -= sizeof(cmsUInt32Number);
n ->Ucr = cmsBuildTabulatedToneCurve16(self ->ContextID, CountUcr, NULL);
if (n ->Ucr == NULL) return NULL;
if (!_cmsReadUInt16Array(io, CountUcr, n ->Ucr->Table16)) return NULL;
if (SizeOfTag < sizeof(cmsUInt32Number)) return NULL;
SizeOfTag -= CountUcr * sizeof(cmsUInt16Number);
// Second curve is Black generation
if (!_cmsReadUInt32Number(io, &CountBg)) return NULL;
if (SizeOfTag < sizeof(cmsUInt32Number)) return NULL;
SizeOfTag -= sizeof(cmsUInt32Number);
n ->Bg = cmsBuildTabulatedToneCurve16(self ->ContextID, CountBg, NULL);
if (n ->Bg == NULL) return NULL;
if (!_cmsReadUInt16Array(io, CountBg, n ->Bg->Table16)) return NULL;
if (SizeOfTag < CountBg * sizeof(cmsUInt16Number)) return NULL;
SizeOfTag -= CountBg * sizeof(cmsUInt16Number);
if (SizeOfTag == UINT_MAX) return NULL;
// Now comes the text. The length is specified by the tag size
n ->Desc = cmsMLUalloc(self ->ContextID, 1);
if (n ->Desc == NULL) return NULL;
ASCIIString = (char*) _cmsMalloc(self ->ContextID, SizeOfTag + 1);
if (io ->Read(io, ASCIIString, sizeof(char), SizeOfTag) != SizeOfTag) return NULL;
ASCIIString[SizeOfTag] = 0;
cmsMLUsetASCII(n ->Desc, cmsNoLanguage, cmsNoCountry, ASCIIString);
_cmsFree(self ->ContextID, ASCIIString);
*nItems = 1;
return (void*) n;
}
static
cmsBool Type_UcrBg_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsUcrBg* Value = (cmsUcrBg*) Ptr;
cmsUInt32Number TextSize;
char* Text;
// First curve is Under color removal
if (!_cmsWriteUInt32Number(io, Value ->Ucr ->nEntries)) return FALSE;
if (!_cmsWriteUInt16Array(io, Value ->Ucr ->nEntries, Value ->Ucr ->Table16)) return FALSE;
// Then black generation
if (!_cmsWriteUInt32Number(io, Value ->Bg ->nEntries)) return FALSE;
if (!_cmsWriteUInt16Array(io, Value ->Bg ->nEntries, Value ->Bg ->Table16)) return FALSE;
// Now comes the text. The length is specified by the tag size
TextSize = cmsMLUgetASCII(Value ->Desc, cmsNoLanguage, cmsNoCountry, NULL, 0);
Text = (char*) _cmsMalloc(self ->ContextID, TextSize);
if (cmsMLUgetASCII(Value ->Desc, cmsNoLanguage, cmsNoCountry, Text, TextSize) != TextSize) return FALSE;
if (!io ->Write(io, TextSize, Text)) return FALSE;
_cmsFree(self ->ContextID, Text);
return TRUE;
cmsUNUSED_PARAMETER(nItems);
}
static
void* Type_UcrBg_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
cmsUcrBg* Src = (cmsUcrBg*) Ptr;
cmsUcrBg* NewUcrBg = (cmsUcrBg*) _cmsMallocZero(self ->ContextID, sizeof(cmsUcrBg));
if (NewUcrBg == NULL) return NULL;
NewUcrBg ->Bg = cmsDupToneCurve(Src ->Bg);
NewUcrBg ->Ucr = cmsDupToneCurve(Src ->Ucr);
NewUcrBg ->Desc = cmsMLUdup(Src ->Desc);
return (void*) NewUcrBg;
cmsUNUSED_PARAMETER(n);
}
static
void Type_UcrBg_Free(struct _cms_typehandler_struct* self, void *Ptr)
{
cmsUcrBg* Src = (cmsUcrBg*) Ptr;
if (Src ->Ucr) cmsFreeToneCurve(Src ->Ucr);
if (Src ->Bg) cmsFreeToneCurve(Src ->Bg);
if (Src ->Desc) cmsMLUfree(Src ->Desc);
_cmsFree(self ->ContextID, Ptr);
}
// ********************************************************************************
// Type cmsSigCrdInfoType
// ********************************************************************************
/*
This type contains the PostScript product name to which this profile corresponds
and the names of the companion CRDs. Recall that a single profile can generate
multiple CRDs. It is implemented as a MLU being the language code "PS" and then
country varies for each element:
nm: PostScript product name
#0: Rendering intent 0 CRD name
#1: Rendering intent 1 CRD name
#2: Rendering intent 2 CRD name
#3: Rendering intent 3 CRD name
*/
// Auxiliary, read an string specified as count + string
static
cmsBool ReadCountAndSting(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsMLU* mlu, cmsUInt32Number* SizeOfTag, const char* Section)
{
cmsUInt32Number Count;
char* Text;
if (*SizeOfTag < sizeof(cmsUInt32Number)) return FALSE;
if (!_cmsReadUInt32Number(io, &Count)) return FALSE;
if (Count > UINT_MAX - sizeof(cmsUInt32Number)) return FALSE;
if (*SizeOfTag < Count + sizeof(cmsUInt32Number)) return FALSE;
Text = (char*) _cmsMalloc(self ->ContextID, Count+1);
if (Text == NULL) return FALSE;
if (io ->Read(io, Text, sizeof(cmsUInt8Number), Count) != Count) {
_cmsFree(self ->ContextID, Text);
return FALSE;
}
Text[Count] = 0;
cmsMLUsetASCII(mlu, "PS", Section, Text);
_cmsFree(self ->ContextID, Text);
*SizeOfTag -= (Count + sizeof(cmsUInt32Number));
return TRUE;
}
static
cmsBool WriteCountAndSting(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsMLU* mlu, const char* Section)
{
cmsUInt32Number TextSize;
char* Text;
TextSize = cmsMLUgetASCII(mlu, "PS", Section, NULL, 0);
Text = (char*) _cmsMalloc(self ->ContextID, TextSize);
if (!_cmsWriteUInt32Number(io, TextSize)) return FALSE;
if (cmsMLUgetASCII(mlu, "PS", Section, Text, TextSize) == 0) return FALSE;
if (!io ->Write(io, TextSize, Text)) return FALSE;
_cmsFree(self ->ContextID, Text);
return TRUE;
}
static
void *Type_CrdInfo_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsMLU* mlu = cmsMLUalloc(self ->ContextID, 5);
*nItems = 0;
if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "nm")) goto Error;
if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "#0")) goto Error;
if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "#1")) goto Error;
if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "#2")) goto Error;
if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "#3")) goto Error;
*nItems = 1;
return (void*) mlu;
Error:
cmsMLUfree(mlu);
return NULL;
}
static
cmsBool Type_CrdInfo_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsMLU* mlu = (cmsMLU*) Ptr;
if (!WriteCountAndSting(self, io, mlu, "nm")) goto Error;
if (!WriteCountAndSting(self, io, mlu, "#0")) goto Error;
if (!WriteCountAndSting(self, io, mlu, "#1")) goto Error;
if (!WriteCountAndSting(self, io, mlu, "#2")) goto Error;
if (!WriteCountAndSting(self, io, mlu, "#3")) goto Error;
return TRUE;
Error:
return FALSE;
cmsUNUSED_PARAMETER(nItems);
}
static
void* Type_CrdInfo_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return (void*) cmsMLUdup((cmsMLU*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_CrdInfo_Free(struct _cms_typehandler_struct* self, void *Ptr)
{
cmsMLUfree((cmsMLU*) Ptr);
return;
cmsUNUSED_PARAMETER(self);
}
// ********************************************************************************
// Type cmsSigScreeningType
// ********************************************************************************
//
//The screeningType describes various screening parameters including screen
//frequency, screening angle, and spot shape.
static
void *Type_Screening_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsScreening* sc = NULL;
cmsUInt32Number i;
sc = (cmsScreening*) _cmsMallocZero(self ->ContextID, sizeof(cmsScreening));
if (sc == NULL) return NULL;
*nItems = 0;
if (!_cmsReadUInt32Number(io, &sc ->Flag)) goto Error;
if (!_cmsReadUInt32Number(io, &sc ->nChannels)) goto Error;
if (sc ->nChannels > cmsMAXCHANNELS - 1)
sc ->nChannels = cmsMAXCHANNELS - 1;
for (i=0; i < sc ->nChannels; i++) {
if (!_cmsRead15Fixed16Number(io, &sc ->Channels[i].Frequency)) goto Error;
if (!_cmsRead15Fixed16Number(io, &sc ->Channels[i].ScreenAngle)) goto Error;
if (!_cmsReadUInt32Number(io, &sc ->Channels[i].SpotShape)) goto Error;
}
*nItems = 1;
return (void*) sc;
Error:
if (sc != NULL)
_cmsFree(self ->ContextID, sc);
return NULL;
cmsUNUSED_PARAMETER(SizeOfTag);
}
static
cmsBool Type_Screening_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsScreening* sc = (cmsScreening* ) Ptr;
cmsUInt32Number i;
if (!_cmsWriteUInt32Number(io, sc ->Flag)) return FALSE;
if (!_cmsWriteUInt32Number(io, sc ->nChannels)) return FALSE;
for (i=0; i < sc ->nChannels; i++) {
if (!_cmsWrite15Fixed16Number(io, sc ->Channels[i].Frequency)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, sc ->Channels[i].ScreenAngle)) return FALSE;
if (!_cmsWriteUInt32Number(io, sc ->Channels[i].SpotShape)) return FALSE;
}
return TRUE;
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
static
void* Type_Screening_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsScreening));
cmsUNUSED_PARAMETER(n);
}
static
void Type_Screening_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
_cmsFree(self ->ContextID, Ptr);
}
// ********************************************************************************
// Type cmsSigViewingConditionsType
// ********************************************************************************
//
//This type represents a set of viewing condition parameters including:
//CIE �absolute� illuminant white point tristimulus values and CIE �absolute�
//surround tristimulus values.
static
void *Type_ViewingConditions_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsICCViewingConditions* vc = NULL;
vc = (cmsICCViewingConditions*) _cmsMallocZero(self ->ContextID, sizeof(cmsICCViewingConditions));
if (vc == NULL) return NULL;
*nItems = 0;
if (!_cmsReadXYZNumber(io, &vc ->IlluminantXYZ)) goto Error;
if (!_cmsReadXYZNumber(io, &vc ->SurroundXYZ)) goto Error;
if (!_cmsReadUInt32Number(io, &vc ->IlluminantType)) goto Error;
*nItems = 1;
return (void*) vc;
Error:
if (vc != NULL)
_cmsFree(self ->ContextID, vc);
return NULL;
cmsUNUSED_PARAMETER(SizeOfTag);
}
static
cmsBool Type_ViewingConditions_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsICCViewingConditions* sc = (cmsICCViewingConditions* ) Ptr;
if (!_cmsWriteXYZNumber(io, &sc ->IlluminantXYZ)) return FALSE;
if (!_cmsWriteXYZNumber(io, &sc ->SurroundXYZ)) return FALSE;
if (!_cmsWriteUInt32Number(io, sc ->IlluminantType)) return FALSE;
return TRUE;
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
static
void* Type_ViewingConditions_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return _cmsDupMem(self->ContextID, Ptr, sizeof(cmsICCViewingConditions));
cmsUNUSED_PARAMETER(n);
}
static
void Type_ViewingConditions_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
_cmsFree(self ->ContextID, Ptr);
}
// ********************************************************************************
// Type cmsSigMultiProcessElementType
// ********************************************************************************
static
void* GenericMPEdup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return (void*) cmsStageDup((cmsStage*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void GenericMPEfree(struct _cms_typehandler_struct* self, void *Ptr)
{
cmsStageFree((cmsStage*) Ptr);
return;
cmsUNUSED_PARAMETER(self);
}
// Each curve is stored in one or more curve segments, with break-points specified between curve segments.
// The first curve segment always starts at �Infinity, and the last curve segment always ends at +Infinity. The
// first and last curve segments shall be specified in terms of a formula, whereas the other segments shall be
// specified either in terms of a formula, or by a sampled curve.
// Read an embedded segmented curve
static
cmsToneCurve* ReadSegmentedCurve(struct _cms_typehandler_struct* self, cmsIOHANDLER* io)
{
cmsCurveSegSignature ElementSig;
cmsUInt32Number i, j;
cmsUInt16Number nSegments;
cmsCurveSegment* Segments;
cmsToneCurve* Curve;
cmsFloat32Number PrevBreak = -1E22F; // - infinite
// Take signature and channels for each element.
if (!_cmsReadUInt32Number(io, (cmsUInt32Number*) &ElementSig)) return NULL;
// That should be a segmented curve
if (ElementSig != cmsSigSegmentedCurve) return NULL;
if (!_cmsReadUInt32Number(io, NULL)) return NULL;
if (!_cmsReadUInt16Number(io, &nSegments)) return NULL;
if (!_cmsReadUInt16Number(io, NULL)) return NULL;
if (nSegments < 1) return NULL;
Segments = (cmsCurveSegment*) _cmsCalloc(self ->ContextID, nSegments, sizeof(cmsCurveSegment));
if (Segments == NULL) return NULL;
// Read breakpoints
for (i=0; i < (cmsUInt32Number) nSegments - 1; i++) {
Segments[i].x0 = PrevBreak;
if (!_cmsReadFloat32Number(io, &Segments[i].x1)) goto Error;
PrevBreak = Segments[i].x1;
}
Segments[nSegments-1].x0 = PrevBreak;
Segments[nSegments-1].x1 = 1E22F; // A big cmsFloat32Number number
// Read segments
for (i=0; i < nSegments; i++) {
if (!_cmsReadUInt32Number(io, (cmsUInt32Number*) &ElementSig)) goto Error;
if (!_cmsReadUInt32Number(io, NULL)) goto Error;
switch (ElementSig) {
case cmsSigFormulaCurveSeg: {
cmsUInt16Number Type;
cmsUInt32Number ParamsByType[] = {4, 5, 5 };
if (!_cmsReadUInt16Number(io, &Type)) goto Error;
if (!_cmsReadUInt16Number(io, NULL)) goto Error;
Segments[i].Type = Type + 6;
if (Type > 2) goto Error;
for (j=0; j < ParamsByType[Type]; j++) {
cmsFloat32Number f;
if (!_cmsReadFloat32Number(io, &f)) goto Error;
Segments[i].Params[j] = f;
}
}
break;
case cmsSigSampledCurveSeg: {
cmsUInt32Number Count;
if (!_cmsReadUInt32Number(io, &Count)) return NULL;
Segments[i].nGridPoints = Count;
Segments[i].SampledPoints = (cmsFloat32Number*) _cmsCalloc(self ->ContextID, Count, sizeof(cmsFloat32Number));
if (Segments[i].SampledPoints == NULL) goto Error;
for (j=0; j < Count; j++) {
if (!_cmsReadFloat32Number(io, &Segments[i].SampledPoints[j])) goto Error;
}
}
break;
default:
{
char String[5];
_cmsTagSignature2String(String, (cmsTagSignature) ElementSig);
cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown curve element type '%s' found.", String);
}
return NULL;
}
}
Curve = cmsBuildSegmentedToneCurve(self ->ContextID, nSegments, Segments);
for (i=0; i < nSegments; i++) {
if (Segments[i].SampledPoints) _cmsFree(self ->ContextID, Segments[i].SampledPoints);
}
_cmsFree(self ->ContextID, Segments);
return Curve;
Error:
if (Segments) _cmsFree(self ->ContextID, Segments);
return NULL;
}
static
cmsBool ReadMPECurve(struct _cms_typehandler_struct* self,
cmsIOHANDLER* io,
void* Cargo,
cmsUInt32Number n,
cmsUInt32Number SizeOfTag)
{
cmsToneCurve** GammaTables = ( cmsToneCurve**) Cargo;
GammaTables[n] = ReadSegmentedCurve(self, io);
return (GammaTables[n] != NULL);
cmsUNUSED_PARAMETER(SizeOfTag);
}
static
void *Type_MPEcurve_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsStage* mpe = NULL;
cmsUInt16Number InputChans, OutputChans;
cmsUInt32Number i, BaseOffset;
cmsToneCurve** GammaTables;
*nItems = 0;
// Get actual position as a basis for element offsets
BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
if (!_cmsReadUInt16Number(io, &InputChans)) return NULL;
if (!_cmsReadUInt16Number(io, &OutputChans)) return NULL;
if (InputChans != OutputChans) return NULL;
GammaTables = (cmsToneCurve**) _cmsCalloc(self ->ContextID, InputChans, sizeof(cmsToneCurve*));
if (GammaTables == NULL) return NULL;
if (ReadPositionTable(self, io, InputChans, BaseOffset, GammaTables, ReadMPECurve)) {
mpe = cmsStageAllocToneCurves(self ->ContextID, InputChans, GammaTables);
}
else {
mpe = NULL;
}
for (i=0; i < InputChans; i++) {
if (GammaTables[i]) cmsFreeToneCurve(GammaTables[i]);
}
_cmsFree(self ->ContextID, GammaTables);
*nItems = (mpe != NULL) ? 1 : 0;
return mpe;
cmsUNUSED_PARAMETER(SizeOfTag);
}
// Write a single segmented curve. NO CHECK IS PERFORMED ON VALIDITY
static
cmsBool WriteSegmentedCurve(cmsIOHANDLER* io, cmsToneCurve* g)
{
cmsUInt32Number i, j;
cmsCurveSegment* Segments = g ->Segments;
cmsUInt32Number nSegments = g ->nSegments;
if (!_cmsWriteUInt32Number(io, cmsSigSegmentedCurve)) goto Error;
if (!_cmsWriteUInt32Number(io, 0)) goto Error;
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) nSegments)) goto Error;
if (!_cmsWriteUInt16Number(io, 0)) goto Error;
// Write the break-points
for (i=0; i < nSegments - 1; i++) {
if (!_cmsWriteFloat32Number(io, Segments[i].x1)) goto Error;
}
// Write the segments
for (i=0; i < g ->nSegments; i++) {
cmsCurveSegment* ActualSeg = Segments + i;
if (ActualSeg -> Type == 0) {
// This is a sampled curve
if (!_cmsWriteUInt32Number(io, (cmsUInt32Number) cmsSigSampledCurveSeg)) goto Error;
if (!_cmsWriteUInt32Number(io, 0)) goto Error;
if (!_cmsWriteUInt32Number(io, ActualSeg -> nGridPoints)) goto Error;
for (j=0; j < g ->Segments[i].nGridPoints; j++) {
if (!_cmsWriteFloat32Number(io, ActualSeg -> SampledPoints[j])) goto Error;
}
}
else {
int Type;
cmsUInt32Number ParamsByType[] = { 4, 5, 5 };
// This is a formula-based
if (!_cmsWriteUInt32Number(io, (cmsUInt32Number) cmsSigFormulaCurveSeg)) goto Error;
if (!_cmsWriteUInt32Number(io, 0)) goto Error;
// We only allow 1, 2 and 3 as types
Type = ActualSeg ->Type - 6;
if (Type > 2 || Type < 0) goto Error;
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) Type)) goto Error;
if (!_cmsWriteUInt16Number(io, 0)) goto Error;
for (j=0; j < ParamsByType[Type]; j++) {
if (!_cmsWriteFloat32Number(io, (cmsFloat32Number) ActualSeg ->Params[j])) goto Error;
}
}
// It seems there is no need to align. Code is here, and for safety commented out
// if (!_cmsWriteAlignment(io)) goto Error;
}
return TRUE;
Error:
return FALSE;
}
static
cmsBool WriteMPECurve(struct _cms_typehandler_struct* self,
cmsIOHANDLER* io,
void* Cargo,
cmsUInt32Number n,
cmsUInt32Number SizeOfTag)
{
_cmsStageToneCurvesData* Curves = (_cmsStageToneCurvesData*) Cargo;
return WriteSegmentedCurve(io, Curves ->TheCurves[n]);
cmsUNUSED_PARAMETER(SizeOfTag);
cmsUNUSED_PARAMETER(self);
}
// Write a curve, checking first for validity
static
cmsBool Type_MPEcurve_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsUInt32Number BaseOffset;
cmsStage* mpe = (cmsStage*) Ptr;
_cmsStageToneCurvesData* Curves = (_cmsStageToneCurvesData*) mpe ->Data;
BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
// Write the header. Since those are curves, input and output channels are same
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->InputChannels)) return FALSE;
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->InputChannels)) return FALSE;
if (!WritePositionTable(self, io, 0,
mpe ->InputChannels, BaseOffset, Curves, WriteMPECurve)) return FALSE;
return TRUE;
cmsUNUSED_PARAMETER(nItems);
}
// The matrix is organized as an array of PxQ+Q elements, where P is the number of input channels to the
// matrix, and Q is the number of output channels. The matrix elements are each float32Numbers. The array
// is organized as follows:
// array = [e11, e12, �, e1P, e21, e22, �, e2P, �, eQ1, eQ2, �, eQP, e1, e2, �, eQ]
static
void *Type_MPEmatrix_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsStage* mpe;
cmsUInt16Number InputChans, OutputChans;
cmsUInt32Number nElems, i;
cmsFloat64Number* Matrix;
cmsFloat64Number* Offsets;
if (!_cmsReadUInt16Number(io, &InputChans)) return NULL;
if (!_cmsReadUInt16Number(io, &OutputChans)) return NULL;
nElems = InputChans * OutputChans;
// Input and output chans may be ANY (up to 0xffff)
Matrix = (cmsFloat64Number*) _cmsCalloc(self ->ContextID, nElems, sizeof(cmsFloat64Number));
if (Matrix == NULL) return NULL;
Offsets = (cmsFloat64Number*) _cmsCalloc(self ->ContextID, OutputChans, sizeof(cmsFloat64Number));
if (Offsets == NULL) {
_cmsFree(self ->ContextID, Matrix);
return NULL;
}
for (i=0; i < nElems; i++) {
cmsFloat32Number v;
if (!_cmsReadFloat32Number(io, &v)) return NULL;
Matrix[i] = v;
}
for (i=0; i < OutputChans; i++) {
cmsFloat32Number v;
if (!_cmsReadFloat32Number(io, &v)) return NULL;
Offsets[i] = v;
}
mpe = cmsStageAllocMatrix(self ->ContextID, OutputChans, InputChans, Matrix, Offsets);
_cmsFree(self ->ContextID, Matrix);
_cmsFree(self ->ContextID, Offsets);
*nItems = 1;
return mpe;
cmsUNUSED_PARAMETER(SizeOfTag);
}
static
cmsBool Type_MPEmatrix_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsUInt32Number i, nElems;
cmsStage* mpe = (cmsStage*) Ptr;
_cmsStageMatrixData* Matrix = (_cmsStageMatrixData*) mpe ->Data;
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->InputChannels)) return FALSE;
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->OutputChannels)) return FALSE;
nElems = mpe ->InputChannels * mpe ->OutputChannels;
for (i=0; i < nElems; i++) {
if (!_cmsWriteFloat32Number(io, (cmsFloat32Number) Matrix->Double[i])) return FALSE;
}
for (i=0; i < mpe ->OutputChannels; i++) {
if (Matrix ->Offset == NULL) {
if (!_cmsWriteFloat32Number(io, 0)) return FALSE;
}
else {
if (!_cmsWriteFloat32Number(io, (cmsFloat32Number) Matrix->Offset[i])) return FALSE;
}
}
return TRUE;
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
static
void *Type_MPEclut_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsStage* mpe = NULL;
cmsUInt16Number InputChans, OutputChans;
cmsUInt8Number Dimensions8[16];
cmsUInt32Number i, nMaxGrids, GridPoints[MAX_INPUT_DIMENSIONS];
_cmsStageCLutData* clut;
if (!_cmsReadUInt16Number(io, &InputChans)) return NULL;
if (!_cmsReadUInt16Number(io, &OutputChans)) return NULL;
if (InputChans == 0) goto Error;
if (OutputChans == 0) goto Error;
if (io ->Read(io, Dimensions8, sizeof(cmsUInt8Number), 16) != 16)
goto Error;
// Copy MAX_INPUT_DIMENSIONS at most. Expand to cmsUInt32Number
nMaxGrids = InputChans > MAX_INPUT_DIMENSIONS ? MAX_INPUT_DIMENSIONS : InputChans;
for (i=0; i < nMaxGrids; i++) GridPoints[i] = (cmsUInt32Number) Dimensions8[i];
// Allocate the true CLUT
mpe = cmsStageAllocCLutFloatGranular(self ->ContextID, GridPoints, InputChans, OutputChans, NULL);
if (mpe == NULL) goto Error;
// Read the data
clut = (_cmsStageCLutData*) mpe ->Data;
for (i=0; i < clut ->nEntries; i++) {
if (!_cmsReadFloat32Number(io, &clut ->Tab.TFloat[i])) goto Error;
}
*nItems = 1;
return mpe;
Error:
*nItems = 0;
if (mpe != NULL) cmsStageFree(mpe);
return NULL;
cmsUNUSED_PARAMETER(SizeOfTag);
}
// Write a CLUT in floating point
static
cmsBool Type_MPEclut_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsUInt8Number Dimensions8[16]; // 16 because the spec says 16 and not max number of channels
cmsUInt32Number i;
cmsStage* mpe = (cmsStage*) Ptr;
_cmsStageCLutData* clut = (_cmsStageCLutData*) mpe ->Data;
// Check for maximum number of channels supported by lcms
if (mpe -> InputChannels > MAX_INPUT_DIMENSIONS) return FALSE;
// Only floats are supported in MPE
if (clut ->HasFloatValues == FALSE) return FALSE;
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->InputChannels)) return FALSE;
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->OutputChannels)) return FALSE;
memset(Dimensions8, 0, sizeof(Dimensions8));
for (i=0; i < mpe ->InputChannels; i++)
Dimensions8[i] = (cmsUInt8Number) clut ->Params ->nSamples[i];
if (!io ->Write(io, 16, Dimensions8)) return FALSE;
for (i=0; i < clut ->nEntries; i++) {
if (!_cmsWriteFloat32Number(io, clut ->Tab.TFloat[i])) return FALSE;
}
return TRUE;
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
// This is the list of built-in MPE types
static _cmsTagTypeLinkedList SupportedMPEtypes[] = {
{{ (cmsTagTypeSignature) cmsSigBAcsElemType, NULL, NULL, NULL, NULL, NULL, 0 }, &SupportedMPEtypes[1] }, // Ignore those elements for now
{{ (cmsTagTypeSignature) cmsSigEAcsElemType, NULL, NULL, NULL, NULL, NULL, 0 }, &SupportedMPEtypes[2] }, // (That's what the spec says)
{TYPE_MPE_HANDLER((cmsTagTypeSignature) cmsSigCurveSetElemType, MPEcurve), &SupportedMPEtypes[3] },
{TYPE_MPE_HANDLER((cmsTagTypeSignature) cmsSigMatrixElemType, MPEmatrix), &SupportedMPEtypes[4] },
{TYPE_MPE_HANDLER((cmsTagTypeSignature) cmsSigCLutElemType, MPEclut), NULL },
};
_cmsTagTypePluginChunkType _cmsMPETypePluginChunk = { NULL };
static
cmsBool ReadMPEElem(struct _cms_typehandler_struct* self,
cmsIOHANDLER* io,
void* Cargo,
cmsUInt32Number n,
cmsUInt32Number SizeOfTag)
{
cmsStageSignature ElementSig;
cmsTagTypeHandler* TypeHandler;
cmsUInt32Number nItems;
cmsPipeline *NewLUT = (cmsPipeline *) Cargo;
_cmsTagTypePluginChunkType* MPETypePluginChunk = ( _cmsTagTypePluginChunkType*) _cmsContextGetClientChunk(self->ContextID, MPEPlugin);
// Take signature and channels for each element.
if (!_cmsReadUInt32Number(io, (cmsUInt32Number*) &ElementSig)) return FALSE;
// The reserved placeholder
if (!_cmsReadUInt32Number(io, NULL)) return FALSE;
// Read diverse MPE types
TypeHandler = GetHandler((cmsTagTypeSignature) ElementSig, MPETypePluginChunk ->TagTypes, SupportedMPEtypes);
if (TypeHandler == NULL) {
char String[5];
_cmsTagSignature2String(String, (cmsTagSignature) ElementSig);
// An unknown element was found.
cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown MPE type '%s' found.", String);
return FALSE;
}
// If no read method, just ignore the element (valid for cmsSigBAcsElemType and cmsSigEAcsElemType)
// Read the MPE. No size is given
if (TypeHandler ->ReadPtr != NULL) {
// This is a real element which should be read and processed
if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, (cmsStage*) TypeHandler ->ReadPtr(self, io, &nItems, SizeOfTag)))
return FALSE;
}
return TRUE;
cmsUNUSED_PARAMETER(SizeOfTag);
cmsUNUSED_PARAMETER(n);
}
// This is the main dispatcher for MPE
static
void *Type_MPE_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsUInt16Number InputChans, OutputChans;
cmsUInt32Number ElementCount;
cmsPipeline *NewLUT = NULL;
cmsUInt32Number BaseOffset;
// Get actual position as a basis for element offsets
BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
// Read channels and element count
if (!_cmsReadUInt16Number(io, &InputChans)) return NULL;
if (!_cmsReadUInt16Number(io, &OutputChans)) return NULL;
// Allocates an empty LUT
NewLUT = cmsPipelineAlloc(self ->ContextID, InputChans, OutputChans);
if (NewLUT == NULL) return NULL;
if (!_cmsReadUInt32Number(io, &ElementCount)) return NULL;
if (!ReadPositionTable(self, io, ElementCount, BaseOffset, NewLUT, ReadMPEElem)) {
if (NewLUT != NULL) cmsPipelineFree(NewLUT);
*nItems = 0;
return NULL;
}
// Success
*nItems = 1;
return NewLUT;
cmsUNUSED_PARAMETER(SizeOfTag);
}
// This one is a liitle bit more complex, so we don't use position tables this time.
static
cmsBool Type_MPE_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsUInt32Number i, BaseOffset, DirectoryPos, CurrentPos;
int inputChan, outputChan;
cmsUInt32Number ElemCount;
cmsUInt32Number *ElementOffsets = NULL, *ElementSizes = NULL, Before;
cmsStageSignature ElementSig;
cmsPipeline* Lut = (cmsPipeline*) Ptr;
cmsStage* Elem = Lut ->Elements;
cmsTagTypeHandler* TypeHandler;
_cmsTagTypePluginChunkType* MPETypePluginChunk = ( _cmsTagTypePluginChunkType*) _cmsContextGetClientChunk(self->ContextID, MPEPlugin);
BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
inputChan = cmsPipelineInputChannels(Lut);
outputChan = cmsPipelineOutputChannels(Lut);
ElemCount = cmsPipelineStageCount(Lut);
ElementOffsets = (cmsUInt32Number *) _cmsCalloc(self ->ContextID, ElemCount, sizeof(cmsUInt32Number));
if (ElementOffsets == NULL) goto Error;
ElementSizes = (cmsUInt32Number *) _cmsCalloc(self ->ContextID, ElemCount, sizeof(cmsUInt32Number));
if (ElementSizes == NULL) goto Error;
// Write the head
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) inputChan)) goto Error;
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) outputChan)) goto Error;
if (!_cmsWriteUInt32Number(io, (cmsUInt16Number) ElemCount)) goto Error;
DirectoryPos = io ->Tell(io);
// Write a fake directory to be filled latter on
for (i=0; i < ElemCount; i++) {
if (!_cmsWriteUInt32Number(io, 0)) goto Error; // Offset
if (!_cmsWriteUInt32Number(io, 0)) goto Error; // size
}
// Write each single tag. Keep track of the size as well.
for (i=0; i < ElemCount; i++) {
ElementOffsets[i] = io ->Tell(io) - BaseOffset;
ElementSig = Elem ->Type;
TypeHandler = GetHandler((cmsTagTypeSignature) ElementSig, MPETypePluginChunk->TagTypes, SupportedMPEtypes);
if (TypeHandler == NULL) {
char String[5];
_cmsTagSignature2String(String, (cmsTagSignature) ElementSig);
// An unknow element was found.
cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Found unknown MPE type '%s'", String);
goto Error;
}
if (!_cmsWriteUInt32Number(io, ElementSig)) goto Error;
if (!_cmsWriteUInt32Number(io, 0)) goto Error;
Before = io ->Tell(io);
if (!TypeHandler ->WritePtr(self, io, Elem, 1)) goto Error;
if (!_cmsWriteAlignment(io)) goto Error;
ElementSizes[i] = io ->Tell(io) - Before;
Elem = Elem ->Next;
}
// Write the directory
CurrentPos = io ->Tell(io);
if (!io ->Seek(io, DirectoryPos)) goto Error;
for (i=0; i < ElemCount; i++) {
if (!_cmsWriteUInt32Number(io, ElementOffsets[i])) goto Error;
if (!_cmsWriteUInt32Number(io, ElementSizes[i])) goto Error;
}
if (!io ->Seek(io, CurrentPos)) goto Error;
if (ElementOffsets != NULL) _cmsFree(self ->ContextID, ElementOffsets);
if (ElementSizes != NULL) _cmsFree(self ->ContextID, ElementSizes);
return TRUE;
Error:
if (ElementOffsets != NULL) _cmsFree(self ->ContextID, ElementOffsets);
if (ElementSizes != NULL) _cmsFree(self ->ContextID, ElementSizes);
return FALSE;
cmsUNUSED_PARAMETER(nItems);
}
static
void* Type_MPE_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return (void*) cmsPipelineDup((cmsPipeline*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_MPE_Free(struct _cms_typehandler_struct* self, void *Ptr)
{
cmsPipelineFree((cmsPipeline*) Ptr);
return;
cmsUNUSED_PARAMETER(self);
}
// ********************************************************************************
// Type cmsSigVcgtType
// ********************************************************************************
#define cmsVideoCardGammaTableType 0
#define cmsVideoCardGammaFormulaType 1
// Used internally
typedef struct {
double Gamma;
double Min;
double Max;
} _cmsVCGTGAMMA;
static
void *Type_vcgt_Read(struct _cms_typehandler_struct* self,
cmsIOHANDLER* io,
cmsUInt32Number* nItems,
cmsUInt32Number SizeOfTag)
{
cmsUInt32Number TagType, n, i;
cmsToneCurve** Curves;
*nItems = 0;
// Read tag type
if (!_cmsReadUInt32Number(io, &TagType)) return NULL;
// Allocate space for the array
Curves = ( cmsToneCurve**) _cmsCalloc(self ->ContextID, 3, sizeof(cmsToneCurve*));
if (Curves == NULL) return NULL;
// There are two possible flavors
switch (TagType) {
// Gamma is stored as a table
case cmsVideoCardGammaTableType:
{
cmsUInt16Number nChannels, nElems, nBytes;
// Check channel count, which should be 3 (we don't support monochrome this time)
if (!_cmsReadUInt16Number(io, &nChannels)) goto Error;
if (nChannels != 3) {
cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported number of channels for VCGT '%d'", nChannels);
goto Error;
}
// Get Table element count and bytes per element
if (!_cmsReadUInt16Number(io, &nElems)) goto Error;
if (!_cmsReadUInt16Number(io, &nBytes)) goto Error;
// Adobe's quirk fixup. Fixing broken profiles...
if (nElems == 256 && nBytes == 1 && SizeOfTag == 1576)
nBytes = 2;
// Populate tone curves
for (n=0; n < 3; n++) {
Curves[n] = cmsBuildTabulatedToneCurve16(self ->ContextID, nElems, NULL);
if (Curves[n] == NULL) goto Error;
// On depending on byte depth
switch (nBytes) {
// One byte, 0..255
case 1:
for (i=0; i < nElems; i++) {
cmsUInt8Number v;
if (!_cmsReadUInt8Number(io, &v)) goto Error;
Curves[n] ->Table16[i] = FROM_8_TO_16(v);
}
break;
// One word 0..65535
case 2:
if (!_cmsReadUInt16Array(io, nElems, Curves[n]->Table16)) goto Error;
break;
// Unsupported
default:
cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported bit depth for VCGT '%d'", nBytes * 8);
goto Error;
}
} // For all 3 channels
}
break;
// In this case, gamma is stored as a formula
case cmsVideoCardGammaFormulaType:
{
_cmsVCGTGAMMA Colorant[3];
// Populate tone curves
for (n=0; n < 3; n++) {
double Params[10];
if (!_cmsRead15Fixed16Number(io, &Colorant[n].Gamma)) goto Error;
if (!_cmsRead15Fixed16Number(io, &Colorant[n].Min)) goto Error;
if (!_cmsRead15Fixed16Number(io, &Colorant[n].Max)) goto Error;
// Parametric curve type 5 is:
// Y = (aX + b)^Gamma + e | X >= d
// Y = cX + f | X < d
// vcgt formula is:
// Y = (Max � Min) * (X ^ Gamma) + Min
// So, the translation is
// a = (Max � Min) ^ ( 1 / Gamma)
// e = Min
// b=c=d=f=0
Params[0] = Colorant[n].Gamma;
Params[1] = pow((Colorant[n].Max - Colorant[n].Min), (1.0 / Colorant[n].Gamma));
Params[2] = 0;
Params[3] = 0;
Params[4] = 0;
Params[5] = Colorant[n].Min;
Params[6] = 0;
Curves[n] = cmsBuildParametricToneCurve(self ->ContextID, 5, Params);
if (Curves[n] == NULL) goto Error;
}
}
break;
// Unsupported
default:
cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported tag type for VCGT '%d'", TagType);
goto Error;
}
*nItems = 1;
return (void*) Curves;
// Regret, free all resources
Error:
cmsFreeToneCurveTriple(Curves);
_cmsFree(self ->ContextID, Curves);
return NULL;
cmsUNUSED_PARAMETER(SizeOfTag);
}
// We don't support all flavors, only 16bits tables and formula
static
cmsBool Type_vcgt_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsToneCurve** Curves = (cmsToneCurve**) Ptr;
cmsUInt32Number i, j;
if (cmsGetToneCurveParametricType(Curves[0]) == 5 &&
cmsGetToneCurveParametricType(Curves[1]) == 5 &&
cmsGetToneCurveParametricType(Curves[2]) == 5) {
if (!_cmsWriteUInt32Number(io, cmsVideoCardGammaFormulaType)) return FALSE;
// Save parameters
for (i=0; i < 3; i++) {
_cmsVCGTGAMMA v;
v.Gamma = Curves[i] ->Segments[0].Params[0];
v.Min = Curves[i] ->Segments[0].Params[5];
v.Max = pow(Curves[i] ->Segments[0].Params[1], v.Gamma) + v.Min;
if (!_cmsWrite15Fixed16Number(io, v.Gamma)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, v.Min)) return FALSE;
if (!_cmsWrite15Fixed16Number(io, v.Max)) return FALSE;
}
}
else {
// Always store as a table of 256 words
if (!_cmsWriteUInt32Number(io, cmsVideoCardGammaTableType)) return FALSE;
if (!_cmsWriteUInt16Number(io, 3)) return FALSE;
if (!_cmsWriteUInt16Number(io, 256)) return FALSE;
if (!_cmsWriteUInt16Number(io, 2)) return FALSE;
for (i=0; i < 3; i++) {
for (j=0; j < 256; j++) {
cmsFloat32Number v = cmsEvalToneCurveFloat(Curves[i], (cmsFloat32Number) (j / 255.0));
cmsUInt16Number n = _cmsQuickSaturateWord(v * 65535.0);
if (!_cmsWriteUInt16Number(io, n)) return FALSE;
}
}
}
return TRUE;
cmsUNUSED_PARAMETER(self);
cmsUNUSED_PARAMETER(nItems);
}
static
void* Type_vcgt_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
cmsToneCurve** OldCurves = (cmsToneCurve**) Ptr;
cmsToneCurve** NewCurves;
NewCurves = ( cmsToneCurve**) _cmsCalloc(self ->ContextID, 3, sizeof(cmsToneCurve*));
if (NewCurves == NULL) return NULL;
NewCurves[0] = cmsDupToneCurve(OldCurves[0]);
NewCurves[1] = cmsDupToneCurve(OldCurves[1]);
NewCurves[2] = cmsDupToneCurve(OldCurves[2]);
return (void*) NewCurves;
cmsUNUSED_PARAMETER(n);
}
static
void Type_vcgt_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsFreeToneCurveTriple((cmsToneCurve**) Ptr);
_cmsFree(self ->ContextID, Ptr);
}
// ********************************************************************************
// Type cmsSigDictType
// ********************************************************************************
// Single column of the table can point to wchar or MLUC elements. Holds arrays of data
typedef struct {
cmsContext ContextID;
cmsUInt32Number *Offsets;
cmsUInt32Number *Sizes;
} _cmsDICelem;
typedef struct {
_cmsDICelem Name, Value, DisplayName, DisplayValue;
} _cmsDICarray;
// Allocate an empty array element
static
cmsBool AllocElem(cmsContext ContextID, _cmsDICelem* e, cmsUInt32Number Count)
{
e->Offsets = (cmsUInt32Number *) _cmsCalloc(ContextID, Count, sizeof(cmsUInt32Number));
if (e->Offsets == NULL) return FALSE;
e->Sizes = (cmsUInt32Number *) _cmsCalloc(ContextID, Count, sizeof(cmsUInt32Number));
if (e->Sizes == NULL) {
_cmsFree(ContextID, e -> Offsets);
return FALSE;
}
e ->ContextID = ContextID;
return TRUE;
}
// Free an array element
static
void FreeElem(_cmsDICelem* e)
{
if (e ->Offsets != NULL) _cmsFree(e -> ContextID, e -> Offsets);
if (e ->Sizes != NULL) _cmsFree(e -> ContextID, e -> Sizes);
e->Offsets = e ->Sizes = NULL;
}
// Get rid of whole array
static
void FreeArray( _cmsDICarray* a)
{
if (a ->Name.Offsets != NULL) FreeElem(&a->Name);
if (a ->Value.Offsets != NULL) FreeElem(&a ->Value);
if (a ->DisplayName.Offsets != NULL) FreeElem(&a->DisplayName);
if (a ->DisplayValue.Offsets != NULL) FreeElem(&a ->DisplayValue);
}
// Allocate whole array
static
cmsBool AllocArray(cmsContext ContextID, _cmsDICarray* a, cmsUInt32Number Count, cmsUInt32Number Length)
{
// Empty values
memset(a, 0, sizeof(_cmsDICarray));
// On depending on record size, create column arrays
if (!AllocElem(ContextID, &a ->Name, Count)) goto Error;
if (!AllocElem(ContextID, &a ->Value, Count)) goto Error;
if (Length > 16) {
if (!AllocElem(ContextID, &a -> DisplayName, Count)) goto Error;
}
if (Length > 24) {
if (!AllocElem(ContextID, &a ->DisplayValue, Count)) goto Error;
}
return TRUE;
Error:
FreeArray(a);
return FALSE;
}
// Read one element
static
cmsBool ReadOneElem(cmsIOHANDLER* io, _cmsDICelem* e, cmsUInt32Number i, cmsUInt32Number BaseOffset)
{
if (!_cmsReadUInt32Number(io, &e->Offsets[i])) return FALSE;
if (!_cmsReadUInt32Number(io, &e ->Sizes[i])) return FALSE;
// An offset of zero has special meaning and shal be preserved
if (e ->Offsets[i] > 0)
e ->Offsets[i] += BaseOffset;
return TRUE;
}
static
cmsBool ReadOffsetArray(cmsIOHANDLER* io, _cmsDICarray* a, cmsUInt32Number Count, cmsUInt32Number Length, cmsUInt32Number BaseOffset)
{
cmsUInt32Number i;
// Read column arrays
for (i=0; i < Count; i++) {
if (!ReadOneElem(io, &a -> Name, i, BaseOffset)) return FALSE;
if (!ReadOneElem(io, &a -> Value, i, BaseOffset)) return FALSE;
if (Length > 16) {
if (!ReadOneElem(io, &a ->DisplayName, i, BaseOffset)) return FALSE;
}
if (Length > 24) {
if (!ReadOneElem(io, & a -> DisplayValue, i, BaseOffset)) return FALSE;
}
}
return TRUE;
}
// Write one element
static
cmsBool WriteOneElem(cmsIOHANDLER* io, _cmsDICelem* e, cmsUInt32Number i)
{
if (!_cmsWriteUInt32Number(io, e->Offsets[i])) return FALSE;
if (!_cmsWriteUInt32Number(io, e ->Sizes[i])) return FALSE;
return TRUE;
}
static
cmsBool WriteOffsetArray(cmsIOHANDLER* io, _cmsDICarray* a, cmsUInt32Number Count, cmsUInt32Number Length)
{
cmsUInt32Number i;
for (i=0; i < Count; i++) {
if (!WriteOneElem(io, &a -> Name, i)) return FALSE;
if (!WriteOneElem(io, &a -> Value, i)) return FALSE;
if (Length > 16) {
if (!WriteOneElem(io, &a -> DisplayName, i)) return FALSE;
}
if (Length > 24) {
if (!WriteOneElem(io, &a -> DisplayValue, i)) return FALSE;
}
}
return TRUE;
}
static
cmsBool ReadOneWChar(cmsIOHANDLER* io, _cmsDICelem* e, cmsUInt32Number i, wchar_t ** wcstr)
{
cmsUInt32Number nChars;
// Special case for undefined strings (see ICC Votable
// Proposal Submission, Dictionary Type and Metadata TAG Definition)
if (e -> Offsets[i] == 0) {
*wcstr = NULL;
return TRUE;
}
if (!io -> Seek(io, e -> Offsets[i])) return FALSE;
nChars = e ->Sizes[i] / sizeof(cmsUInt16Number);
*wcstr = (wchar_t*) _cmsMallocZero(e ->ContextID, (nChars + 1) * sizeof(wchar_t));
if (*wcstr == NULL) return FALSE;
if (!_cmsReadWCharArray(io, nChars, *wcstr)) {
_cmsFree(e ->ContextID, *wcstr);
return FALSE;
}
// End of string marker
(*wcstr)[nChars] = 0;
return TRUE;
}
static
cmsUInt32Number mywcslen(const wchar_t *s)
{
const wchar_t *p;
p = s;
while (*p)
p++;
return (cmsUInt32Number)(p - s);
}
static
cmsBool WriteOneWChar(cmsIOHANDLER* io, _cmsDICelem* e, cmsUInt32Number i, const wchar_t * wcstr, cmsUInt32Number BaseOffset)
{
cmsUInt32Number Before = io ->Tell(io);
cmsUInt32Number n;
e ->Offsets[i] = Before - BaseOffset;
if (wcstr == NULL) {
e ->Sizes[i] = 0;
e ->Offsets[i] = 0;
return TRUE;
}
n = mywcslen(wcstr);
if (!_cmsWriteWCharArray(io, n, wcstr)) return FALSE;
e ->Sizes[i] = io ->Tell(io) - Before;
return TRUE;
}
static
cmsBool ReadOneMLUC(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, _cmsDICelem* e, cmsUInt32Number i, cmsMLU** mlu)
{
cmsUInt32Number nItems = 0;
// A way to get null MLUCs
if (e -> Offsets[i] == 0 || e ->Sizes[i] == 0) {
*mlu = NULL;
return TRUE;
}
if (!io -> Seek(io, e -> Offsets[i])) return FALSE;
*mlu = (cmsMLU*) Type_MLU_Read(self, io, &nItems, e ->Sizes[i]);
return *mlu != NULL;
}
static
cmsBool WriteOneMLUC(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, _cmsDICelem* e, cmsUInt32Number i, const cmsMLU* mlu, cmsUInt32Number BaseOffset)
{
cmsUInt32Number Before;
// Special case for undefined strings (see ICC Votable
// Proposal Submission, Dictionary Type and Metadata TAG Definition)
if (mlu == NULL) {
e ->Sizes[i] = 0;
e ->Offsets[i] = 0;
return TRUE;
}
Before = io ->Tell(io);
e ->Offsets[i] = Before - BaseOffset;
if (!Type_MLU_Write(self, io, (void*) mlu, 1)) return FALSE;
e ->Sizes[i] = io ->Tell(io) - Before;
return TRUE;
}
static
void *Type_Dictionary_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsHANDLE hDict;
cmsUInt32Number i, Count, Length;
cmsUInt32Number BaseOffset;
_cmsDICarray a;
wchar_t *NameWCS = NULL, *ValueWCS = NULL;
cmsMLU *DisplayNameMLU = NULL, *DisplayValueMLU=NULL;
cmsBool rc;
*nItems = 0;
// Get actual position as a basis for element offsets
BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
// Get name-value record count
if (!_cmsReadUInt32Number(io, &Count)) return NULL;
SizeOfTag -= sizeof(cmsUInt32Number);
// Get rec length
if (!_cmsReadUInt32Number(io, &Length)) return NULL;
SizeOfTag -= sizeof(cmsUInt32Number);
// Check for valid lengths
if (Length != 16 && Length != 24 && Length != 32) {
cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown record length in dictionary '%d'", Length);
return NULL;
}
// Creates an empty dictionary
hDict = cmsDictAlloc(self -> ContextID);
if (hDict == NULL) return NULL;
// On depending on record size, create column arrays
if (!AllocArray(self -> ContextID, &a, Count, Length)) goto Error;
// Read column arrays
if (!ReadOffsetArray(io, &a, Count, Length, BaseOffset)) goto Error;
// Seek to each element and read it
for (i=0; i < Count; i++) {
if (!ReadOneWChar(io, &a.Name, i, &NameWCS)) goto Error;
if (!ReadOneWChar(io, &a.Value, i, &ValueWCS)) goto Error;
if (Length > 16) {
if (!ReadOneMLUC(self, io, &a.DisplayName, i, &DisplayNameMLU)) goto Error;
}
if (Length > 24) {
if (!ReadOneMLUC(self, io, &a.DisplayValue, i, &DisplayValueMLU)) goto Error;
}
if (NameWCS == NULL || ValueWCS == NULL) {
cmsSignalError(self->ContextID, cmsERROR_CORRUPTION_DETECTED, "Bad dictionary Name/Value");
rc = FALSE;
}
else {
rc = cmsDictAddEntry(hDict, NameWCS, ValueWCS, DisplayNameMLU, DisplayValueMLU);
}
if (NameWCS != NULL) _cmsFree(self ->ContextID, NameWCS);
if (ValueWCS != NULL) _cmsFree(self ->ContextID, ValueWCS);
if (DisplayNameMLU != NULL) cmsMLUfree(DisplayNameMLU);
if (DisplayValueMLU != NULL) cmsMLUfree(DisplayValueMLU);
if (!rc) goto Error;
}
FreeArray(&a);
*nItems = 1;
return (void*) hDict;
Error:
FreeArray(&a);
cmsDictFree(hDict);
return NULL;
}
static
cmsBool Type_Dictionary_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsHANDLE hDict = (cmsHANDLE) Ptr;
const cmsDICTentry* p;
cmsBool AnyName, AnyValue;
cmsUInt32Number i, Count, Length;
cmsUInt32Number DirectoryPos, CurrentPos, BaseOffset;
_cmsDICarray a;
if (hDict == NULL) return FALSE;
BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
// Let's inspect the dictionary
Count = 0; AnyName = FALSE; AnyValue = FALSE;
for (p = cmsDictGetEntryList(hDict); p != NULL; p = cmsDictNextEntry(p)) {
if (p ->DisplayName != NULL) AnyName = TRUE;
if (p ->DisplayValue != NULL) AnyValue = TRUE;
Count++;
}
Length = 16;
if (AnyName) Length += 8;
if (AnyValue) Length += 8;
if (!_cmsWriteUInt32Number(io, Count)) return FALSE;
if (!_cmsWriteUInt32Number(io, Length)) return FALSE;
// Keep starting position of offsets table
DirectoryPos = io ->Tell(io);
// Allocate offsets array
if (!AllocArray(self ->ContextID, &a, Count, Length)) goto Error;
// Write a fake directory to be filled latter on
if (!WriteOffsetArray(io, &a, Count, Length)) goto Error;
// Write each element. Keep track of the size as well.
p = cmsDictGetEntryList(hDict);
for (i=0; i < Count; i++) {
if (!WriteOneWChar(io, &a.Name, i, p ->Name, BaseOffset)) goto Error;
if (!WriteOneWChar(io, &a.Value, i, p ->Value, BaseOffset)) goto Error;
if (p ->DisplayName != NULL) {
if (!WriteOneMLUC(self, io, &a.DisplayName, i, p ->DisplayName, BaseOffset)) goto Error;
}
if (p ->DisplayValue != NULL) {
if (!WriteOneMLUC(self, io, &a.DisplayValue, i, p ->DisplayValue, BaseOffset)) goto Error;
}
p = cmsDictNextEntry(p);
}
// Write the directory
CurrentPos = io ->Tell(io);
if (!io ->Seek(io, DirectoryPos)) goto Error;
if (!WriteOffsetArray(io, &a, Count, Length)) goto Error;
if (!io ->Seek(io, CurrentPos)) goto Error;
FreeArray(&a);
return TRUE;
Error:
FreeArray(&a);
return FALSE;
cmsUNUSED_PARAMETER(nItems);
}
static
void* Type_Dictionary_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return (void*) cmsDictDup((cmsHANDLE) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
static
void Type_Dictionary_Free(struct _cms_typehandler_struct* self, void* Ptr)
{
cmsDictFree((cmsHANDLE) Ptr);
cmsUNUSED_PARAMETER(self);
}
// ********************************************************************************
// Type support main routines
// ********************************************************************************
// This is the list of built-in types
static _cmsTagTypeLinkedList SupportedTagTypes[] = {
{TYPE_HANDLER(cmsSigChromaticityType, Chromaticity), &SupportedTagTypes[1] },
{TYPE_HANDLER(cmsSigColorantOrderType, ColorantOrderType), &SupportedTagTypes[2] },
{TYPE_HANDLER(cmsSigS15Fixed16ArrayType, S15Fixed16), &SupportedTagTypes[3] },
{TYPE_HANDLER(cmsSigU16Fixed16ArrayType, U16Fixed16), &SupportedTagTypes[4] },
{TYPE_HANDLER(cmsSigTextType, Text), &SupportedTagTypes[5] },
{TYPE_HANDLER(cmsSigTextDescriptionType, Text_Description), &SupportedTagTypes[6] },
{TYPE_HANDLER(cmsSigCurveType, Curve), &SupportedTagTypes[7] },
{TYPE_HANDLER(cmsSigParametricCurveType, ParametricCurve), &SupportedTagTypes[8] },
{TYPE_HANDLER(cmsSigDateTimeType, DateTime), &SupportedTagTypes[9] },
{TYPE_HANDLER(cmsSigLut8Type, LUT8), &SupportedTagTypes[10] },
{TYPE_HANDLER(cmsSigLut16Type, LUT16), &SupportedTagTypes[11] },
{TYPE_HANDLER(cmsSigColorantTableType, ColorantTable), &SupportedTagTypes[12] },
{TYPE_HANDLER(cmsSigNamedColor2Type, NamedColor), &SupportedTagTypes[13] },
{TYPE_HANDLER(cmsSigMultiLocalizedUnicodeType, MLU), &SupportedTagTypes[14] },
{TYPE_HANDLER(cmsSigProfileSequenceDescType, ProfileSequenceDesc), &SupportedTagTypes[15] },
{TYPE_HANDLER(cmsSigSignatureType, Signature), &SupportedTagTypes[16] },
{TYPE_HANDLER(cmsSigMeasurementType, Measurement), &SupportedTagTypes[17] },
{TYPE_HANDLER(cmsSigDataType, Data), &SupportedTagTypes[18] },
{TYPE_HANDLER(cmsSigLutAtoBType, LUTA2B), &SupportedTagTypes[19] },
{TYPE_HANDLER(cmsSigLutBtoAType, LUTB2A), &SupportedTagTypes[20] },
{TYPE_HANDLER(cmsSigUcrBgType, UcrBg), &SupportedTagTypes[21] },
{TYPE_HANDLER(cmsSigCrdInfoType, CrdInfo), &SupportedTagTypes[22] },
{TYPE_HANDLER(cmsSigMultiProcessElementType, MPE), &SupportedTagTypes[23] },
{TYPE_HANDLER(cmsSigScreeningType, Screening), &SupportedTagTypes[24] },
{TYPE_HANDLER(cmsSigViewingConditionsType, ViewingConditions), &SupportedTagTypes[25] },
{TYPE_HANDLER(cmsSigXYZType, XYZ), &SupportedTagTypes[26] },
{TYPE_HANDLER(cmsCorbisBrokenXYZtype, XYZ), &SupportedTagTypes[27] },
{TYPE_HANDLER(cmsMonacoBrokenCurveType, Curve), &SupportedTagTypes[28] },
{TYPE_HANDLER(cmsSigProfileSequenceIdType, ProfileSequenceId), &SupportedTagTypes[29] },
{TYPE_HANDLER(cmsSigDictType, Dictionary), &SupportedTagTypes[30] },
{TYPE_HANDLER(cmsSigVcgtType, vcgt), NULL }
};
_cmsTagTypePluginChunkType _cmsTagTypePluginChunk = { NULL };
// Duplicates the zone of memory used by the plug-in in the new context
static
void DupTagTypeList(struct _cmsContext_struct* ctx,
const struct _cmsContext_struct* src,
int loc)
{
_cmsTagTypePluginChunkType newHead = { NULL };
_cmsTagTypeLinkedList* entry;
_cmsTagTypeLinkedList* Anterior = NULL;
_cmsTagTypePluginChunkType* head = (_cmsTagTypePluginChunkType*) src->chunks[loc];
// Walk the list copying all nodes
for (entry = head->TagTypes;
entry != NULL;
entry = entry ->Next) {
_cmsTagTypeLinkedList *newEntry = ( _cmsTagTypeLinkedList *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsTagTypeLinkedList));
if (newEntry == NULL)
return;
// We want to keep the linked list order, so this is a little bit tricky
newEntry -> Next = NULL;
if (Anterior)
Anterior -> Next = newEntry;
Anterior = newEntry;
if (newHead.TagTypes == NULL)
newHead.TagTypes = newEntry;
}
ctx ->chunks[loc] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsTagTypePluginChunkType));
}
void _cmsAllocTagTypePluginChunk(struct _cmsContext_struct* ctx,
const struct _cmsContext_struct* src)
{
if (src != NULL) {
// Duplicate the LIST
DupTagTypeList(ctx, src, TagTypePlugin);
}
else {
static _cmsTagTypePluginChunkType TagTypePluginChunk = { NULL };
ctx ->chunks[TagTypePlugin] = _cmsSubAllocDup(ctx ->MemPool, &TagTypePluginChunk, sizeof(_cmsTagTypePluginChunkType));
}
}
void _cmsAllocMPETypePluginChunk(struct _cmsContext_struct* ctx,
const struct _cmsContext_struct* src)
{
if (src != NULL) {
// Duplicate the LIST
DupTagTypeList(ctx, src, MPEPlugin);
}
else {
static _cmsTagTypePluginChunkType TagTypePluginChunk = { NULL };
ctx ->chunks[MPEPlugin] = _cmsSubAllocDup(ctx ->MemPool, &TagTypePluginChunk, sizeof(_cmsTagTypePluginChunkType));
}
}
// Both kind of plug-ins share same structure
cmsBool _cmsRegisterTagTypePlugin(cmsContext id, cmsPluginBase* Data)
{
return RegisterTypesPlugin(id, Data, TagTypePlugin);
}
cmsBool _cmsRegisterMultiProcessElementPlugin(cmsContext id, cmsPluginBase* Data)
{
return RegisterTypesPlugin(id, Data,MPEPlugin);
}
// Wrapper for tag types
cmsTagTypeHandler* _cmsGetTagTypeHandler(cmsContext ContextID, cmsTagTypeSignature sig)
{
_cmsTagTypePluginChunkType* ctx = ( _cmsTagTypePluginChunkType*) _cmsContextGetClientChunk(ContextID, TagTypePlugin);
return GetHandler(sig, ctx->TagTypes, SupportedTagTypes);
}
// ********************************************************************************
// Tag support main routines
// ********************************************************************************
typedef struct _cmsTagLinkedList_st {
cmsTagSignature Signature;
cmsTagDescriptor Descriptor;
struct _cmsTagLinkedList_st* Next;
} _cmsTagLinkedList;
// This is the list of built-in tags
static _cmsTagLinkedList SupportedTags[] = {
{ cmsSigAToB0Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutAtoBType, cmsSigLut8Type}, DecideLUTtypeA2B}, &SupportedTags[1]},
{ cmsSigAToB1Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutAtoBType, cmsSigLut8Type}, DecideLUTtypeA2B}, &SupportedTags[2]},
{ cmsSigAToB2Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutAtoBType, cmsSigLut8Type}, DecideLUTtypeA2B}, &SupportedTags[3]},
{ cmsSigBToA0Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type}, DecideLUTtypeB2A}, &SupportedTags[4]},
{ cmsSigBToA1Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type}, DecideLUTtypeB2A}, &SupportedTags[5]},
{ cmsSigBToA2Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type}, DecideLUTtypeB2A}, &SupportedTags[6]},
// Allow corbis and its broken XYZ type
{ cmsSigRedColorantTag, { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, DecideXYZtype}, &SupportedTags[7]},
{ cmsSigGreenColorantTag, { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, DecideXYZtype}, &SupportedTags[8]},
{ cmsSigBlueColorantTag, { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, DecideXYZtype}, &SupportedTags[9]},
{ cmsSigRedTRCTag, { 1, 3, { cmsSigCurveType, cmsSigParametricCurveType, cmsMonacoBrokenCurveType }, DecideCurveType}, &SupportedTags[10]},
{ cmsSigGreenTRCTag, { 1, 3, { cmsSigCurveType, cmsSigParametricCurveType, cmsMonacoBrokenCurveType }, DecideCurveType}, &SupportedTags[11]},
{ cmsSigBlueTRCTag, { 1, 3, { cmsSigCurveType, cmsSigParametricCurveType, cmsMonacoBrokenCurveType }, DecideCurveType}, &SupportedTags[12]},
{ cmsSigCalibrationDateTimeTag, { 1, 1, { cmsSigDateTimeType }, NULL}, &SupportedTags[13]},
{ cmsSigCharTargetTag, { 1, 1, { cmsSigTextType }, NULL}, &SupportedTags[14]},
{ cmsSigChromaticAdaptationTag, { 9, 1, { cmsSigS15Fixed16ArrayType }, NULL}, &SupportedTags[15]},
{ cmsSigChromaticityTag, { 1, 1, { cmsSigChromaticityType }, NULL}, &SupportedTags[16]},
{ cmsSigColorantOrderTag, { 1, 1, { cmsSigColorantOrderType }, NULL}, &SupportedTags[17]},
{ cmsSigColorantTableTag, { 1, 1, { cmsSigColorantTableType }, NULL}, &SupportedTags[18]},
{ cmsSigColorantTableOutTag, { 1, 1, { cmsSigColorantTableType }, NULL}, &SupportedTags[19]},
{ cmsSigCopyrightTag, { 1, 3, { cmsSigTextType, cmsSigMultiLocalizedUnicodeType, cmsSigTextDescriptionType}, DecideTextType}, &SupportedTags[20]},
{ cmsSigDateTimeTag, { 1, 1, { cmsSigDateTimeType }, NULL}, &SupportedTags[21]},
{ cmsSigDeviceMfgDescTag, { 1, 3, { cmsSigTextDescriptionType, cmsSigMultiLocalizedUnicodeType, cmsSigTextType}, DecideTextDescType}, &SupportedTags[22]},
{ cmsSigDeviceModelDescTag, { 1, 3, { cmsSigTextDescriptionType, cmsSigMultiLocalizedUnicodeType, cmsSigTextType}, DecideTextDescType}, &SupportedTags[23]},
{ cmsSigGamutTag, { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type }, DecideLUTtypeB2A}, &SupportedTags[24]},
{ cmsSigGrayTRCTag, { 1, 2, { cmsSigCurveType, cmsSigParametricCurveType }, DecideCurveType}, &SupportedTags[25]},
{ cmsSigLuminanceTag, { 1, 1, { cmsSigXYZType }, NULL}, &SupportedTags[26]},
{ cmsSigMediaBlackPointTag, { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, NULL}, &SupportedTags[27]},
{ cmsSigMediaWhitePointTag, { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, NULL}, &SupportedTags[28]},
{ cmsSigNamedColor2Tag, { 1, 1, { cmsSigNamedColor2Type }, NULL}, &SupportedTags[29]},
{ cmsSigPreview0Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type }, DecideLUTtypeB2A}, &SupportedTags[30]},
{ cmsSigPreview1Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type }, DecideLUTtypeB2A}, &SupportedTags[31]},
{ cmsSigPreview2Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type }, DecideLUTtypeB2A}, &SupportedTags[32]},
{ cmsSigProfileDescriptionTag, { 1, 3, { cmsSigTextDescriptionType, cmsSigMultiLocalizedUnicodeType, cmsSigTextType}, DecideTextDescType}, &SupportedTags[33]},
{ cmsSigProfileSequenceDescTag, { 1, 1, { cmsSigProfileSequenceDescType }, NULL}, &SupportedTags[34]},
{ cmsSigTechnologyTag, { 1, 1, { cmsSigSignatureType }, NULL}, &SupportedTags[35]},
{ cmsSigColorimetricIntentImageStateTag, { 1, 1, { cmsSigSignatureType }, NULL}, &SupportedTags[36]},
{ cmsSigPerceptualRenderingIntentGamutTag, { 1, 1, { cmsSigSignatureType }, NULL}, &SupportedTags[37]},
{ cmsSigSaturationRenderingIntentGamutTag, { 1, 1, { cmsSigSignatureType }, NULL}, &SupportedTags[38]},
{ cmsSigMeasurementTag, { 1, 1, { cmsSigMeasurementType }, NULL}, &SupportedTags[39]},
{ cmsSigPs2CRD0Tag, { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[40]},
{ cmsSigPs2CRD1Tag, { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[41]},
{ cmsSigPs2CRD2Tag, { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[42]},
{ cmsSigPs2CRD3Tag, { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[43]},
{ cmsSigPs2CSATag, { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[44]},
{ cmsSigPs2RenderingIntentTag, { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[45]},
{ cmsSigViewingCondDescTag, { 1, 3, { cmsSigTextDescriptionType, cmsSigMultiLocalizedUnicodeType, cmsSigTextType}, DecideTextDescType}, &SupportedTags[46]},
{ cmsSigUcrBgTag, { 1, 1, { cmsSigUcrBgType}, NULL}, &SupportedTags[47]},
{ cmsSigCrdInfoTag, { 1, 1, { cmsSigCrdInfoType}, NULL}, &SupportedTags[48]},
{ cmsSigDToB0Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[49]},
{ cmsSigDToB1Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[50]},
{ cmsSigDToB2Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[51]},
{ cmsSigDToB3Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[52]},
{ cmsSigBToD0Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[53]},
{ cmsSigBToD1Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[54]},
{ cmsSigBToD2Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[55]},
{ cmsSigBToD3Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[56]},
{ cmsSigScreeningDescTag, { 1, 1, { cmsSigTextDescriptionType }, NULL}, &SupportedTags[57]},
{ cmsSigViewingConditionsTag, { 1, 1, { cmsSigViewingConditionsType }, NULL}, &SupportedTags[58]},
{ cmsSigScreeningTag, { 1, 1, { cmsSigScreeningType}, NULL }, &SupportedTags[59]},
{ cmsSigVcgtTag, { 1, 1, { cmsSigVcgtType}, NULL }, &SupportedTags[60]},
{ cmsSigMetaTag, { 1, 1, { cmsSigDictType}, NULL }, &SupportedTags[61]},
{ cmsSigProfileSequenceIdTag, { 1, 1, { cmsSigProfileSequenceIdType}, NULL }, &SupportedTags[62]},
{ cmsSigProfileDescriptionMLTag,{ 1, 1, { cmsSigMultiLocalizedUnicodeType}, NULL}, &SupportedTags[63]},
{ cmsSigArgyllArtsTag, { 9, 1, { cmsSigS15Fixed16ArrayType}, NULL}, NULL}
};
/*
Not supported Why
======================= =========================================
cmsSigOutputResponseTag ==> WARNING, POSSIBLE PATENT ON THIS SUBJECT!
cmsSigNamedColorTag ==> Deprecated
cmsSigDataTag ==> Ancient, unused
cmsSigDeviceSettingsTag ==> Deprecated, useless
*/
_cmsTagPluginChunkType _cmsTagPluginChunk = { NULL };
// Duplicates the zone of memory used by the plug-in in the new context
static
void DupTagList(struct _cmsContext_struct* ctx,
const struct _cmsContext_struct* src)
{
_cmsTagPluginChunkType newHead = { NULL };
_cmsTagLinkedList* entry;
_cmsTagLinkedList* Anterior = NULL;
_cmsTagPluginChunkType* head = (_cmsTagPluginChunkType*) src->chunks[TagPlugin];
// Walk the list copying all nodes
for (entry = head->Tag;
entry != NULL;
entry = entry ->Next) {
_cmsTagLinkedList *newEntry = ( _cmsTagLinkedList *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsTagLinkedList));
if (newEntry == NULL)
return;
// We want to keep the linked list order, so this is a little bit tricky
newEntry -> Next = NULL;
if (Anterior)
Anterior -> Next = newEntry;
Anterior = newEntry;
if (newHead.Tag == NULL)
newHead.Tag = newEntry;
}
ctx ->chunks[TagPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsTagPluginChunkType));
}
void _cmsAllocTagPluginChunk(struct _cmsContext_struct* ctx,
const struct _cmsContext_struct* src)
{
if (src != NULL) {
DupTagList(ctx, src);
}
else {
static _cmsTagPluginChunkType TagPluginChunk = { NULL };
ctx ->chunks[TagPlugin] = _cmsSubAllocDup(ctx ->MemPool, &TagPluginChunk, sizeof(_cmsTagPluginChunkType));
}
}
cmsBool _cmsRegisterTagPlugin(cmsContext id, cmsPluginBase* Data)
{
cmsPluginTag* Plugin = (cmsPluginTag*) Data;
_cmsTagLinkedList *pt;
_cmsTagPluginChunkType* TagPluginChunk = ( _cmsTagPluginChunkType*) _cmsContextGetClientChunk(id, TagPlugin);
if (Data == NULL) {
TagPluginChunk->Tag = NULL;
return TRUE;
}
pt = (_cmsTagLinkedList*) _cmsPluginMalloc(id, sizeof(_cmsTagLinkedList));
if (pt == NULL) return FALSE;
pt ->Signature = Plugin ->Signature;
pt ->Descriptor = Plugin ->Descriptor;
pt ->Next = TagPluginChunk ->Tag;
TagPluginChunk ->Tag = pt;
return TRUE;
}
// Return a descriptor for a given tag or NULL
cmsTagDescriptor* _cmsGetTagDescriptor(cmsContext ContextID, cmsTagSignature sig)
{
_cmsTagLinkedList* pt;
_cmsTagPluginChunkType* TagPluginChunk = ( _cmsTagPluginChunkType*) _cmsContextGetClientChunk(ContextID, TagPlugin);
for (pt = TagPluginChunk->Tag;
pt != NULL;
pt = pt ->Next) {
if (sig == pt -> Signature) return &pt ->Descriptor;
}
for (pt = SupportedTags;
pt != NULL;
pt = pt ->Next) {
if (sig == pt -> Signature) return &pt ->Descriptor;
}
return NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4827_0 |
crossvul-cpp_data_good_514_1 | /*
* uriparser - RFC 3986 URI parsing library
*
* Copyright (C) 2007, Weijia Song <songweijia@gmail.com>
* Copyright (C) 2007, Sebastian Pipping <sebastian@pipping.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of the <ORGANIZATION> nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file UriParse.c
* Holds the RFC 3986 %URI parsing implementation.
* NOTE: This source file includes itself twice.
*/
/* What encodings are enabled? */
#include <uriparser/UriDefsConfig.h>
#if (!defined(URI_PASS_ANSI) && !defined(URI_PASS_UNICODE))
/* Include SELF twice */
# ifdef URI_ENABLE_ANSI
# define URI_PASS_ANSI 1
# include "UriParse.c"
# undef URI_PASS_ANSI
# endif
# ifdef URI_ENABLE_UNICODE
# define URI_PASS_UNICODE 1
# include "UriParse.c"
# undef URI_PASS_UNICODE
# endif
#else
# ifdef URI_PASS_ANSI
# include <uriparser/UriDefsAnsi.h>
# else
# include <uriparser/UriDefsUnicode.h>
# include <wchar.h>
# endif
#ifndef URI_DOXYGEN
# include <uriparser/Uri.h>
# include <uriparser/UriIp4.h>
# include "UriCommon.h"
# include "UriMemory.h"
# include "UriParseBase.h"
#endif
#define URI_SET_DIGIT \
_UT('0'): \
case _UT('1'): \
case _UT('2'): \
case _UT('3'): \
case _UT('4'): \
case _UT('5'): \
case _UT('6'): \
case _UT('7'): \
case _UT('8'): \
case _UT('9')
#define URI_SET_HEX_LETTER_UPPER \
_UT('A'): \
case _UT('B'): \
case _UT('C'): \
case _UT('D'): \
case _UT('E'): \
case _UT('F')
#define URI_SET_HEX_LETTER_LOWER \
_UT('a'): \
case _UT('b'): \
case _UT('c'): \
case _UT('d'): \
case _UT('e'): \
case _UT('f')
#define URI_SET_HEXDIG \
URI_SET_DIGIT: \
case URI_SET_HEX_LETTER_UPPER: \
case URI_SET_HEX_LETTER_LOWER
#define URI_SET_ALPHA \
URI_SET_HEX_LETTER_UPPER: \
case URI_SET_HEX_LETTER_LOWER: \
case _UT('g'): \
case _UT('G'): \
case _UT('h'): \
case _UT('H'): \
case _UT('i'): \
case _UT('I'): \
case _UT('j'): \
case _UT('J'): \
case _UT('k'): \
case _UT('K'): \
case _UT('l'): \
case _UT('L'): \
case _UT('m'): \
case _UT('M'): \
case _UT('n'): \
case _UT('N'): \
case _UT('o'): \
case _UT('O'): \
case _UT('p'): \
case _UT('P'): \
case _UT('q'): \
case _UT('Q'): \
case _UT('r'): \
case _UT('R'): \
case _UT('s'): \
case _UT('S'): \
case _UT('t'): \
case _UT('T'): \
case _UT('u'): \
case _UT('U'): \
case _UT('v'): \
case _UT('V'): \
case _UT('w'): \
case _UT('W'): \
case _UT('x'): \
case _UT('X'): \
case _UT('y'): \
case _UT('Y'): \
case _UT('z'): \
case _UT('Z')
static const URI_CHAR * URI_FUNC(ParseAuthority)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseAuthorityTwo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast);
static const URI_CHAR * URI_FUNC(ParseHexZero)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast);
static const URI_CHAR * URI_FUNC(ParseHierPart)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseIpFutLoop)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseIpFutStopGo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseIpLit2)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseIPv6address2)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseMustBeSegmentNzNc)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseOwnHost)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseOwnHost2)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseOwnHostUserInfo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseOwnHostUserInfoNz)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseOwnPortUserInfo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseOwnUserInfo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePartHelperTwo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePathAbsEmpty)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePathAbsNoLeadSlash)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePathRootless)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePchar)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePctEncoded)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePctSubUnres)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePort)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast);
static const URI_CHAR * URI_FUNC(ParseQueryFrag)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseSegment)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseSegmentNz)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseSegmentNzNcOrScheme2)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseUriReference)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseUriTail)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseUriTailTwo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseZeroMoreSlashSegs)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static UriBool URI_FUNC(OnExitOwnHost2)(URI_TYPE(ParserState) * state, const URI_CHAR * first, UriMemoryManager * memory);
static UriBool URI_FUNC(OnExitOwnHostUserInfo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, UriMemoryManager * memory);
static UriBool URI_FUNC(OnExitOwnPortUserInfo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, UriMemoryManager * memory);
static UriBool URI_FUNC(OnExitSegmentNzNcOrScheme2)(URI_TYPE(ParserState) * state, const URI_CHAR * first, UriMemoryManager * memory);
static void URI_FUNC(OnExitPartHelperTwo)(URI_TYPE(ParserState) * state);
static void URI_FUNC(ResetParserStateExceptUri)(URI_TYPE(ParserState) * state);
static UriBool URI_FUNC(PushPathSegment)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory);
static void URI_FUNC(StopSyntax)(URI_TYPE(ParserState) * state, const URI_CHAR * errorPos, UriMemoryManager * memory);
static void URI_FUNC(StopMalloc)(URI_TYPE(ParserState) * state, UriMemoryManager * memory);
static int URI_FUNC(ParseUriExMm)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory);
static URI_INLINE void URI_FUNC(StopSyntax)(URI_TYPE(ParserState) * state,
const URI_CHAR * errorPos, UriMemoryManager * memory) {
URI_FUNC(FreeUriMembersMm)(state->uri, memory);
state->errorPos = errorPos;
state->errorCode = URI_ERROR_SYNTAX;
}
static URI_INLINE void URI_FUNC(StopMalloc)(URI_TYPE(ParserState) * state, UriMemoryManager * memory) {
URI_FUNC(FreeUriMembersMm)(state->uri, memory);
state->errorPos = NULL;
state->errorCode = URI_ERROR_MALLOC;
}
/*
* [authority]-><[>[ipLit2][authorityTwo]
* [authority]->[ownHostUserInfoNz]
* [authority]-><NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseAuthority)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
/* "" regname host */
state->uri->hostText.first = URI_FUNC(SafeToPointTo);
state->uri->hostText.afterLast = URI_FUNC(SafeToPointTo);
return afterLast;
}
switch (*first) {
case _UT('['):
{
const URI_CHAR * const afterIpLit2
= URI_FUNC(ParseIpLit2)(state, first + 1, afterLast, memory);
if (afterIpLit2 == NULL) {
return NULL;
}
state->uri->hostText.first = first + 1; /* HOST BEGIN */
return URI_FUNC(ParseAuthorityTwo)(state, afterIpLit2, afterLast);
}
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('@'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
state->uri->userInfo.first = first; /* USERINFO BEGIN */
return URI_FUNC(ParseOwnHostUserInfoNz)(state, first, afterLast, memory);
default:
/* "" regname host */
state->uri->hostText.first = URI_FUNC(SafeToPointTo);
state->uri->hostText.afterLast = URI_FUNC(SafeToPointTo);
return first;
}
}
/*
* [authorityTwo]-><:>[port]
* [authorityTwo]-><NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseAuthorityTwo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT(':'):
{
const URI_CHAR * const afterPort = URI_FUNC(ParsePort)(state, first + 1, afterLast);
if (afterPort == NULL) {
return NULL;
}
state->uri->portText.first = first + 1; /* PORT BEGIN */
state->uri->portText.afterLast = afterPort; /* PORT END */
return afterPort;
}
default:
return first;
}
}
/*
* [hexZero]->[HEXDIG][hexZero]
* [hexZero]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParseHexZero)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case URI_SET_HEXDIG:
return URI_FUNC(ParseHexZero)(state, first + 1, afterLast);
default:
return first;
}
}
/*
* [hierPart]->[pathRootless]
* [hierPart]-></>[partHelperTwo]
* [hierPart]-><NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseHierPart)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('@'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
return URI_FUNC(ParsePathRootless)(state, first, afterLast, memory);
case _UT('/'):
return URI_FUNC(ParsePartHelperTwo)(state, first + 1, afterLast, memory);
default:
return first;
}
}
/*
* [ipFutLoop]->[subDelims][ipFutStopGo]
* [ipFutLoop]->[unreserved][ipFutStopGo]
* [ipFutLoop]-><:>[ipFutStopGo]
*/
static const URI_CHAR * URI_FUNC(ParseIpFutLoop)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
return URI_FUNC(ParseIpFutStopGo)(state, first + 1, afterLast, memory);
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
}
/*
* [ipFutStopGo]->[ipFutLoop]
* [ipFutStopGo]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParseIpFutStopGo)(
URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
return URI_FUNC(ParseIpFutLoop)(state, first, afterLast, memory);
default:
return first;
}
}
/*
* [ipFuture]-><v>[HEXDIG][hexZero]<.>[ipFutLoop]
*/
static const URI_CHAR * URI_FUNC(ParseIpFuture)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
/*
First character has already been
checked before entering this rule.
switch (*first) {
case _UT('v'):
*/
if (first + 1 >= afterLast) {
URI_FUNC(StopSyntax)(state, first + 1, memory);
return NULL;
}
switch (first[1]) {
case URI_SET_HEXDIG:
{
const URI_CHAR * afterIpFutLoop;
const URI_CHAR * const afterHexZero
= URI_FUNC(ParseHexZero)(state, first + 2, afterLast);
if (afterHexZero == NULL) {
return NULL;
}
if ((afterHexZero >= afterLast)
|| (*afterHexZero != _UT('.'))) {
URI_FUNC(StopSyntax)(state, afterHexZero, memory);
return NULL;
}
state->uri->hostText.first = first; /* HOST BEGIN */
state->uri->hostData.ipFuture.first = first; /* IPFUTURE BEGIN */
afterIpFutLoop = URI_FUNC(ParseIpFutLoop)(state, afterHexZero + 1, afterLast, memory);
if (afterIpFutLoop == NULL) {
return NULL;
}
state->uri->hostText.afterLast = afterIpFutLoop; /* HOST END */
state->uri->hostData.ipFuture.afterLast = afterIpFutLoop; /* IPFUTURE END */
return afterIpFutLoop;
}
default:
URI_FUNC(StopSyntax)(state, first + 1, memory);
return NULL;
}
/*
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
*/
}
/*
* [ipLit2]->[ipFuture]<]>
* [ipLit2]->[IPv6address2]
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseIpLit2)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
switch (*first) {
case _UT('v'):
{
const URI_CHAR * const afterIpFuture
= URI_FUNC(ParseIpFuture)(state, first, afterLast, memory);
if (afterIpFuture == NULL) {
return NULL;
}
if ((afterIpFuture >= afterLast)
|| (*afterIpFuture != _UT(']'))) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
return afterIpFuture + 1;
}
case _UT(':'):
case _UT(']'):
case URI_SET_HEXDIG:
state->uri->hostData.ip6 = memory->malloc(memory, 1 * sizeof(UriIp6)); /* Freed when stopping on parse error */
if (state->uri->hostData.ip6 == NULL) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return URI_FUNC(ParseIPv6address2)(state, first, afterLast, memory);
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
}
/*
* [IPv6address2]->..<]>
*/
static const URI_CHAR * URI_FUNC(ParseIPv6address2)(
URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
int zipperEver = 0;
int quadsDone = 0;
int digitCount = 0;
unsigned char digitHistory[4];
int ip4OctetsDone = 0;
unsigned char quadsAfterZipper[14];
int quadsAfterZipperCount = 0;
for (;;) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
/* Inside IPv4 part? */
if (ip4OctetsDone > 0) {
/* Eat rest of IPv4 address */
for (;;) {
switch (*first) {
case URI_SET_DIGIT:
if (digitCount == 4) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
digitHistory[digitCount++] = (unsigned char)(9 + *first - _UT('9'));
break;
case _UT('.'):
if ((ip4OctetsDone == 4) /* NOTE! */
|| (digitCount == 0)
|| (digitCount == 4)) {
/* Invalid digit or octet count */
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
} else if ((digitCount > 1)
&& (digitHistory[0] == 0)) {
/* Leading zero */
URI_FUNC(StopSyntax)(state, first - digitCount, memory);
return NULL;
} else if ((digitCount > 2)
&& (digitHistory[1] == 0)) {
/* Leading zero */
URI_FUNC(StopSyntax)(state, first - digitCount + 1, memory);
return NULL;
} else if ((digitCount == 3)
&& (100 * digitHistory[0]
+ 10 * digitHistory[1]
+ digitHistory[2] > 255)) {
/* Octet value too large */
if (digitHistory[0] > 2) {
URI_FUNC(StopSyntax)(state, first - 3, memory);
} else if (digitHistory[1] > 5) {
URI_FUNC(StopSyntax)(state, first - 2, memory);
} else {
URI_FUNC(StopSyntax)(state, first - 1, memory);
}
return NULL;
}
/* Copy IPv4 octet */
state->uri->hostData.ip6->data[16 - 4 + ip4OctetsDone] = uriGetOctetValue(digitHistory, digitCount);
digitCount = 0;
ip4OctetsDone++;
break;
case _UT(']'):
if ((ip4OctetsDone != 3) /* NOTE! */
|| (digitCount == 0)
|| (digitCount == 4)) {
/* Invalid digit or octet count */
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
} else if ((digitCount > 1)
&& (digitHistory[0] == 0)) {
/* Leading zero */
URI_FUNC(StopSyntax)(state, first - digitCount, memory);
return NULL;
} else if ((digitCount > 2)
&& (digitHistory[1] == 0)) {
/* Leading zero */
URI_FUNC(StopSyntax)(state, first - digitCount + 1, memory);
return NULL;
} else if ((digitCount == 3)
&& (100 * digitHistory[0]
+ 10 * digitHistory[1]
+ digitHistory[2] > 255)) {
/* Octet value too large */
if (digitHistory[0] > 2) {
URI_FUNC(StopSyntax)(state, first - 3, memory);
} else if (digitHistory[1] > 5) {
URI_FUNC(StopSyntax)(state, first - 2, memory);
} else {
URI_FUNC(StopSyntax)(state, first - 1, memory);
}
return NULL;
}
state->uri->hostText.afterLast = first; /* HOST END */
/* Copy missing quads right before IPv4 */
memcpy(state->uri->hostData.ip6->data + 16 - 4 - 2 * quadsAfterZipperCount,
quadsAfterZipper, 2 * quadsAfterZipperCount);
/* Copy last IPv4 octet */
state->uri->hostData.ip6->data[16 - 4 + 3] = uriGetOctetValue(digitHistory, digitCount);
return first + 1;
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
first++;
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
}
} else {
/* Eat while no dot in sight */
int letterAmong = 0;
int walking = 1;
do {
switch (*first) {
case URI_SET_HEX_LETTER_LOWER:
letterAmong = 1;
if (digitCount == 4) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
digitHistory[digitCount] = (unsigned char)(15 + *first - _UT('f'));
digitCount++;
break;
case URI_SET_HEX_LETTER_UPPER:
letterAmong = 1;
if (digitCount == 4) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
digitHistory[digitCount] = (unsigned char)(15 + *first - _UT('F'));
digitCount++;
break;
case URI_SET_DIGIT:
if (digitCount == 4) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
digitHistory[digitCount] = (unsigned char)(9 + *first - _UT('9'));
digitCount++;
break;
case _UT(':'):
{
int setZipper = 0;
if (digitCount > 0) {
if (zipperEver) {
uriWriteQuadToDoubleByte(digitHistory, digitCount, quadsAfterZipper + 2 * quadsAfterZipperCount);
quadsAfterZipperCount++;
} else {
uriWriteQuadToDoubleByte(digitHistory, digitCount, state->uri->hostData.ip6->data + 2 * quadsDone);
}
quadsDone++;
digitCount = 0;
}
letterAmong = 0;
/* Too many quads? */
if (quadsDone >= 8 - zipperEver) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
/* "::"? */
if (first + 1 >= afterLast) {
URI_FUNC(StopSyntax)(state, first + 1, memory);
return NULL;
}
if (first[1] == _UT(':')) {
const int resetOffset = 2 * (quadsDone + (digitCount > 0));
first++;
if (zipperEver) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL; /* "::.+::" */
}
/* Zero everything after zipper */
memset(state->uri->hostData.ip6->data + resetOffset, 0, 16 - resetOffset);
setZipper = 1;
/* ":::+"? */
if (first + 1 >= afterLast) {
URI_FUNC(StopSyntax)(state, first + 1, memory);
return NULL; /* No ']' yet */
}
if (first[1] == _UT(':')) {
URI_FUNC(StopSyntax)(state, first + 1, memory);
return NULL; /* ":::+ "*/
}
}
if (setZipper) {
zipperEver = 1;
}
}
break;
case _UT('.'):
if ((quadsDone > 6) /* NOTE */
|| (!zipperEver && (quadsDone < 6))
|| letterAmong
|| (digitCount == 0)
|| (digitCount == 4)) {
/* Invalid octet before */
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
} else if ((digitCount > 1)
&& (digitHistory[0] == 0)) {
/* Leading zero */
URI_FUNC(StopSyntax)(state, first - digitCount, memory);
return NULL;
} else if ((digitCount > 2)
&& (digitHistory[1] == 0)) {
/* Leading zero */
URI_FUNC(StopSyntax)(state, first - digitCount + 1, memory);
return NULL;
} else if ((digitCount == 3)
&& (100 * digitHistory[0]
+ 10 * digitHistory[1]
+ digitHistory[2] > 255)) {
/* Octet value too large */
if (digitHistory[0] > 2) {
URI_FUNC(StopSyntax)(state, first - 3, memory);
} else if (digitHistory[1] > 5) {
URI_FUNC(StopSyntax)(state, first - 2, memory);
} else {
URI_FUNC(StopSyntax)(state, first - 1, memory);
}
return NULL;
}
/* Copy first IPv4 octet */
state->uri->hostData.ip6->data[16 - 4] = uriGetOctetValue(digitHistory, digitCount);
digitCount = 0;
/* Switch over to IPv4 loop */
ip4OctetsDone = 1;
walking = 0;
break;
case _UT(']'):
/* Too little quads? */
if (!zipperEver && !((quadsDone == 7) && (digitCount > 0))) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
if (digitCount > 0) {
if (zipperEver) {
uriWriteQuadToDoubleByte(digitHistory, digitCount, quadsAfterZipper + 2 * quadsAfterZipperCount);
quadsAfterZipperCount++;
} else {
uriWriteQuadToDoubleByte(digitHistory, digitCount, state->uri->hostData.ip6->data + 2 * quadsDone);
}
/*
quadsDone++;
digitCount = 0;
*/
}
/* Copy missing quads to the end */
memcpy(state->uri->hostData.ip6->data + 16 - 2 * quadsAfterZipperCount,
quadsAfterZipper, 2 * quadsAfterZipperCount);
state->uri->hostText.afterLast = first; /* HOST END */
return first + 1; /* Fine */
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
first++;
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL; /* No ']' yet */
}
} while (walking);
}
}
}
/*
* [mustBeSegmentNzNc]->[pctEncoded][mustBeSegmentNzNc]
* [mustBeSegmentNzNc]->[subDelims][mustBeSegmentNzNc]
* [mustBeSegmentNzNc]->[unreserved][mustBeSegmentNzNc]
* [mustBeSegmentNzNc]->[uriTail] // can take <NULL>
* [mustBeSegmentNzNc]-></>[segment][zeroMoreSlashSegs][uriTail]
* [mustBeSegmentNzNc]-><@>[mustBeSegmentNzNc]
*/
static const URI_CHAR * URI_FUNC(ParseMustBeSegmentNzNc)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
if (!URI_FUNC(PushPathSegment)(state, state->uri->scheme.first, first, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
state->uri->scheme.first = NULL; /* Not a scheme, reset */
return afterLast;
}
switch (*first) {
case _UT('%'):
{
const URI_CHAR * const afterPctEncoded
= URI_FUNC(ParsePctEncoded)(state, first, afterLast, memory);
if (afterPctEncoded == NULL) {
return NULL;
}
return URI_FUNC(ParseMustBeSegmentNzNc)(state, afterPctEncoded, afterLast, memory);
}
case _UT('@'):
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('*'):
case _UT(','):
case _UT(';'):
case _UT('\''):
case _UT('+'):
case _UT('='):
case _UT('-'):
case _UT('.'):
case _UT('_'):
case _UT('~'):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
return URI_FUNC(ParseMustBeSegmentNzNc)(state, first + 1, afterLast, memory);
case _UT('/'):
{
const URI_CHAR * afterZeroMoreSlashSegs;
const URI_CHAR * afterSegment;
if (!URI_FUNC(PushPathSegment)(state, state->uri->scheme.first, first, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
state->uri->scheme.first = NULL; /* Not a scheme, reset */
afterSegment = URI_FUNC(ParseSegment)(state, first + 1, afterLast, memory);
if (afterSegment == NULL) {
return NULL;
}
if (!URI_FUNC(PushPathSegment)(state, first + 1, afterSegment, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
afterZeroMoreSlashSegs
= URI_FUNC(ParseZeroMoreSlashSegs)(state, afterSegment, afterLast, memory);
if (afterZeroMoreSlashSegs == NULL) {
return NULL;
}
return URI_FUNC(ParseUriTail)(state, afterZeroMoreSlashSegs, afterLast, memory);
}
default:
if (!URI_FUNC(PushPathSegment)(state, state->uri->scheme.first, first, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
state->uri->scheme.first = NULL; /* Not a scheme, reset */
return URI_FUNC(ParseUriTail)(state, first, afterLast, memory);
}
}
/*
* [ownHost]-><[>[ipLit2][authorityTwo]
* [ownHost]->[ownHost2] // can take <NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseOwnHost)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
state->uri->hostText.afterLast = afterLast; /* HOST END */
return afterLast;
}
switch (*first) {
case _UT('['):
{
const URI_CHAR * const afterIpLit2
= URI_FUNC(ParseIpLit2)(state, first + 1, afterLast, memory);
if (afterIpLit2 == NULL) {
return NULL;
}
state->uri->hostText.first = first + 1; /* HOST BEGIN */
return URI_FUNC(ParseAuthorityTwo)(state, afterIpLit2, afterLast);
}
default:
return URI_FUNC(ParseOwnHost2)(state, first, afterLast, memory);
}
}
static URI_INLINE UriBool URI_FUNC(OnExitOwnHost2)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
UriMemoryManager * memory) {
state->uri->hostText.afterLast = first; /* HOST END */
/* Valid IPv4 or just a regname? */
state->uri->hostData.ip4 = memory->malloc(memory, 1 * sizeof(UriIp4)); /* Freed when stopping on parse error */
if (state->uri->hostData.ip4 == NULL) {
return URI_FALSE; /* Raises malloc error */
}
if (URI_FUNC(ParseIpFourAddress)(state->uri->hostData.ip4->data,
state->uri->hostText.first, state->uri->hostText.afterLast)) {
/* Not IPv4 */
memory->free(memory, state->uri->hostData.ip4);
state->uri->hostData.ip4 = NULL;
}
return URI_TRUE; /* Success */
}
/*
* [ownHost2]->[authorityTwo] // can take <NULL>
* [ownHost2]->[pctSubUnres][ownHost2]
*/
static const URI_CHAR * URI_FUNC(ParseOwnHost2)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
if (!URI_FUNC(OnExitOwnHost2)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return afterLast;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(';'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
{
const URI_CHAR * const afterPctSubUnres
= URI_FUNC(ParsePctSubUnres)(state, first, afterLast, memory);
if (afterPctSubUnres == NULL) {
return NULL;
}
return URI_FUNC(ParseOwnHost2)(state, afterPctSubUnres, afterLast, memory);
}
default:
if (!URI_FUNC(OnExitOwnHost2)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return URI_FUNC(ParseAuthorityTwo)(state, first, afterLast);
}
}
static URI_INLINE UriBool URI_FUNC(OnExitOwnHostUserInfo)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
UriMemoryManager * memory) {
state->uri->hostText.first = state->uri->userInfo.first; /* Host instead of userInfo, update */
state->uri->userInfo.first = NULL; /* Not a userInfo, reset */
state->uri->hostText.afterLast = first; /* HOST END */
/* Valid IPv4 or just a regname? */
state->uri->hostData.ip4 = memory->malloc(memory, 1 * sizeof(UriIp4)); /* Freed when stopping on parse error */
if (state->uri->hostData.ip4 == NULL) {
return URI_FALSE; /* Raises malloc error */
}
if (URI_FUNC(ParseIpFourAddress)(state->uri->hostData.ip4->data,
state->uri->hostText.first, state->uri->hostText.afterLast)) {
/* Not IPv4 */
memory->free(memory, state->uri->hostData.ip4);
state->uri->hostData.ip4 = NULL;
}
return URI_TRUE; /* Success */
}
/*
* [ownHostUserInfo]->[ownHostUserInfoNz]
* [ownHostUserInfo]-><NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseOwnHostUserInfo)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
if (!URI_FUNC(OnExitOwnHostUserInfo)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return afterLast;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('@'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
return URI_FUNC(ParseOwnHostUserInfoNz)(state, first, afterLast, memory);
default:
if (!URI_FUNC(OnExitOwnHostUserInfo)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return first;
}
}
/*
* [ownHostUserInfoNz]->[pctSubUnres][ownHostUserInfo]
* [ownHostUserInfoNz]-><:>[ownPortUserInfo]
* [ownHostUserInfoNz]-><@>[ownHost]
*/
static const URI_CHAR * URI_FUNC(ParseOwnHostUserInfoNz)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(';'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
{
const URI_CHAR * const afterPctSubUnres
= URI_FUNC(ParsePctSubUnres)(state, first, afterLast, memory);
if (afterPctSubUnres == NULL) {
return NULL;
}
return URI_FUNC(ParseOwnHostUserInfo)(state, afterPctSubUnres, afterLast, memory);
}
case _UT(':'):
state->uri->hostText.afterLast = first; /* HOST END */
state->uri->portText.first = first + 1; /* PORT BEGIN */
return URI_FUNC(ParseOwnPortUserInfo)(state, first + 1, afterLast, memory);
case _UT('@'):
state->uri->userInfo.afterLast = first; /* USERINFO END */
state->uri->hostText.first = first + 1; /* HOST BEGIN */
return URI_FUNC(ParseOwnHost)(state, first + 1, afterLast, memory);
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
}
static URI_INLINE UriBool URI_FUNC(OnExitOwnPortUserInfo)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
UriMemoryManager * memory) {
state->uri->hostText.first = state->uri->userInfo.first; /* Host instead of userInfo, update */
state->uri->userInfo.first = NULL; /* Not a userInfo, reset */
state->uri->portText.afterLast = first; /* PORT END */
/* Valid IPv4 or just a regname? */
state->uri->hostData.ip4 = memory->malloc(memory, 1 * sizeof(UriIp4)); /* Freed when stopping on parse error */
if (state->uri->hostData.ip4 == NULL) {
return URI_FALSE; /* Raises malloc error */
}
if (URI_FUNC(ParseIpFourAddress)(state->uri->hostData.ip4->data,
state->uri->hostText.first, state->uri->hostText.afterLast)) {
/* Not IPv4 */
memory->free(memory, state->uri->hostData.ip4);
state->uri->hostData.ip4 = NULL;
}
return URI_TRUE; /* Success */
}
/*
* [ownPortUserInfo]->[ALPHA][ownUserInfo]
* [ownPortUserInfo]->[DIGIT][ownPortUserInfo]
* [ownPortUserInfo]-><.>[ownUserInfo]
* [ownPortUserInfo]-><_>[ownUserInfo]
* [ownPortUserInfo]-><~>[ownUserInfo]
* [ownPortUserInfo]-><->[ownUserInfo]
* [ownPortUserInfo]->[subDelims][ownUserInfo]
* [ownPortUserInfo]->[pctEncoded][ownUserInfo]
* [ownPortUserInfo]-><:>[ownUserInfo]
* [ownPortUserInfo]-><@>[ownHost]
* [ownPortUserInfo]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParseOwnPortUserInfo)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
if (!URI_FUNC(OnExitOwnPortUserInfo)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return afterLast;
}
switch (*first) {
/* begin sub-delims */
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('\''):
case _UT('('):
case _UT(')'):
case _UT('*'):
case _UT('+'):
case _UT(','):
case _UT(';'):
case _UT('='):
/* end sub-delims */
/* begin unreserved (except alpha and digit) */
case _UT('-'):
case _UT('.'):
case _UT('_'):
case _UT('~'):
/* end unreserved (except alpha and digit) */
case _UT(':'):
case URI_SET_ALPHA:
state->uri->hostText.afterLast = NULL; /* Not a host, reset */
state->uri->portText.first = NULL; /* Not a port, reset */
return URI_FUNC(ParseOwnUserInfo)(state, first + 1, afterLast, memory);
case URI_SET_DIGIT:
return URI_FUNC(ParseOwnPortUserInfo)(state, first + 1, afterLast, memory);
case _UT('%'):
state->uri->portText.first = NULL; /* Not a port, reset */
{
const URI_CHAR * const afterPct
= URI_FUNC(ParsePctEncoded)(state, first, afterLast, memory);
if (afterPct == NULL) {
return NULL;
}
return URI_FUNC(ParseOwnUserInfo)(state, afterPct, afterLast, memory);
}
case _UT('@'):
state->uri->hostText.afterLast = NULL; /* Not a host, reset */
state->uri->portText.first = NULL; /* Not a port, reset */
state->uri->userInfo.afterLast = first; /* USERINFO END */
state->uri->hostText.first = first + 1; /* HOST BEGIN */
return URI_FUNC(ParseOwnHost)(state, first + 1, afterLast, memory);
default:
if (!URI_FUNC(OnExitOwnPortUserInfo)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return first;
}
}
/*
* [ownUserInfo]->[pctSubUnres][ownUserInfo]
* [ownUserInfo]-><:>[ownUserInfo]
* [ownUserInfo]-><@>[ownHost]
*/
static const URI_CHAR * URI_FUNC(ParseOwnUserInfo)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(';'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
{
const URI_CHAR * const afterPctSubUnres
= URI_FUNC(ParsePctSubUnres)(state, first, afterLast, memory);
if (afterPctSubUnres == NULL) {
return NULL;
}
return URI_FUNC(ParseOwnUserInfo)(state, afterPctSubUnres, afterLast, memory);
}
case _UT(':'):
return URI_FUNC(ParseOwnUserInfo)(state, first + 1, afterLast, memory);
case _UT('@'):
/* SURE */
state->uri->userInfo.afterLast = first; /* USERINFO END */
state->uri->hostText.first = first + 1; /* HOST BEGIN */
return URI_FUNC(ParseOwnHost)(state, first + 1, afterLast, memory);
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
}
static URI_INLINE void URI_FUNC(OnExitPartHelperTwo)(URI_TYPE(ParserState) * state) {
state->uri->absolutePath = URI_TRUE;
}
/*
* [partHelperTwo]->[pathAbsNoLeadSlash] // can take <NULL>
* [partHelperTwo]-></>[authority][pathAbsEmpty]
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParsePartHelperTwo)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(OnExitPartHelperTwo)(state);
return afterLast;
}
switch (*first) {
case _UT('/'):
{
const URI_CHAR * const afterAuthority
= URI_FUNC(ParseAuthority)(state, first + 1, afterLast, memory);
const URI_CHAR * afterPathAbsEmpty;
if (afterAuthority == NULL) {
return NULL;
}
afterPathAbsEmpty = URI_FUNC(ParsePathAbsEmpty)(state, afterAuthority, afterLast, memory);
URI_FUNC(FixEmptyTrailSegment)(state->uri, memory);
return afterPathAbsEmpty;
}
default:
URI_FUNC(OnExitPartHelperTwo)(state);
return URI_FUNC(ParsePathAbsNoLeadSlash)(state, first, afterLast, memory);
}
}
/*
* [pathAbsEmpty]-></>[segment][pathAbsEmpty]
* [pathAbsEmpty]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParsePathAbsEmpty)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('/'):
{
const URI_CHAR * const afterSegment
= URI_FUNC(ParseSegment)(state, first + 1, afterLast, memory);
if (afterSegment == NULL) {
return NULL;
}
if (!URI_FUNC(PushPathSegment)(state, first + 1, afterSegment, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return URI_FUNC(ParsePathAbsEmpty)(state, afterSegment, afterLast, memory);
}
default:
return first;
}
}
/*
* [pathAbsNoLeadSlash]->[segmentNz][zeroMoreSlashSegs]
* [pathAbsNoLeadSlash]-><NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParsePathAbsNoLeadSlash)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('@'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
{
const URI_CHAR * const afterSegmentNz
= URI_FUNC(ParseSegmentNz)(state, first, afterLast, memory);
if (afterSegmentNz == NULL) {
return NULL;
}
if (!URI_FUNC(PushPathSegment)(state, first, afterSegmentNz, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return URI_FUNC(ParseZeroMoreSlashSegs)(state, afterSegmentNz, afterLast, memory);
}
default:
return first;
}
}
/*
* [pathRootless]->[segmentNz][zeroMoreSlashSegs]
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParsePathRootless)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
const URI_CHAR * const afterSegmentNz
= URI_FUNC(ParseSegmentNz)(state, first, afterLast, memory);
if (afterSegmentNz == NULL) {
return NULL;
} else {
if (!URI_FUNC(PushPathSegment)(state, first, afterSegmentNz, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
}
return URI_FUNC(ParseZeroMoreSlashSegs)(state, afterSegmentNz, afterLast, memory);
}
/*
* [pchar]->[pctEncoded]
* [pchar]->[subDelims]
* [pchar]->[unreserved]
* [pchar]-><:>
* [pchar]-><@>
*/
static const URI_CHAR * URI_FUNC(ParsePchar)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
switch (*first) {
case _UT('%'):
return URI_FUNC(ParsePctEncoded)(state, first, afterLast, memory);
case _UT(':'):
case _UT('@'):
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('*'):
case _UT(','):
case _UT(';'):
case _UT('\''):
case _UT('+'):
case _UT('='):
case _UT('-'):
case _UT('.'):
case _UT('_'):
case _UT('~'):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
return first + 1;
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
}
/*
* [pctEncoded]-><%>[HEXDIG][HEXDIG]
*/
static const URI_CHAR * URI_FUNC(ParsePctEncoded)(
URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
/*
First character has already been
checked before entering this rule.
switch (*first) {
case _UT('%'):
*/
if (first + 1 >= afterLast) {
URI_FUNC(StopSyntax)(state, first + 1, memory);
return NULL;
}
switch (first[1]) {
case URI_SET_HEXDIG:
if (first + 2 >= afterLast) {
URI_FUNC(StopSyntax)(state, first + 2, memory);
return NULL;
}
switch (first[2]) {
case URI_SET_HEXDIG:
return first + 3;
default:
URI_FUNC(StopSyntax)(state, first + 2, memory);
return NULL;
}
default:
URI_FUNC(StopSyntax)(state, first + 1, memory);
return NULL;
}
/*
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
*/
}
/*
* [pctSubUnres]->[pctEncoded]
* [pctSubUnres]->[subDelims]
* [pctSubUnres]->[unreserved]
*/
static const URI_CHAR * URI_FUNC(ParsePctSubUnres)(
URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
switch (*first) {
case _UT('%'):
return URI_FUNC(ParsePctEncoded)(state, first, afterLast, memory);
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('*'):
case _UT(','):
case _UT(';'):
case _UT('\''):
case _UT('+'):
case _UT('='):
case _UT('-'):
case _UT('.'):
case _UT('_'):
case _UT('~'):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
return first + 1;
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
}
/*
* [port]->[DIGIT][port]
* [port]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParsePort)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case URI_SET_DIGIT:
return URI_FUNC(ParsePort)(state, first + 1, afterLast);
default:
return first;
}
}
/*
* [queryFrag]->[pchar][queryFrag]
* [queryFrag]-></>[queryFrag]
* [queryFrag]-><?>[queryFrag]
* [queryFrag]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParseQueryFrag)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('@'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
{
const URI_CHAR * const afterPchar
= URI_FUNC(ParsePchar)(state, first, afterLast, memory);
if (afterPchar == NULL) {
return NULL;
}
return URI_FUNC(ParseQueryFrag)(state, afterPchar, afterLast, memory);
}
case _UT('/'):
case _UT('?'):
return URI_FUNC(ParseQueryFrag)(state, first + 1, afterLast, memory);
default:
return first;
}
}
/*
* [segment]->[pchar][segment]
* [segment]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParseSegment)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('@'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
{
const URI_CHAR * const afterPchar
= URI_FUNC(ParsePchar)(state, first, afterLast, memory);
if (afterPchar == NULL) {
return NULL;
}
return URI_FUNC(ParseSegment)(state, afterPchar, afterLast, memory);
}
default:
return first;
}
}
/*
* [segmentNz]->[pchar][segment]
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseSegmentNz)(
URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
const URI_CHAR * const afterPchar
= URI_FUNC(ParsePchar)(state, first, afterLast, memory);
if (afterPchar == NULL) {
return NULL;
}
return URI_FUNC(ParseSegment)(state, afterPchar, afterLast, memory);
}
static URI_INLINE UriBool URI_FUNC(OnExitSegmentNzNcOrScheme2)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
UriMemoryManager * memory) {
if (!URI_FUNC(PushPathSegment)(state, state->uri->scheme.first, first, memory)) { /* SEGMENT BOTH */
return URI_FALSE; /* Raises malloc error*/
}
state->uri->scheme.first = NULL; /* Not a scheme, reset */
return URI_TRUE; /* Success */
}
/*
* [segmentNzNcOrScheme2]->[ALPHA][segmentNzNcOrScheme2]
* [segmentNzNcOrScheme2]->[DIGIT][segmentNzNcOrScheme2]
* [segmentNzNcOrScheme2]->[pctEncoded][mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]->[uriTail] // can take <NULL>
* [segmentNzNcOrScheme2]-><!>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><$>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><&>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><(>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><)>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><*>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><,>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><.>[segmentNzNcOrScheme2]
* [segmentNzNcOrScheme2]-></>[segment][zeroMoreSlashSegs][uriTail]
* [segmentNzNcOrScheme2]-><:>[hierPart][uriTail]
* [segmentNzNcOrScheme2]-><;>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><@>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><_>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><~>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><+>[segmentNzNcOrScheme2]
* [segmentNzNcOrScheme2]-><=>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><'>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><->[segmentNzNcOrScheme2]
*/
static const URI_CHAR * URI_FUNC(ParseSegmentNzNcOrScheme2)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
if (!URI_FUNC(OnExitSegmentNzNcOrScheme2)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return afterLast;
}
switch (*first) {
case _UT('.'):
case _UT('+'):
case _UT('-'):
case URI_SET_ALPHA:
case URI_SET_DIGIT:
return URI_FUNC(ParseSegmentNzNcOrScheme2)(state, first + 1, afterLast, memory);
case _UT('%'):
{
const URI_CHAR * const afterPctEncoded
= URI_FUNC(ParsePctEncoded)(state, first, afterLast, memory);
if (afterPctEncoded == NULL) {
return NULL;
}
return URI_FUNC(ParseMustBeSegmentNzNc)(state, afterPctEncoded, afterLast, memory);
}
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('*'):
case _UT(','):
case _UT(';'):
case _UT('@'):
case _UT('_'):
case _UT('~'):
case _UT('='):
case _UT('\''):
return URI_FUNC(ParseMustBeSegmentNzNc)(state, first + 1, afterLast, memory);
case _UT('/'):
{
const URI_CHAR * afterZeroMoreSlashSegs;
const URI_CHAR * const afterSegment
= URI_FUNC(ParseSegment)(state, first + 1, afterLast, memory);
if (afterSegment == NULL) {
return NULL;
}
if (!URI_FUNC(PushPathSegment)(state, state->uri->scheme.first, first, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
state->uri->scheme.first = NULL; /* Not a scheme, reset */
if (!URI_FUNC(PushPathSegment)(state, first + 1, afterSegment, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
afterZeroMoreSlashSegs
= URI_FUNC(ParseZeroMoreSlashSegs)(state, afterSegment, afterLast, memory);
if (afterZeroMoreSlashSegs == NULL) {
return NULL;
}
return URI_FUNC(ParseUriTail)(state, afterZeroMoreSlashSegs, afterLast, memory);
}
case _UT(':'):
{
const URI_CHAR * const afterHierPart
= URI_FUNC(ParseHierPart)(state, first + 1, afterLast, memory);
state->uri->scheme.afterLast = first; /* SCHEME END */
if (afterHierPart == NULL) {
return NULL;
}
return URI_FUNC(ParseUriTail)(state, afterHierPart, afterLast, memory);
}
default:
if (!URI_FUNC(OnExitSegmentNzNcOrScheme2)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return URI_FUNC(ParseUriTail)(state, first, afterLast, memory);
}
}
/*
* [uriReference]->[ALPHA][segmentNzNcOrScheme2]
* [uriReference]->[DIGIT][mustBeSegmentNzNc]
* [uriReference]->[pctEncoded][mustBeSegmentNzNc]
* [uriReference]->[subDelims][mustBeSegmentNzNc]
* [uriReference]->[uriTail] // can take <NULL>
* [uriReference]-><.>[mustBeSegmentNzNc]
* [uriReference]-></>[partHelperTwo][uriTail]
* [uriReference]-><@>[mustBeSegmentNzNc]
* [uriReference]-><_>[mustBeSegmentNzNc]
* [uriReference]-><~>[mustBeSegmentNzNc]
* [uriReference]-><->[mustBeSegmentNzNc]
*/
static const URI_CHAR * URI_FUNC(ParseUriReference)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case URI_SET_ALPHA:
state->uri->scheme.first = first; /* SCHEME BEGIN */
return URI_FUNC(ParseSegmentNzNcOrScheme2)(state, first + 1, afterLast, memory);
case URI_SET_DIGIT:
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('*'):
case _UT(','):
case _UT(';'):
case _UT('\''):
case _UT('+'):
case _UT('='):
case _UT('.'):
case _UT('_'):
case _UT('~'):
case _UT('-'):
case _UT('@'):
state->uri->scheme.first = first; /* SEGMENT BEGIN, ABUSE SCHEME POINTER */
return URI_FUNC(ParseMustBeSegmentNzNc)(state, first + 1, afterLast, memory);
case _UT('%'):
{
const URI_CHAR * const afterPctEncoded
= URI_FUNC(ParsePctEncoded)(state, first, afterLast, memory);
if (afterPctEncoded == NULL) {
return NULL;
}
state->uri->scheme.first = first; /* SEGMENT BEGIN, ABUSE SCHEME POINTER */
return URI_FUNC(ParseMustBeSegmentNzNc)(state, afterPctEncoded, afterLast, memory);
}
case _UT('/'):
{
const URI_CHAR * const afterPartHelperTwo
= URI_FUNC(ParsePartHelperTwo)(state, first + 1, afterLast, memory);
if (afterPartHelperTwo == NULL) {
return NULL;
}
return URI_FUNC(ParseUriTail)(state, afterPartHelperTwo, afterLast, memory);
}
default:
return URI_FUNC(ParseUriTail)(state, first, afterLast, memory);
}
}
/*
* [uriTail]-><#>[queryFrag]
* [uriTail]-><?>[queryFrag][uriTailTwo]
* [uriTail]-><NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseUriTail)(
URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('#'):
{
const URI_CHAR * const afterQueryFrag = URI_FUNC(ParseQueryFrag)(state, first + 1, afterLast, memory);
if (afterQueryFrag == NULL) {
return NULL;
}
state->uri->fragment.first = first + 1; /* FRAGMENT BEGIN */
state->uri->fragment.afterLast = afterQueryFrag; /* FRAGMENT END */
return afterQueryFrag;
}
case _UT('?'):
{
const URI_CHAR * const afterQueryFrag
= URI_FUNC(ParseQueryFrag)(state, first + 1, afterLast, memory);
if (afterQueryFrag == NULL) {
return NULL;
}
state->uri->query.first = first + 1; /* QUERY BEGIN */
state->uri->query.afterLast = afterQueryFrag; /* QUERY END */
return URI_FUNC(ParseUriTailTwo)(state, afterQueryFrag, afterLast, memory);
}
default:
return first;
}
}
/*
* [uriTailTwo]-><#>[queryFrag]
* [uriTailTwo]-><NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseUriTailTwo)(
URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('#'):
{
const URI_CHAR * const afterQueryFrag = URI_FUNC(ParseQueryFrag)(state, first + 1, afterLast, memory);
if (afterQueryFrag == NULL) {
return NULL;
}
state->uri->fragment.first = first + 1; /* FRAGMENT BEGIN */
state->uri->fragment.afterLast = afterQueryFrag; /* FRAGMENT END */
return afterQueryFrag;
}
default:
return first;
}
}
/*
* [zeroMoreSlashSegs]-></>[segment][zeroMoreSlashSegs]
* [zeroMoreSlashSegs]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParseZeroMoreSlashSegs)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('/'):
{
const URI_CHAR * const afterSegment
= URI_FUNC(ParseSegment)(state, first + 1, afterLast, memory);
if (afterSegment == NULL) {
return NULL;
}
if (!URI_FUNC(PushPathSegment)(state, first + 1, afterSegment, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return URI_FUNC(ParseZeroMoreSlashSegs)(state, afterSegment, afterLast, memory);
}
default:
return first;
}
}
static URI_INLINE void URI_FUNC(ResetParserStateExceptUri)(URI_TYPE(ParserState) * state) {
URI_TYPE(Uri) * const uriBackup = state->uri;
memset(state, 0, sizeof(URI_TYPE(ParserState)));
state->uri = uriBackup;
}
static URI_INLINE UriBool URI_FUNC(PushPathSegment)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
URI_TYPE(PathSegment) * segment = memory->calloc(memory, 1, sizeof(URI_TYPE(PathSegment)));
if (segment == NULL) {
return URI_FALSE; /* Raises malloc error */
}
if (first == afterLast) {
segment->text.first = URI_FUNC(SafeToPointTo);
segment->text.afterLast = URI_FUNC(SafeToPointTo);
} else {
segment->text.first = first;
segment->text.afterLast = afterLast;
}
/* First segment ever? */
if (state->uri->pathHead == NULL) {
/* First segment ever, set head and tail */
state->uri->pathHead = segment;
state->uri->pathTail = segment;
} else {
/* Append, update tail */
state->uri->pathTail->next = segment;
state->uri->pathTail = segment;
}
return URI_TRUE; /* Success */
}
int URI_FUNC(ParseUriEx)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast) {
return URI_FUNC(ParseUriExMm)(state, first, afterLast, NULL);
}
static int URI_FUNC(ParseUriExMm)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
const URI_CHAR * afterUriReference;
URI_TYPE(Uri) * uri;
/* Check params */
if ((state == NULL) || (first == NULL) || (afterLast == NULL)) {
return URI_ERROR_NULL;
}
URI_CHECK_MEMORY_MANAGER(memory); /* may return */
uri = state->uri;
/* Init parser */
URI_FUNC(ResetParserStateExceptUri)(state);
URI_FUNC(ResetUri)(uri);
/* Parse */
afterUriReference = URI_FUNC(ParseUriReference)(state, first, afterLast, memory);
if (afterUriReference == NULL) {
return state->errorCode;
}
if (afterUriReference != afterLast) {
URI_FUNC(StopSyntax)(state, afterUriReference, memory);
return state->errorCode;
}
return URI_SUCCESS;
}
int URI_FUNC(ParseUri)(URI_TYPE(ParserState) * state, const URI_CHAR * text) {
if ((state == NULL) || (text == NULL)) {
return URI_ERROR_NULL;
}
return URI_FUNC(ParseUriEx)(state, text, text + URI_STRLEN(text));
}
int URI_FUNC(ParseSingleUri)(URI_TYPE(Uri) * uri, const URI_CHAR * text,
const URI_CHAR ** errorPos) {
return URI_FUNC(ParseSingleUriEx)(uri, text, NULL, errorPos);
}
int URI_FUNC(ParseSingleUriEx)(URI_TYPE(Uri) * uri,
const URI_CHAR * first, const URI_CHAR * afterLast,
const URI_CHAR ** errorPos) {
if ((afterLast == NULL) && (first != NULL)) {
afterLast = first + URI_STRLEN(first);
}
return URI_FUNC(ParseSingleUriExMm)(uri, first, afterLast, errorPos, NULL);
}
int URI_FUNC(ParseSingleUriExMm)(URI_TYPE(Uri) * uri,
const URI_CHAR * first, const URI_CHAR * afterLast,
const URI_CHAR ** errorPos, UriMemoryManager * memory) {
URI_TYPE(ParserState) state;
int res;
/* Check params */
if ((uri == NULL) || (first == NULL) || (afterLast == NULL)) {
return URI_ERROR_NULL;
}
URI_CHECK_MEMORY_MANAGER(memory); /* may return */
state.uri = uri;
res = URI_FUNC(ParseUriExMm)(&state, first, afterLast, memory);
if (res != URI_SUCCESS) {
if (errorPos != NULL) {
*errorPos = state.errorPos;
}
URI_FUNC(FreeUriMembersMm)(uri, memory);
}
return res;
}
void URI_FUNC(FreeUriMembers)(URI_TYPE(Uri) * uri) {
URI_FUNC(FreeUriMembersMm)(uri, NULL);
}
int URI_FUNC(FreeUriMembersMm)(URI_TYPE(Uri) * uri, UriMemoryManager * memory) {
if (uri == NULL) {
return URI_ERROR_NULL;
}
URI_CHECK_MEMORY_MANAGER(memory); /* may return */
if (uri->owner) {
/* Scheme */
if (uri->scheme.first != NULL) {
if (uri->scheme.first != uri->scheme.afterLast) {
memory->free(memory, (URI_CHAR *)uri->scheme.first);
}
uri->scheme.first = NULL;
uri->scheme.afterLast = NULL;
}
/* User info */
if (uri->userInfo.first != NULL) {
if (uri->userInfo.first != uri->userInfo.afterLast) {
memory->free(memory, (URI_CHAR *)uri->userInfo.first);
}
uri->userInfo.first = NULL;
uri->userInfo.afterLast = NULL;
}
/* Host data - IPvFuture */
if (uri->hostData.ipFuture.first != NULL) {
if (uri->hostData.ipFuture.first != uri->hostData.ipFuture.afterLast) {
memory->free(memory, (URI_CHAR *)uri->hostData.ipFuture.first);
}
uri->hostData.ipFuture.first = NULL;
uri->hostData.ipFuture.afterLast = NULL;
uri->hostText.first = NULL;
uri->hostText.afterLast = NULL;
}
/* Host text (if regname, after IPvFuture!) */
if ((uri->hostText.first != NULL)
&& (uri->hostData.ip4 == NULL)
&& (uri->hostData.ip6 == NULL)) {
/* Real regname */
if (uri->hostText.first != uri->hostText.afterLast) {
memory->free(memory, (URI_CHAR *)uri->hostText.first);
}
uri->hostText.first = NULL;
uri->hostText.afterLast = NULL;
}
}
/* Host data - IPv4 */
if (uri->hostData.ip4 != NULL) {
memory->free(memory, uri->hostData.ip4);
uri->hostData.ip4 = NULL;
}
/* Host data - IPv6 */
if (uri->hostData.ip6 != NULL) {
memory->free(memory, uri->hostData.ip6);
uri->hostData.ip6 = NULL;
}
/* Port text */
if (uri->owner && (uri->portText.first != NULL)) {
if (uri->portText.first != uri->portText.afterLast) {
memory->free(memory, (URI_CHAR *)uri->portText.first);
}
uri->portText.first = NULL;
uri->portText.afterLast = NULL;
}
/* Path */
if (uri->pathHead != NULL) {
URI_TYPE(PathSegment) * segWalk = uri->pathHead;
while (segWalk != NULL) {
URI_TYPE(PathSegment) * const next = segWalk->next;
if (uri->owner && (segWalk->text.first != NULL)
&& (segWalk->text.first < segWalk->text.afterLast)) {
memory->free(memory, (URI_CHAR *)segWalk->text.first);
}
memory->free(memory, segWalk);
segWalk = next;
}
uri->pathHead = NULL;
uri->pathTail = NULL;
}
if (uri->owner) {
/* Query */
if (uri->query.first != NULL) {
if (uri->query.first != uri->query.afterLast) {
memory->free(memory, (URI_CHAR *)uri->query.first);
}
uri->query.first = NULL;
uri->query.afterLast = NULL;
}
/* Fragment */
if (uri->fragment.first != NULL) {
if (uri->fragment.first != uri->fragment.afterLast) {
memory->free(memory, (URI_CHAR *)uri->fragment.first);
}
uri->fragment.first = NULL;
uri->fragment.afterLast = NULL;
}
}
return URI_SUCCESS;
}
UriBool URI_FUNC(_TESTING_ONLY_ParseIpSix)(const URI_CHAR * text) {
UriMemoryManager * const memory = &defaultMemoryManager;
URI_TYPE(Uri) uri;
URI_TYPE(ParserState) parser;
const URI_CHAR * const afterIpSix = text + URI_STRLEN(text);
const URI_CHAR * res;
URI_FUNC(ResetUri)(&uri);
parser.uri = &uri;
URI_FUNC(ResetParserStateExceptUri)(&parser);
parser.uri->hostData.ip6 = memory->malloc(memory, 1 * sizeof(UriIp6));
res = URI_FUNC(ParseIPv6address2)(&parser, text, afterIpSix, memory);
URI_FUNC(FreeUriMembersMm)(&uri, memory);
return res == afterIpSix ? URI_TRUE : URI_FALSE;
}
UriBool URI_FUNC(_TESTING_ONLY_ParseIpFour)(const URI_CHAR * text) {
unsigned char octets[4];
int res = URI_FUNC(ParseIpFourAddress)(octets, text, text + URI_STRLEN(text));
return (res == URI_SUCCESS) ? URI_TRUE : URI_FALSE;
}
#undef URI_SET_DIGIT
#undef URI_SET_HEX_LETTER_UPPER
#undef URI_SET_HEX_LETTER_LOWER
#undef URI_SET_HEXDIG
#undef URI_SET_ALPHA
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_514_1 |
crossvul-cpp_data_good_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(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if(image2!=NULL)
if(image2!=image) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) unlink(clone_info->filename);
}
}
}
}
clone_info=DestroyImageInfo(clone_info);
RelinquishMagickMemory(BImgBuff);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r M A T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method RegisterMATImage adds attributes for the MAT image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterMATImage method is:
%
% size_t RegisterMATImage(void)
%
*/
ModuleExport size_t RegisterMATImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("MAT");
entry->decoder=(DecodeImageHandler *) ReadMATImage;
entry->encoder=(EncodeImageHandler *) WriteMATImage;
entry->blob_support=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=AcquireString("MATLAB level 5 image format");
entry->module=AcquireString("MAT");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r M A T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method UnregisterMATImage removes format registrations made by the
% MAT module from the list of supported formats.
%
% The format of the UnregisterMATImage method is:
%
% UnregisterMATImage(void)
%
*/
ModuleExport void UnregisterMATImage(void)
{
(void) UnregisterMagickInfo("MAT");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M A T L A B I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Function WriteMATImage writes an Matlab matrix to a file.
%
% The format of the WriteMATImage method is:
%
% unsigned int WriteMATImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o status: Function WriteMATImage return True if the image is written.
% False is returned is there is a memory shortage or if the image file
% fails to write.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o image: A pointer to an Image structure.
%
*/
static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image)
{
ExceptionInfo
*exception;
ssize_t y;
unsigned z;
const PixelPacket *p;
unsigned int status;
int logging;
size_t DataSize;
char padding;
char MATLAB_HDR[0x80];
time_t current_time;
struct tm local_time;
unsigned char *pixels;
int is_gray;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
(void) logging;
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(MagickFalse);
image->depth=8;
current_time=time((time_t *) NULL);
#if defined(MAGICKCORE_HAVE_LOCALTIME_R)
(void) localtime_r(¤t_time,&local_time);
#else
(void) memcpy(&local_time,localtime(¤t_time),sizeof(local_time));
#endif
(void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124));
FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR),
"MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d",
OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon],
local_time.tm_mday,local_time.tm_hour,local_time.tm_min,
local_time.tm_sec,local_time.tm_year+1900);
MATLAB_HDR[0x7C]=0;
MATLAB_HDR[0x7D]=1;
MATLAB_HDR[0x7E]='I';
MATLAB_HDR[0x7F]='M';
(void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR);
scene=0;
do
{
(void) TransformImageColorspace(image,sRGBColorspace);
is_gray = SetImageGray(image,&image->exception);
z = is_gray ? 0 : 3;
/*
Store MAT header.
*/
DataSize = image->rows /*Y*/ * image->columns /*X*/;
if(!is_gray) DataSize *= 3 /*Z*/;
padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7;
(void) WriteBlobLSBLong(image, miMATRIX);
(void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56));
(void) WriteBlobLSBLong(image, 0x6); /* 0x88 */
(void) WriteBlobLSBLong(image, 0x8); /* 0x8C */
(void) WriteBlobLSBLong(image, 0x6); /* 0x90 */
(void) WriteBlobLSBLong(image, 0);
(void) WriteBlobLSBLong(image, 0x5); /* 0x98 */
(void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */
(void) WriteBlobLSBLong(image, (unsigned int) image->rows); /* x: 0xA0 */
(void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */
if(!is_gray)
{
(void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */
(void) WriteBlobLSBLong(image, 0);
}
(void) WriteBlobLSBShort(image, 1); /* 0xB0 */
(void) WriteBlobLSBShort(image, 1); /* 0xB2 */
(void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */
(void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */
(void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */
/*
Store image data.
*/
exception=(&image->exception);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
do
{
for (y=0; y < (ssize_t)image->columns; y++)
{
p=GetVirtualPixels(image,y,0,1,image->rows,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
z2qtype[z],pixels,exception);
(void) WriteBlob(image,image->rows,pixels);
}
if (!SyncAuthenticPixels(image,exception))
break;
} while(z-- >= 2);
while(padding-->0) (void) WriteBlobByte(image,0);
quantum_info=DestroyQuantumInfo(quantum_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4792_0 |
crossvul-cpp_data_bad_2684_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 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "ip6.h"
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static const char tstr[] = "[|MOBILITY]";
/* Mobility header */
struct ip6_mobility {
uint8_t ip6m_pproto; /* following payload protocol (for PG) */
uint8_t ip6m_len; /* length in units of 8 octets */
uint8_t ip6m_type; /* message type */
uint8_t reserved; /* reserved */
uint16_t ip6m_cksum; /* sum of IPv6 pseudo-header and MH */
union {
uint16_t ip6m_un_data16[1]; /* type-specific field */
uint8_t ip6m_un_data8[2]; /* type-specific field */
} ip6m_dataun;
};
#define ip6m_data16 ip6m_dataun.ip6m_un_data16
#define ip6m_data8 ip6m_dataun.ip6m_un_data8
#define IP6M_MINLEN 8
/* http://www.iana.org/assignments/mobility-parameters/mobility-parameters.xhtml */
/* message type */
#define IP6M_BINDING_REQUEST 0 /* Binding Refresh Request */
#define IP6M_HOME_TEST_INIT 1 /* Home Test Init */
#define IP6M_CAREOF_TEST_INIT 2 /* Care-of Test Init */
#define IP6M_HOME_TEST 3 /* Home Test */
#define IP6M_CAREOF_TEST 4 /* Care-of Test */
#define IP6M_BINDING_UPDATE 5 /* Binding Update */
#define IP6M_BINDING_ACK 6 /* Binding Acknowledgement */
#define IP6M_BINDING_ERROR 7 /* Binding Error */
#define IP6M_MAX 7
static const struct tok ip6m_str[] = {
{ IP6M_BINDING_REQUEST, "BRR" },
{ IP6M_HOME_TEST_INIT, "HoTI" },
{ IP6M_CAREOF_TEST_INIT, "CoTI" },
{ IP6M_HOME_TEST, "HoT" },
{ IP6M_CAREOF_TEST, "CoT" },
{ IP6M_BINDING_UPDATE, "BU" },
{ IP6M_BINDING_ACK, "BA" },
{ IP6M_BINDING_ERROR, "BE" },
{ 0, NULL }
};
static const unsigned ip6m_hdrlen[IP6M_MAX + 1] = {
IP6M_MINLEN, /* IP6M_BINDING_REQUEST */
IP6M_MINLEN + 8, /* IP6M_HOME_TEST_INIT */
IP6M_MINLEN + 8, /* IP6M_CAREOF_TEST_INIT */
IP6M_MINLEN + 16, /* IP6M_HOME_TEST */
IP6M_MINLEN + 16, /* IP6M_CAREOF_TEST */
IP6M_MINLEN + 4, /* IP6M_BINDING_UPDATE */
IP6M_MINLEN + 4, /* IP6M_BINDING_ACK */
IP6M_MINLEN + 16, /* IP6M_BINDING_ERROR */
};
/* Mobility Header Options */
#define IP6MOPT_MINLEN 2
#define IP6MOPT_PAD1 0x0 /* Pad1 */
#define IP6MOPT_PADN 0x1 /* PadN */
#define IP6MOPT_REFRESH 0x2 /* Binding Refresh Advice */
#define IP6MOPT_REFRESH_MINLEN 4
#define IP6MOPT_ALTCOA 0x3 /* Alternate Care-of Address */
#define IP6MOPT_ALTCOA_MINLEN 18
#define IP6MOPT_NONCEID 0x4 /* Nonce Indices */
#define IP6MOPT_NONCEID_MINLEN 6
#define IP6MOPT_AUTH 0x5 /* Binding Authorization Data */
#define IP6MOPT_AUTH_MINLEN 12
static int
mobility_opt_print(netdissect_options *ndo,
const u_char *bp, const unsigned len)
{
unsigned i, optlen;
for (i = 0; i < len; i += optlen) {
ND_TCHECK(bp[i]);
if (bp[i] == IP6MOPT_PAD1)
optlen = 1;
else {
if (i + 1 < len) {
ND_TCHECK(bp[i + 1]);
optlen = bp[i + 1] + 2;
}
else
goto trunc;
}
if (i + optlen > len)
goto trunc;
ND_TCHECK(bp[i + optlen]);
switch (bp[i]) {
case IP6MOPT_PAD1:
ND_PRINT((ndo, "(pad1)"));
break;
case IP6MOPT_PADN:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(padn: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(padn)"));
break;
case IP6MOPT_REFRESH:
if (len - i < IP6MOPT_REFRESH_MINLEN) {
ND_PRINT((ndo, "(refresh: trunc)"));
goto trunc;
}
/* units of 4 secs */
ND_PRINT((ndo, "(refresh: %u)",
EXTRACT_16BITS(&bp[i+2]) << 2));
break;
case IP6MOPT_ALTCOA:
if (len - i < IP6MOPT_ALTCOA_MINLEN) {
ND_PRINT((ndo, "(altcoa: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2])));
break;
case IP6MOPT_NONCEID:
if (len - i < IP6MOPT_NONCEID_MINLEN) {
ND_PRINT((ndo, "(ni: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)",
EXTRACT_16BITS(&bp[i+2]),
EXTRACT_16BITS(&bp[i+4])));
break;
case IP6MOPT_AUTH:
if (len - i < IP6MOPT_AUTH_MINLEN) {
ND_PRINT((ndo, "(auth: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(auth)"));
break;
default:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i]));
goto trunc;
}
ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1]));
break;
}
}
return 0;
trunc:
return 1;
}
/*
* Mobility Header
*/
int
mobility_print(netdissect_options *ndo,
const u_char *bp, const u_char *bp2 _U_)
{
const struct ip6_mobility *mh;
const u_char *ep;
unsigned mhlen, hlen;
uint8_t type;
mh = (const struct ip6_mobility *)bp;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if (!ND_TTEST(mh->ip6m_len)) {
/*
* There's not enough captured data to include the
* mobility header length.
*
* Our caller expects us to return the length, however,
* so return a value that will run to the end of the
* captured data.
*
* XXX - "ip6_print()" doesn't do anything with the
* returned length, however, as it breaks out of the
* header-processing loop.
*/
mhlen = ep - bp;
goto trunc;
}
mhlen = (mh->ip6m_len + 1) << 3;
/* XXX ip6m_cksum */
ND_TCHECK(mh->ip6m_type);
type = mh->ip6m_type;
if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) {
ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type));
goto trunc;
}
ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type)));
switch (type) {
case IP6M_BINDING_REQUEST:
hlen = IP6M_MINLEN;
break;
case IP6M_HOME_TEST_INIT:
case IP6M_CAREOF_TEST_INIT:
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_TCHECK2(*mh, hlen + 8);
ND_PRINT((ndo, " %s Init Cookie=%08x:%08x",
type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
break;
case IP6M_HOME_TEST:
case IP6M_CAREOF_TEST:
ND_TCHECK(mh->ip6m_data16[0]);
ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0])));
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_TCHECK2(*mh, hlen + 8);
ND_PRINT((ndo, " %s Init Cookie=%08x:%08x",
type == IP6M_HOME_TEST ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
if (ndo->ndo_vflag) {
ND_TCHECK2(*mh, hlen + 8);
ND_PRINT((ndo, " %s Keygen Token=%08x:%08x",
type == IP6M_HOME_TEST ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
break;
case IP6M_BINDING_UPDATE:
ND_TCHECK(mh->ip6m_data16[0]);
ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0])));
hlen = IP6M_MINLEN;
ND_TCHECK2(*mh, hlen + 1);
if (bp[hlen] & 0xf0)
ND_PRINT((ndo, " "));
if (bp[hlen] & 0x80)
ND_PRINT((ndo, "A"));
if (bp[hlen] & 0x40)
ND_PRINT((ndo, "H"));
if (bp[hlen] & 0x20)
ND_PRINT((ndo, "L"));
if (bp[hlen] & 0x10)
ND_PRINT((ndo, "K"));
/* Reserved (4bits) */
hlen += 1;
/* Reserved (8bits) */
hlen += 1;
ND_TCHECK2(*mh, hlen + 2);
/* units of 4 secs */
ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2));
hlen += 2;
break;
case IP6M_BINDING_ACK:
ND_TCHECK(mh->ip6m_data8[0]);
ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0]));
if (mh->ip6m_data8[1] & 0x80)
ND_PRINT((ndo, " K"));
/* Reserved (7bits) */
hlen = IP6M_MINLEN;
ND_TCHECK2(*mh, hlen + 2);
ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen])));
hlen += 2;
ND_TCHECK2(*mh, hlen + 2);
/* units of 4 secs */
ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2));
hlen += 2;
break;
case IP6M_BINDING_ERROR:
ND_TCHECK(mh->ip6m_data8[0]);
ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0]));
/* Reserved */
hlen = IP6M_MINLEN;
ND_TCHECK2(*mh, hlen + 16);
ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen])));
hlen += 16;
break;
default:
ND_PRINT((ndo, " len=%u", mh->ip6m_len));
return(mhlen);
break;
}
if (ndo->ndo_vflag)
if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen))
goto trunc;
return(mhlen);
trunc:
ND_PRINT((ndo, "%s", tstr));
return(-1);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2684_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.